xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 // sanity 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   // Sanity 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     std::pair<unsigned, unsigned> Args =
2059         Attrs.getFnAttrs().getVScaleRangeArgs();
2060 
2061     if (Args.first > Args.second && Args.second != 0)
2062       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2063   }
2064 
2065   if (Attrs.hasFnAttr("frame-pointer")) {
2066     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2067     if (FP != "all" && FP != "non-leaf" && FP != "none")
2068       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2069   }
2070 
2071   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2072   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2073   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2074 }
2075 
2076 void Verifier::verifyFunctionMetadata(
2077     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2078   for (const auto &Pair : MDs) {
2079     if (Pair.first == LLVMContext::MD_prof) {
2080       MDNode *MD = Pair.second;
2081       Assert(MD->getNumOperands() >= 2,
2082              "!prof annotations should have no less than 2 operands", MD);
2083 
2084       // Check first operand.
2085       Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
2086              MD);
2087       Assert(isa<MDString>(MD->getOperand(0)),
2088              "expected string with name of the !prof annotation", MD);
2089       MDString *MDS = cast<MDString>(MD->getOperand(0));
2090       StringRef ProfName = MDS->getString();
2091       Assert(ProfName.equals("function_entry_count") ||
2092                  ProfName.equals("synthetic_function_entry_count"),
2093              "first operand should be 'function_entry_count'"
2094              " or 'synthetic_function_entry_count'",
2095              MD);
2096 
2097       // Check second operand.
2098       Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
2099              MD);
2100       Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
2101              "expected integer argument to function_entry_count", MD);
2102     }
2103   }
2104 }
2105 
2106 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
2107   if (!ConstantExprVisited.insert(EntryC).second)
2108     return;
2109 
2110   SmallVector<const Constant *, 16> Stack;
2111   Stack.push_back(EntryC);
2112 
2113   while (!Stack.empty()) {
2114     const Constant *C = Stack.pop_back_val();
2115 
2116     // Check this constant expression.
2117     if (const auto *CE = dyn_cast<ConstantExpr>(C))
2118       visitConstantExpr(CE);
2119 
2120     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
2121       // Global Values get visited separately, but we do need to make sure
2122       // that the global value is in the correct module
2123       Assert(GV->getParent() == &M, "Referencing global in another module!",
2124              EntryC, &M, GV, GV->getParent());
2125       continue;
2126     }
2127 
2128     // Visit all sub-expressions.
2129     for (const Use &U : C->operands()) {
2130       const auto *OpC = dyn_cast<Constant>(U);
2131       if (!OpC)
2132         continue;
2133       if (!ConstantExprVisited.insert(OpC).second)
2134         continue;
2135       Stack.push_back(OpC);
2136     }
2137   }
2138 }
2139 
2140 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
2141   if (CE->getOpcode() == Instruction::BitCast)
2142     Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
2143                                  CE->getType()),
2144            "Invalid bitcast", CE);
2145 }
2146 
2147 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
2148   // There shouldn't be more attribute sets than there are parameters plus the
2149   // function and return value.
2150   return Attrs.getNumAttrSets() <= Params + 2;
2151 }
2152 
2153 /// Verify that statepoint intrinsic is well formed.
2154 void Verifier::verifyStatepoint(const CallBase &Call) {
2155   assert(Call.getCalledFunction() &&
2156          Call.getCalledFunction()->getIntrinsicID() ==
2157              Intrinsic::experimental_gc_statepoint);
2158 
2159   Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
2160              !Call.onlyAccessesArgMemory(),
2161          "gc.statepoint must read and write all memory to preserve "
2162          "reordering restrictions required by safepoint semantics",
2163          Call);
2164 
2165   const int64_t NumPatchBytes =
2166       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
2167   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
2168   Assert(NumPatchBytes >= 0,
2169          "gc.statepoint number of patchable bytes must be "
2170          "positive",
2171          Call);
2172 
2173   const Value *Target = Call.getArgOperand(2);
2174   auto *PT = dyn_cast<PointerType>(Target->getType());
2175   Assert(PT && PT->getElementType()->isFunctionTy(),
2176          "gc.statepoint callee must be of function pointer type", Call, Target);
2177   FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
2178 
2179   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
2180   Assert(NumCallArgs >= 0,
2181          "gc.statepoint number of arguments to underlying call "
2182          "must be positive",
2183          Call);
2184   const int NumParams = (int)TargetFuncType->getNumParams();
2185   if (TargetFuncType->isVarArg()) {
2186     Assert(NumCallArgs >= NumParams,
2187            "gc.statepoint mismatch in number of vararg call args", Call);
2188 
2189     // TODO: Remove this limitation
2190     Assert(TargetFuncType->getReturnType()->isVoidTy(),
2191            "gc.statepoint doesn't support wrapping non-void "
2192            "vararg functions yet",
2193            Call);
2194   } else
2195     Assert(NumCallArgs == NumParams,
2196            "gc.statepoint mismatch in number of call args", Call);
2197 
2198   const uint64_t Flags
2199     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
2200   Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2201          "unknown flag used in gc.statepoint flags argument", Call);
2202 
2203   // Verify that the types of the call parameter arguments match
2204   // the type of the wrapped callee.
2205   AttributeList Attrs = Call.getAttributes();
2206   for (int i = 0; i < NumParams; i++) {
2207     Type *ParamType = TargetFuncType->getParamType(i);
2208     Type *ArgType = Call.getArgOperand(5 + i)->getType();
2209     Assert(ArgType == ParamType,
2210            "gc.statepoint call argument does not match wrapped "
2211            "function type",
2212            Call);
2213 
2214     if (TargetFuncType->isVarArg()) {
2215       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
2216       Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
2217              "Attribute 'sret' cannot be used for vararg call arguments!",
2218              Call);
2219     }
2220   }
2221 
2222   const int EndCallArgsInx = 4 + NumCallArgs;
2223 
2224   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
2225   Assert(isa<ConstantInt>(NumTransitionArgsV),
2226          "gc.statepoint number of transition arguments "
2227          "must be constant integer",
2228          Call);
2229   const int NumTransitionArgs =
2230       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2231   Assert(NumTransitionArgs == 0,
2232          "gc.statepoint w/inline transition bundle is deprecated", Call);
2233   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2234 
2235   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
2236   Assert(isa<ConstantInt>(NumDeoptArgsV),
2237          "gc.statepoint number of deoptimization arguments "
2238          "must be constant integer",
2239          Call);
2240   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2241   Assert(NumDeoptArgs == 0,
2242          "gc.statepoint w/inline deopt operands is deprecated", Call);
2243 
2244   const int ExpectedNumArgs = 7 + NumCallArgs;
2245   Assert(ExpectedNumArgs == (int)Call.arg_size(),
2246          "gc.statepoint too many arguments", Call);
2247 
2248   // Check that the only uses of this gc.statepoint are gc.result or
2249   // gc.relocate calls which are tied to this statepoint and thus part
2250   // of the same statepoint sequence
2251   for (const User *U : Call.users()) {
2252     const CallInst *UserCall = dyn_cast<const CallInst>(U);
2253     Assert(UserCall, "illegal use of statepoint token", Call, U);
2254     if (!UserCall)
2255       continue;
2256     Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2257            "gc.result or gc.relocate are the only value uses "
2258            "of a gc.statepoint",
2259            Call, U);
2260     if (isa<GCResultInst>(UserCall)) {
2261       Assert(UserCall->getArgOperand(0) == &Call,
2262              "gc.result connected to wrong gc.statepoint", Call, UserCall);
2263     } else if (isa<GCRelocateInst>(Call)) {
2264       Assert(UserCall->getArgOperand(0) == &Call,
2265              "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2266     }
2267   }
2268 
2269   // Note: It is legal for a single derived pointer to be listed multiple
2270   // times.  It's non-optimal, but it is legal.  It can also happen after
2271   // insertion if we strip a bitcast away.
2272   // Note: It is really tempting to check that each base is relocated and
2273   // that a derived pointer is never reused as a base pointer.  This turns
2274   // out to be problematic since optimizations run after safepoint insertion
2275   // can recognize equality properties that the insertion logic doesn't know
2276   // about.  See example statepoint.ll in the verifier subdirectory
2277 }
2278 
2279 void Verifier::verifyFrameRecoverIndices() {
2280   for (auto &Counts : FrameEscapeInfo) {
2281     Function *F = Counts.first;
2282     unsigned EscapedObjectCount = Counts.second.first;
2283     unsigned MaxRecoveredIndex = Counts.second.second;
2284     Assert(MaxRecoveredIndex <= EscapedObjectCount,
2285            "all indices passed to llvm.localrecover must be less than the "
2286            "number of arguments passed to llvm.localescape in the parent "
2287            "function",
2288            F);
2289   }
2290 }
2291 
2292 static Instruction *getSuccPad(Instruction *Terminator) {
2293   BasicBlock *UnwindDest;
2294   if (auto *II = dyn_cast<InvokeInst>(Terminator))
2295     UnwindDest = II->getUnwindDest();
2296   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2297     UnwindDest = CSI->getUnwindDest();
2298   else
2299     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2300   return UnwindDest->getFirstNonPHI();
2301 }
2302 
2303 void Verifier::verifySiblingFuncletUnwinds() {
2304   SmallPtrSet<Instruction *, 8> Visited;
2305   SmallPtrSet<Instruction *, 8> Active;
2306   for (const auto &Pair : SiblingFuncletInfo) {
2307     Instruction *PredPad = Pair.first;
2308     if (Visited.count(PredPad))
2309       continue;
2310     Active.insert(PredPad);
2311     Instruction *Terminator = Pair.second;
2312     do {
2313       Instruction *SuccPad = getSuccPad(Terminator);
2314       if (Active.count(SuccPad)) {
2315         // Found a cycle; report error
2316         Instruction *CyclePad = SuccPad;
2317         SmallVector<Instruction *, 8> CycleNodes;
2318         do {
2319           CycleNodes.push_back(CyclePad);
2320           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2321           if (CycleTerminator != CyclePad)
2322             CycleNodes.push_back(CycleTerminator);
2323           CyclePad = getSuccPad(CycleTerminator);
2324         } while (CyclePad != SuccPad);
2325         Assert(false, "EH pads can't handle each other's exceptions",
2326                ArrayRef<Instruction *>(CycleNodes));
2327       }
2328       // Don't re-walk a node we've already checked
2329       if (!Visited.insert(SuccPad).second)
2330         break;
2331       // Walk to this successor if it has a map entry.
2332       PredPad = SuccPad;
2333       auto TermI = SiblingFuncletInfo.find(PredPad);
2334       if (TermI == SiblingFuncletInfo.end())
2335         break;
2336       Terminator = TermI->second;
2337       Active.insert(PredPad);
2338     } while (true);
2339     // Each node only has one successor, so we've walked all the active
2340     // nodes' successors.
2341     Active.clear();
2342   }
2343 }
2344 
2345 // visitFunction - Verify that a function is ok.
2346 //
2347 void Verifier::visitFunction(const Function &F) {
2348   visitGlobalValue(F);
2349 
2350   // Check function arguments.
2351   FunctionType *FT = F.getFunctionType();
2352   unsigned NumArgs = F.arg_size();
2353 
2354   Assert(&Context == &F.getContext(),
2355          "Function context does not match Module context!", &F);
2356 
2357   Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
2358   Assert(FT->getNumParams() == NumArgs,
2359          "# formal arguments must match # of arguments for function type!", &F,
2360          FT);
2361   Assert(F.getReturnType()->isFirstClassType() ||
2362              F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2363          "Functions cannot return aggregate values!", &F);
2364 
2365   Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2366          "Invalid struct return type!", &F);
2367 
2368   AttributeList Attrs = F.getAttributes();
2369 
2370   Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
2371          "Attribute after last parameter!", &F);
2372 
2373   bool IsIntrinsic = F.isIntrinsic();
2374 
2375   // Check function attributes.
2376   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic);
2377 
2378   // On function declarations/definitions, we do not support the builtin
2379   // attribute. We do not check this in VerifyFunctionAttrs since that is
2380   // checking for Attributes that can/can not ever be on functions.
2381   Assert(!Attrs.hasFnAttr(Attribute::Builtin),
2382          "Attribute 'builtin' can only be applied to a callsite.", &F);
2383 
2384   Assert(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2385          "Attribute 'elementtype' can only be applied to a callsite.", &F);
2386 
2387   // Check that this function meets the restrictions on this calling convention.
2388   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2389   // restrictions can be lifted.
2390   switch (F.getCallingConv()) {
2391   default:
2392   case CallingConv::C:
2393     break;
2394   case CallingConv::X86_INTR: {
2395     Assert(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2396            "Calling convention parameter requires byval", &F);
2397     break;
2398   }
2399   case CallingConv::AMDGPU_KERNEL:
2400   case CallingConv::SPIR_KERNEL:
2401     Assert(F.getReturnType()->isVoidTy(),
2402            "Calling convention requires void return type", &F);
2403     LLVM_FALLTHROUGH;
2404   case CallingConv::AMDGPU_VS:
2405   case CallingConv::AMDGPU_HS:
2406   case CallingConv::AMDGPU_GS:
2407   case CallingConv::AMDGPU_PS:
2408   case CallingConv::AMDGPU_CS:
2409     Assert(!F.hasStructRetAttr(),
2410            "Calling convention does not allow sret", &F);
2411     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2412       const unsigned StackAS = DL.getAllocaAddrSpace();
2413       unsigned i = 0;
2414       for (const Argument &Arg : F.args()) {
2415         Assert(!Attrs.hasParamAttr(i, Attribute::ByVal),
2416                "Calling convention disallows byval", &F);
2417         Assert(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2418                "Calling convention disallows preallocated", &F);
2419         Assert(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2420                "Calling convention disallows inalloca", &F);
2421 
2422         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2423           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2424           // value here.
2425           Assert(Arg.getType()->getPointerAddressSpace() != StackAS,
2426                  "Calling convention disallows stack byref", &F);
2427         }
2428 
2429         ++i;
2430       }
2431     }
2432 
2433     LLVM_FALLTHROUGH;
2434   case CallingConv::Fast:
2435   case CallingConv::Cold:
2436   case CallingConv::Intel_OCL_BI:
2437   case CallingConv::PTX_Kernel:
2438   case CallingConv::PTX_Device:
2439     Assert(!F.isVarArg(), "Calling convention does not support varargs or "
2440                           "perfect forwarding!",
2441            &F);
2442     break;
2443   }
2444 
2445   // Check that the argument values match the function type for this function...
2446   unsigned i = 0;
2447   for (const Argument &Arg : F.args()) {
2448     Assert(Arg.getType() == FT->getParamType(i),
2449            "Argument value does not match function argument type!", &Arg,
2450            FT->getParamType(i));
2451     Assert(Arg.getType()->isFirstClassType(),
2452            "Function arguments must have first-class types!", &Arg);
2453     if (!IsIntrinsic) {
2454       Assert(!Arg.getType()->isMetadataTy(),
2455              "Function takes metadata but isn't an intrinsic", &Arg, &F);
2456       Assert(!Arg.getType()->isTokenTy(),
2457              "Function takes token but isn't an intrinsic", &Arg, &F);
2458       Assert(!Arg.getType()->isX86_AMXTy(),
2459              "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
2460     }
2461 
2462     // Check that swifterror argument is only used by loads and stores.
2463     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2464       verifySwiftErrorValue(&Arg);
2465     }
2466     ++i;
2467   }
2468 
2469   if (!IsIntrinsic) {
2470     Assert(!F.getReturnType()->isTokenTy(),
2471            "Function returns a token but isn't an intrinsic", &F);
2472     Assert(!F.getReturnType()->isX86_AMXTy(),
2473            "Function returns a x86_amx but isn't an intrinsic", &F);
2474   }
2475 
2476   // Get the function metadata attachments.
2477   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2478   F.getAllMetadata(MDs);
2479   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
2480   verifyFunctionMetadata(MDs);
2481 
2482   // Check validity of the personality function
2483   if (F.hasPersonalityFn()) {
2484     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2485     if (Per)
2486       Assert(Per->getParent() == F.getParent(),
2487              "Referencing personality function in another module!",
2488              &F, F.getParent(), Per, Per->getParent());
2489   }
2490 
2491   if (F.isMaterializable()) {
2492     // Function has a body somewhere we can't see.
2493     Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2494            MDs.empty() ? nullptr : MDs.front().second);
2495   } else if (F.isDeclaration()) {
2496     for (const auto &I : MDs) {
2497       // This is used for call site debug information.
2498       AssertDI(I.first != LLVMContext::MD_dbg ||
2499                    !cast<DISubprogram>(I.second)->isDistinct(),
2500                "function declaration may only have a unique !dbg attachment",
2501                &F);
2502       Assert(I.first != LLVMContext::MD_prof,
2503              "function declaration may not have a !prof attachment", &F);
2504 
2505       // Verify the metadata itself.
2506       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
2507     }
2508     Assert(!F.hasPersonalityFn(),
2509            "Function declaration shouldn't have a personality routine", &F);
2510   } else {
2511     // Verify that this function (which has a body) is not named "llvm.*".  It
2512     // is not legal to define intrinsics.
2513     Assert(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
2514 
2515     // Check the entry node
2516     const BasicBlock *Entry = &F.getEntryBlock();
2517     Assert(pred_empty(Entry),
2518            "Entry block to function must not have predecessors!", Entry);
2519 
2520     // The address of the entry block cannot be taken, unless it is dead.
2521     if (Entry->hasAddressTaken()) {
2522       Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
2523              "blockaddress may not be used with the entry block!", Entry);
2524     }
2525 
2526     unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2527     // Visit metadata attachments.
2528     for (const auto &I : MDs) {
2529       // Verify that the attachment is legal.
2530       auto AllowLocs = AreDebugLocsAllowed::No;
2531       switch (I.first) {
2532       default:
2533         break;
2534       case LLVMContext::MD_dbg: {
2535         ++NumDebugAttachments;
2536         AssertDI(NumDebugAttachments == 1,
2537                  "function must have a single !dbg attachment", &F, I.second);
2538         AssertDI(isa<DISubprogram>(I.second),
2539                  "function !dbg attachment must be a subprogram", &F, I.second);
2540         AssertDI(cast<DISubprogram>(I.second)->isDistinct(),
2541                  "function definition may only have a distinct !dbg attachment",
2542                  &F);
2543 
2544         auto *SP = cast<DISubprogram>(I.second);
2545         const Function *&AttachedTo = DISubprogramAttachments[SP];
2546         AssertDI(!AttachedTo || AttachedTo == &F,
2547                  "DISubprogram attached to more than one function", SP, &F);
2548         AttachedTo = &F;
2549         AllowLocs = AreDebugLocsAllowed::Yes;
2550         break;
2551       }
2552       case LLVMContext::MD_prof:
2553         ++NumProfAttachments;
2554         Assert(NumProfAttachments == 1,
2555                "function must have a single !prof attachment", &F, I.second);
2556         break;
2557       }
2558 
2559       // Verify the metadata itself.
2560       visitMDNode(*I.second, AllowLocs);
2561     }
2562   }
2563 
2564   // If this function is actually an intrinsic, verify that it is only used in
2565   // direct call/invokes, never having its "address taken".
2566   // Only do this if the module is materialized, otherwise we don't have all the
2567   // uses.
2568   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
2569     const User *U;
2570     if (F.hasAddressTaken(&U, false, true, false,
2571                           /*IgnoreARCAttachedCall=*/true))
2572       Assert(false, "Invalid user of intrinsic instruction!", U);
2573   }
2574 
2575   // Check intrinsics' signatures.
2576   switch (F.getIntrinsicID()) {
2577   case Intrinsic::experimental_gc_get_pointer_base: {
2578     FunctionType *FT = F.getFunctionType();
2579     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2580     Assert(isa<PointerType>(F.getReturnType()),
2581            "gc.get.pointer.base must return a pointer", F);
2582     Assert(FT->getParamType(0) == F.getReturnType(),
2583            "gc.get.pointer.base operand and result must be of the same type",
2584            F);
2585     break;
2586   }
2587   case Intrinsic::experimental_gc_get_pointer_offset: {
2588     FunctionType *FT = F.getFunctionType();
2589     Assert(FT->getNumParams() == 1, "wrong number of parameters", F);
2590     Assert(isa<PointerType>(FT->getParamType(0)),
2591            "gc.get.pointer.offset operand must be a pointer", F);
2592     Assert(F.getReturnType()->isIntegerTy(),
2593            "gc.get.pointer.offset must return integer", F);
2594     break;
2595   }
2596   }
2597 
2598   auto *N = F.getSubprogram();
2599   HasDebugInfo = (N != nullptr);
2600   if (!HasDebugInfo)
2601     return;
2602 
2603   // Check that all !dbg attachments lead to back to N.
2604   //
2605   // FIXME: Check this incrementally while visiting !dbg attachments.
2606   // FIXME: Only check when N is the canonical subprogram for F.
2607   SmallPtrSet<const MDNode *, 32> Seen;
2608   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
2609     // Be careful about using DILocation here since we might be dealing with
2610     // broken code (this is the Verifier after all).
2611     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
2612     if (!DL)
2613       return;
2614     if (!Seen.insert(DL).second)
2615       return;
2616 
2617     Metadata *Parent = DL->getRawScope();
2618     AssertDI(Parent && isa<DILocalScope>(Parent),
2619              "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
2620              Parent);
2621 
2622     DILocalScope *Scope = DL->getInlinedAtScope();
2623     Assert(Scope, "Failed to find DILocalScope", DL);
2624 
2625     if (!Seen.insert(Scope).second)
2626       return;
2627 
2628     DISubprogram *SP = Scope->getSubprogram();
2629 
2630     // Scope and SP could be the same MDNode and we don't want to skip
2631     // validation in that case
2632     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
2633       return;
2634 
2635     AssertDI(SP->describes(&F),
2636              "!dbg attachment points at wrong subprogram for function", N, &F,
2637              &I, DL, Scope, SP);
2638   };
2639   for (auto &BB : F)
2640     for (auto &I : BB) {
2641       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
2642       // The llvm.loop annotations also contain two DILocations.
2643       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
2644         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
2645           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2646       if (BrokenDebugInfo)
2647         return;
2648     }
2649 }
2650 
2651 // verifyBasicBlock - Verify that a basic block is well formed...
2652 //
2653 void Verifier::visitBasicBlock(BasicBlock &BB) {
2654   InstsInThisBlock.clear();
2655 
2656   // Ensure that basic blocks have terminators!
2657   Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
2658 
2659   // Check constraints that this basic block imposes on all of the PHI nodes in
2660   // it.
2661   if (isa<PHINode>(BB.front())) {
2662     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
2663     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
2664     llvm::sort(Preds);
2665     for (const PHINode &PN : BB.phis()) {
2666       Assert(PN.getNumIncomingValues() == Preds.size(),
2667              "PHINode should have one entry for each predecessor of its "
2668              "parent basic block!",
2669              &PN);
2670 
2671       // Get and sort all incoming values in the PHI node...
2672       Values.clear();
2673       Values.reserve(PN.getNumIncomingValues());
2674       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2675         Values.push_back(
2676             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2677       llvm::sort(Values);
2678 
2679       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2680         // Check to make sure that if there is more than one entry for a
2681         // particular basic block in this PHI node, that the incoming values are
2682         // all identical.
2683         //
2684         Assert(i == 0 || Values[i].first != Values[i - 1].first ||
2685                    Values[i].second == Values[i - 1].second,
2686                "PHI node has multiple entries for the same basic block with "
2687                "different incoming values!",
2688                &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2689 
2690         // Check to make sure that the predecessors and PHI node entries are
2691         // matched up.
2692         Assert(Values[i].first == Preds[i],
2693                "PHI node entries do not match predecessors!", &PN,
2694                Values[i].first, Preds[i]);
2695       }
2696     }
2697   }
2698 
2699   // Check that all instructions have their parent pointers set up correctly.
2700   for (auto &I : BB)
2701   {
2702     Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2703   }
2704 }
2705 
2706 void Verifier::visitTerminator(Instruction &I) {
2707   // Ensure that terminators only exist at the end of the basic block.
2708   Assert(&I == I.getParent()->getTerminator(),
2709          "Terminator found in the middle of a basic block!", I.getParent());
2710   visitInstruction(I);
2711 }
2712 
2713 void Verifier::visitBranchInst(BranchInst &BI) {
2714   if (BI.isConditional()) {
2715     Assert(BI.getCondition()->getType()->isIntegerTy(1),
2716            "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2717   }
2718   visitTerminator(BI);
2719 }
2720 
2721 void Verifier::visitReturnInst(ReturnInst &RI) {
2722   Function *F = RI.getParent()->getParent();
2723   unsigned N = RI.getNumOperands();
2724   if (F->getReturnType()->isVoidTy())
2725     Assert(N == 0,
2726            "Found return instr that returns non-void in Function of void "
2727            "return type!",
2728            &RI, F->getReturnType());
2729   else
2730     Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2731            "Function return type does not match operand "
2732            "type of return inst!",
2733            &RI, F->getReturnType());
2734 
2735   // Check to make sure that the return value has necessary properties for
2736   // terminators...
2737   visitTerminator(RI);
2738 }
2739 
2740 void Verifier::visitSwitchInst(SwitchInst &SI) {
2741   Assert(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
2742   // Check to make sure that all of the constants in the switch instruction
2743   // have the same type as the switched-on value.
2744   Type *SwitchTy = SI.getCondition()->getType();
2745   SmallPtrSet<ConstantInt*, 32> Constants;
2746   for (auto &Case : SI.cases()) {
2747     Assert(Case.getCaseValue()->getType() == SwitchTy,
2748            "Switch constants must all be same type as switch value!", &SI);
2749     Assert(Constants.insert(Case.getCaseValue()).second,
2750            "Duplicate integer as switch case", &SI, Case.getCaseValue());
2751   }
2752 
2753   visitTerminator(SI);
2754 }
2755 
2756 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2757   Assert(BI.getAddress()->getType()->isPointerTy(),
2758          "Indirectbr operand must have pointer type!", &BI);
2759   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2760     Assert(BI.getDestination(i)->getType()->isLabelTy(),
2761            "Indirectbr destinations must all have pointer type!", &BI);
2762 
2763   visitTerminator(BI);
2764 }
2765 
2766 void Verifier::visitCallBrInst(CallBrInst &CBI) {
2767   Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!",
2768          &CBI);
2769   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
2770   Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed");
2771   for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i)
2772     Assert(CBI.getSuccessor(i)->getType()->isLabelTy(),
2773            "Callbr successors must all have pointer type!", &CBI);
2774   for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) {
2775     Assert(i >= CBI.arg_size() || !isa<BasicBlock>(CBI.getOperand(i)),
2776            "Using an unescaped label as a callbr argument!", &CBI);
2777     if (isa<BasicBlock>(CBI.getOperand(i)))
2778       for (unsigned j = i + 1; j != e; ++j)
2779         Assert(CBI.getOperand(i) != CBI.getOperand(j),
2780                "Duplicate callbr destination!", &CBI);
2781   }
2782   {
2783     SmallPtrSet<BasicBlock *, 4> ArgBBs;
2784     for (Value *V : CBI.args())
2785       if (auto *BA = dyn_cast<BlockAddress>(V))
2786         ArgBBs.insert(BA->getBasicBlock());
2787     for (BasicBlock *BB : CBI.getIndirectDests())
2788       Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI);
2789   }
2790 
2791   visitTerminator(CBI);
2792 }
2793 
2794 void Verifier::visitSelectInst(SelectInst &SI) {
2795   Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2796                                          SI.getOperand(2)),
2797          "Invalid operands for select instruction!", &SI);
2798 
2799   Assert(SI.getTrueValue()->getType() == SI.getType(),
2800          "Select values must have same type as select instruction!", &SI);
2801   visitInstruction(SI);
2802 }
2803 
2804 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2805 /// a pass, if any exist, it's an error.
2806 ///
2807 void Verifier::visitUserOp1(Instruction &I) {
2808   Assert(false, "User-defined operators should not live outside of a pass!", &I);
2809 }
2810 
2811 void Verifier::visitTruncInst(TruncInst &I) {
2812   // Get the source and destination types
2813   Type *SrcTy = I.getOperand(0)->getType();
2814   Type *DestTy = I.getType();
2815 
2816   // Get the size of the types in bits, we'll need this later
2817   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2818   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2819 
2820   Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2821   Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2822   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2823          "trunc source and destination must both be a vector or neither", &I);
2824   Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2825 
2826   visitInstruction(I);
2827 }
2828 
2829 void Verifier::visitZExtInst(ZExtInst &I) {
2830   // Get the source and destination types
2831   Type *SrcTy = I.getOperand(0)->getType();
2832   Type *DestTy = I.getType();
2833 
2834   // Get the size of the types in bits, we'll need this later
2835   Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2836   Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2837   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2838          "zext source and destination must both be a vector or neither", &I);
2839   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2840   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2841 
2842   Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2843 
2844   visitInstruction(I);
2845 }
2846 
2847 void Verifier::visitSExtInst(SExtInst &I) {
2848   // Get the source and destination types
2849   Type *SrcTy = I.getOperand(0)->getType();
2850   Type *DestTy = I.getType();
2851 
2852   // Get the size of the types in bits, we'll need this later
2853   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2854   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2855 
2856   Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2857   Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2858   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2859          "sext source and destination must both be a vector or neither", &I);
2860   Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2861 
2862   visitInstruction(I);
2863 }
2864 
2865 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2866   // Get the source and destination types
2867   Type *SrcTy = I.getOperand(0)->getType();
2868   Type *DestTy = I.getType();
2869   // Get the size of the types in bits, we'll need this later
2870   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2871   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2872 
2873   Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2874   Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2875   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2876          "fptrunc source and destination must both be a vector or neither", &I);
2877   Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2878 
2879   visitInstruction(I);
2880 }
2881 
2882 void Verifier::visitFPExtInst(FPExtInst &I) {
2883   // Get the source and destination types
2884   Type *SrcTy = I.getOperand(0)->getType();
2885   Type *DestTy = I.getType();
2886 
2887   // Get the size of the types in bits, we'll need this later
2888   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2889   unsigned DestBitSize = DestTy->getScalarSizeInBits();
2890 
2891   Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2892   Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2893   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2894          "fpext source and destination must both be a vector or neither", &I);
2895   Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2896 
2897   visitInstruction(I);
2898 }
2899 
2900 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2901   // Get the source and destination types
2902   Type *SrcTy = I.getOperand(0)->getType();
2903   Type *DestTy = I.getType();
2904 
2905   bool SrcVec = SrcTy->isVectorTy();
2906   bool DstVec = DestTy->isVectorTy();
2907 
2908   Assert(SrcVec == DstVec,
2909          "UIToFP source and dest must both be vector or scalar", &I);
2910   Assert(SrcTy->isIntOrIntVectorTy(),
2911          "UIToFP source must be integer or integer vector", &I);
2912   Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2913          &I);
2914 
2915   if (SrcVec && DstVec)
2916     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2917                cast<VectorType>(DestTy)->getElementCount(),
2918            "UIToFP source and dest vector length mismatch", &I);
2919 
2920   visitInstruction(I);
2921 }
2922 
2923 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2924   // Get the source and destination types
2925   Type *SrcTy = I.getOperand(0)->getType();
2926   Type *DestTy = I.getType();
2927 
2928   bool SrcVec = SrcTy->isVectorTy();
2929   bool DstVec = DestTy->isVectorTy();
2930 
2931   Assert(SrcVec == DstVec,
2932          "SIToFP source and dest must both be vector or scalar", &I);
2933   Assert(SrcTy->isIntOrIntVectorTy(),
2934          "SIToFP source must be integer or integer vector", &I);
2935   Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2936          &I);
2937 
2938   if (SrcVec && DstVec)
2939     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2940                cast<VectorType>(DestTy)->getElementCount(),
2941            "SIToFP source and dest vector length mismatch", &I);
2942 
2943   visitInstruction(I);
2944 }
2945 
2946 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2947   // Get the source and destination types
2948   Type *SrcTy = I.getOperand(0)->getType();
2949   Type *DestTy = I.getType();
2950 
2951   bool SrcVec = SrcTy->isVectorTy();
2952   bool DstVec = DestTy->isVectorTy();
2953 
2954   Assert(SrcVec == DstVec,
2955          "FPToUI source and dest must both be vector or scalar", &I);
2956   Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2957          &I);
2958   Assert(DestTy->isIntOrIntVectorTy(),
2959          "FPToUI result must be integer or integer vector", &I);
2960 
2961   if (SrcVec && DstVec)
2962     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2963                cast<VectorType>(DestTy)->getElementCount(),
2964            "FPToUI source and dest vector length mismatch", &I);
2965 
2966   visitInstruction(I);
2967 }
2968 
2969 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2970   // Get the source and destination types
2971   Type *SrcTy = I.getOperand(0)->getType();
2972   Type *DestTy = I.getType();
2973 
2974   bool SrcVec = SrcTy->isVectorTy();
2975   bool DstVec = DestTy->isVectorTy();
2976 
2977   Assert(SrcVec == DstVec,
2978          "FPToSI source and dest must both be vector or scalar", &I);
2979   Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2980          &I);
2981   Assert(DestTy->isIntOrIntVectorTy(),
2982          "FPToSI result must be integer or integer vector", &I);
2983 
2984   if (SrcVec && DstVec)
2985     Assert(cast<VectorType>(SrcTy)->getElementCount() ==
2986                cast<VectorType>(DestTy)->getElementCount(),
2987            "FPToSI source and dest vector length mismatch", &I);
2988 
2989   visitInstruction(I);
2990 }
2991 
2992 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2993   // Get the source and destination types
2994   Type *SrcTy = I.getOperand(0)->getType();
2995   Type *DestTy = I.getType();
2996 
2997   Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
2998 
2999   Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
3000   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
3001          &I);
3002 
3003   if (SrcTy->isVectorTy()) {
3004     auto *VSrc = cast<VectorType>(SrcTy);
3005     auto *VDest = cast<VectorType>(DestTy);
3006     Assert(VSrc->getElementCount() == VDest->getElementCount(),
3007            "PtrToInt Vector width mismatch", &I);
3008   }
3009 
3010   visitInstruction(I);
3011 }
3012 
3013 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
3014   // Get the source and destination types
3015   Type *SrcTy = I.getOperand(0)->getType();
3016   Type *DestTy = I.getType();
3017 
3018   Assert(SrcTy->isIntOrIntVectorTy(),
3019          "IntToPtr source must be an integral", &I);
3020   Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
3021 
3022   Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
3023          &I);
3024   if (SrcTy->isVectorTy()) {
3025     auto *VSrc = cast<VectorType>(SrcTy);
3026     auto *VDest = cast<VectorType>(DestTy);
3027     Assert(VSrc->getElementCount() == VDest->getElementCount(),
3028            "IntToPtr Vector width mismatch", &I);
3029   }
3030   visitInstruction(I);
3031 }
3032 
3033 void Verifier::visitBitCastInst(BitCastInst &I) {
3034   Assert(
3035       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
3036       "Invalid bitcast", &I);
3037   visitInstruction(I);
3038 }
3039 
3040 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
3041   Type *SrcTy = I.getOperand(0)->getType();
3042   Type *DestTy = I.getType();
3043 
3044   Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
3045          &I);
3046   Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
3047          &I);
3048   Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
3049          "AddrSpaceCast must be between different address spaces", &I);
3050   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3051     Assert(SrcVTy->getElementCount() ==
3052                cast<VectorType>(DestTy)->getElementCount(),
3053            "AddrSpaceCast vector pointer number of elements mismatch", &I);
3054   visitInstruction(I);
3055 }
3056 
3057 /// visitPHINode - Ensure that a PHI node is well formed.
3058 ///
3059 void Verifier::visitPHINode(PHINode &PN) {
3060   // Ensure that the PHI nodes are all grouped together at the top of the block.
3061   // This can be tested by checking whether the instruction before this is
3062   // either nonexistent (because this is begin()) or is a PHI node.  If not,
3063   // then there is some other instruction before a PHI.
3064   Assert(&PN == &PN.getParent()->front() ||
3065              isa<PHINode>(--BasicBlock::iterator(&PN)),
3066          "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
3067 
3068   // Check that a PHI doesn't yield a Token.
3069   Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
3070 
3071   // Check that all of the values of the PHI node have the same type as the
3072   // result, and that the incoming blocks are really basic blocks.
3073   for (Value *IncValue : PN.incoming_values()) {
3074     Assert(PN.getType() == IncValue->getType(),
3075            "PHI node operands are not the same type as the result!", &PN);
3076   }
3077 
3078   // All other PHI node constraints are checked in the visitBasicBlock method.
3079 
3080   visitInstruction(PN);
3081 }
3082 
3083 void Verifier::visitCallBase(CallBase &Call) {
3084   Assert(Call.getCalledOperand()->getType()->isPointerTy(),
3085          "Called function must be a pointer!", Call);
3086   PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
3087 
3088   Assert(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
3089          "Called function is not the same type as the call!", Call);
3090 
3091   FunctionType *FTy = Call.getFunctionType();
3092 
3093   // Verify that the correct number of arguments are being passed
3094   if (FTy->isVarArg())
3095     Assert(Call.arg_size() >= FTy->getNumParams(),
3096            "Called function requires more parameters than were provided!",
3097            Call);
3098   else
3099     Assert(Call.arg_size() == FTy->getNumParams(),
3100            "Incorrect number of arguments passed to called function!", Call);
3101 
3102   // Verify that all arguments to the call match the function type.
3103   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3104     Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3105            "Call parameter type does not match function signature!",
3106            Call.getArgOperand(i), FTy->getParamType(i), Call);
3107 
3108   AttributeList Attrs = Call.getAttributes();
3109 
3110   Assert(verifyAttributeCount(Attrs, Call.arg_size()),
3111          "Attribute after last parameter!", Call);
3112 
3113   Function *Callee =
3114       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3115   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3116   if (IsIntrinsic)
3117     Assert(Callee->getValueType() == FTy,
3118            "Intrinsic called with incompatible signature", Call);
3119 
3120   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
3121     // Don't allow speculatable on call sites, unless the underlying function
3122     // declaration is also speculatable.
3123     Assert(Callee && Callee->isSpeculatable(),
3124            "speculatable attribute may not apply to call sites", Call);
3125   }
3126 
3127   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
3128     Assert(Call.getCalledFunction()->getIntrinsicID() ==
3129                Intrinsic::call_preallocated_arg,
3130            "preallocated as a call site attribute can only be on "
3131            "llvm.call.preallocated.arg");
3132   }
3133 
3134   // Verify call attributes.
3135   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
3136 
3137   // Conservatively check the inalloca argument.
3138   // We have a bug if we can find that there is an underlying alloca without
3139   // inalloca.
3140   if (Call.hasInAllocaArgument()) {
3141     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
3142     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
3143       Assert(AI->isUsedWithInAlloca(),
3144              "inalloca argument for call has mismatched alloca", AI, Call);
3145   }
3146 
3147   // For each argument of the callsite, if it has the swifterror argument,
3148   // make sure the underlying alloca/parameter it comes from has a swifterror as
3149   // well.
3150   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3151     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
3152       Value *SwiftErrorArg = Call.getArgOperand(i);
3153       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
3154         Assert(AI->isSwiftError(),
3155                "swifterror argument for call has mismatched alloca", AI, Call);
3156         continue;
3157       }
3158       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3159       Assert(ArgI,
3160              "swifterror argument should come from an alloca or parameter",
3161              SwiftErrorArg, Call);
3162       Assert(ArgI->hasSwiftErrorAttr(),
3163              "swifterror argument for call has mismatched parameter", ArgI,
3164              Call);
3165     }
3166 
3167     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3168       // Don't allow immarg on call sites, unless the underlying declaration
3169       // also has the matching immarg.
3170       Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
3171              "immarg may not apply only to call sites",
3172              Call.getArgOperand(i), Call);
3173     }
3174 
3175     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
3176       Value *ArgVal = Call.getArgOperand(i);
3177       Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3178              "immarg operand has non-immediate parameter", ArgVal, Call);
3179     }
3180 
3181     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
3182       Value *ArgVal = Call.getArgOperand(i);
3183       bool hasOB =
3184           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
3185       bool isMustTail = Call.isMustTailCall();
3186       Assert(hasOB != isMustTail,
3187              "preallocated operand either requires a preallocated bundle or "
3188              "the call to be musttail (but not both)",
3189              ArgVal, Call);
3190     }
3191   }
3192 
3193   if (FTy->isVarArg()) {
3194     // FIXME? is 'nest' even legal here?
3195     bool SawNest = false;
3196     bool SawReturned = false;
3197 
3198     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3199       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
3200         SawNest = true;
3201       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
3202         SawReturned = true;
3203     }
3204 
3205     // Check attributes on the varargs part.
3206     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
3207       Type *Ty = Call.getArgOperand(Idx)->getType();
3208       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
3209       verifyParameterAttrs(ArgAttrs, Ty, &Call);
3210 
3211       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
3212         Assert(!SawNest, "More than one parameter has attribute nest!", Call);
3213         SawNest = true;
3214       }
3215 
3216       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
3217         Assert(!SawReturned, "More than one parameter has attribute returned!",
3218                Call);
3219         Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
3220                "Incompatible argument and return types for 'returned' "
3221                "attribute",
3222                Call);
3223         SawReturned = true;
3224       }
3225 
3226       // Statepoint intrinsic is vararg but the wrapped function may be not.
3227       // Allow sret here and check the wrapped function in verifyStatepoint.
3228       if (!Call.getCalledFunction() ||
3229           Call.getCalledFunction()->getIntrinsicID() !=
3230               Intrinsic::experimental_gc_statepoint)
3231         Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
3232                "Attribute 'sret' cannot be used for vararg call arguments!",
3233                Call);
3234 
3235       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
3236         Assert(Idx == Call.arg_size() - 1,
3237                "inalloca isn't on the last argument!", Call);
3238     }
3239   }
3240 
3241   // Verify that there's no metadata unless it's a direct call to an intrinsic.
3242   if (!IsIntrinsic) {
3243     for (Type *ParamTy : FTy->params()) {
3244       Assert(!ParamTy->isMetadataTy(),
3245              "Function has metadata parameter but isn't an intrinsic", Call);
3246       Assert(!ParamTy->isTokenTy(),
3247              "Function has token parameter but isn't an intrinsic", Call);
3248     }
3249   }
3250 
3251   // Verify that indirect calls don't return tokens.
3252   if (!Call.getCalledFunction()) {
3253     Assert(!FTy->getReturnType()->isTokenTy(),
3254            "Return type cannot be token for indirect call!");
3255     Assert(!FTy->getReturnType()->isX86_AMXTy(),
3256            "Return type cannot be x86_amx for indirect call!");
3257   }
3258 
3259   if (Function *F = Call.getCalledFunction())
3260     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3261       visitIntrinsicCall(ID, Call);
3262 
3263   // Verify that a callsite has at most one "deopt", at most one "funclet", at
3264   // most one "gc-transition", at most one "cfguardtarget",
3265   // and at most one "preallocated" operand bundle.
3266   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
3267        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3268        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3269        FoundAttachedCallBundle = false;
3270   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
3271     OperandBundleUse BU = Call.getOperandBundleAt(i);
3272     uint32_t Tag = BU.getTagID();
3273     if (Tag == LLVMContext::OB_deopt) {
3274       Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
3275       FoundDeoptBundle = true;
3276     } else if (Tag == LLVMContext::OB_gc_transition) {
3277       Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
3278              Call);
3279       FoundGCTransitionBundle = true;
3280     } else if (Tag == LLVMContext::OB_funclet) {
3281       Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
3282       FoundFuncletBundle = true;
3283       Assert(BU.Inputs.size() == 1,
3284              "Expected exactly one funclet bundle operand", Call);
3285       Assert(isa<FuncletPadInst>(BU.Inputs.front()),
3286              "Funclet bundle operands should correspond to a FuncletPadInst",
3287              Call);
3288     } else if (Tag == LLVMContext::OB_cfguardtarget) {
3289       Assert(!FoundCFGuardTargetBundle,
3290              "Multiple CFGuardTarget operand bundles", Call);
3291       FoundCFGuardTargetBundle = true;
3292       Assert(BU.Inputs.size() == 1,
3293              "Expected exactly one cfguardtarget bundle operand", Call);
3294     } else if (Tag == LLVMContext::OB_preallocated) {
3295       Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
3296              Call);
3297       FoundPreallocatedBundle = true;
3298       Assert(BU.Inputs.size() == 1,
3299              "Expected exactly one preallocated bundle operand", Call);
3300       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
3301       Assert(Input &&
3302                  Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3303              "\"preallocated\" argument must be a token from "
3304              "llvm.call.preallocated.setup",
3305              Call);
3306     } else if (Tag == LLVMContext::OB_gc_live) {
3307       Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles",
3308              Call);
3309       FoundGCLiveBundle = true;
3310     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
3311       Assert(!FoundAttachedCallBundle,
3312              "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3313       FoundAttachedCallBundle = true;
3314       verifyAttachedCallBundle(Call, BU);
3315     }
3316   }
3317 
3318   // Verify that each inlinable callsite of a debug-info-bearing function in a
3319   // debug-info-bearing function has a debug location attached to it. Failure to
3320   // do so causes assertion failures when the inliner sets up inline scope info.
3321   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3322       Call.getCalledFunction()->getSubprogram())
3323     AssertDI(Call.getDebugLoc(),
3324              "inlinable function call in a function with "
3325              "debug info must have a !dbg location",
3326              Call);
3327 
3328   visitInstruction(Call);
3329 }
3330 
3331 void Verifier::verifyTailCCMustTailAttrs(AttrBuilder Attrs,
3332                                          StringRef Context) {
3333   Assert(!Attrs.contains(Attribute::InAlloca),
3334          Twine("inalloca attribute not allowed in ") + Context);
3335   Assert(!Attrs.contains(Attribute::InReg),
3336          Twine("inreg attribute not allowed in ") + Context);
3337   Assert(!Attrs.contains(Attribute::SwiftError),
3338          Twine("swifterror attribute not allowed in ") + Context);
3339   Assert(!Attrs.contains(Attribute::Preallocated),
3340          Twine("preallocated attribute not allowed in ") + Context);
3341   Assert(!Attrs.contains(Attribute::ByRef),
3342          Twine("byref attribute not allowed in ") + Context);
3343 }
3344 
3345 /// Two types are "congruent" if they are identical, or if they are both pointer
3346 /// types with different pointee types and the same address space.
3347 static bool isTypeCongruent(Type *L, Type *R) {
3348   if (L == R)
3349     return true;
3350   PointerType *PL = dyn_cast<PointerType>(L);
3351   PointerType *PR = dyn_cast<PointerType>(R);
3352   if (!PL || !PR)
3353     return false;
3354   return PL->getAddressSpace() == PR->getAddressSpace();
3355 }
3356 
3357 static AttrBuilder getParameterABIAttributes(unsigned I, AttributeList Attrs) {
3358   static const Attribute::AttrKind ABIAttrs[] = {
3359       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3360       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3361       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3362       Attribute::ByRef};
3363   AttrBuilder Copy;
3364   for (auto AK : ABIAttrs) {
3365     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3366     if (Attr.isValid())
3367       Copy.addAttribute(Attr);
3368   }
3369 
3370   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3371   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3372       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3373        Attrs.hasParamAttr(I, Attribute::ByRef)))
3374     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
3375   return Copy;
3376 }
3377 
3378 void Verifier::verifyMustTailCall(CallInst &CI) {
3379   Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
3380 
3381   Function *F = CI.getParent()->getParent();
3382   FunctionType *CallerTy = F->getFunctionType();
3383   FunctionType *CalleeTy = CI.getFunctionType();
3384   Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3385          "cannot guarantee tail call due to mismatched varargs", &CI);
3386   Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
3387          "cannot guarantee tail call due to mismatched return types", &CI);
3388 
3389   // - The calling conventions of the caller and callee must match.
3390   Assert(F->getCallingConv() == CI.getCallingConv(),
3391          "cannot guarantee tail call due to mismatched calling conv", &CI);
3392 
3393   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3394   //   or a pointer bitcast followed by a ret instruction.
3395   // - The ret instruction must return the (possibly bitcasted) value
3396   //   produced by the call or void.
3397   Value *RetVal = &CI;
3398   Instruction *Next = CI.getNextNode();
3399 
3400   // Handle the optional bitcast.
3401   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3402     Assert(BI->getOperand(0) == RetVal,
3403            "bitcast following musttail call must use the call", BI);
3404     RetVal = BI;
3405     Next = BI->getNextNode();
3406   }
3407 
3408   // Check the return.
3409   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
3410   Assert(Ret, "musttail call must precede a ret with an optional bitcast",
3411          &CI);
3412   Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3413              isa<UndefValue>(Ret->getReturnValue()),
3414          "musttail call result must be returned", Ret);
3415 
3416   AttributeList CallerAttrs = F->getAttributes();
3417   AttributeList CalleeAttrs = CI.getAttributes();
3418   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3419       CI.getCallingConv() == CallingConv::Tail) {
3420     StringRef CCName =
3421         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3422 
3423     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3424     //   are allowed in swifttailcc call
3425     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3426       AttrBuilder ABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3427       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3428       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3429     }
3430     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
3431       AttrBuilder ABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3432       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3433       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3434     }
3435     // - Varargs functions are not allowed
3436     Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3437                                       " tail call for varargs function");
3438     return;
3439   }
3440 
3441   // - The caller and callee prototypes must match.  Pointer types of
3442   //   parameters or return types may differ in pointee type, but not
3443   //   address space.
3444   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
3445     Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3446            "cannot guarantee tail call due to mismatched parameter counts",
3447            &CI);
3448     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3449       Assert(
3450           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3451           "cannot guarantee tail call due to mismatched parameter types", &CI);
3452     }
3453   }
3454 
3455   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3456   //   returned, preallocated, and inalloca, must match.
3457   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
3458     AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
3459     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
3460     Assert(CallerABIAttrs == CalleeABIAttrs,
3461            "cannot guarantee tail call due to mismatched ABI impacting "
3462            "function attributes",
3463            &CI, CI.getOperand(I));
3464   }
3465 }
3466 
3467 void Verifier::visitCallInst(CallInst &CI) {
3468   visitCallBase(CI);
3469 
3470   if (CI.isMustTailCall())
3471     verifyMustTailCall(CI);
3472 }
3473 
3474 void Verifier::visitInvokeInst(InvokeInst &II) {
3475   visitCallBase(II);
3476 
3477   // Verify that the first non-PHI instruction of the unwind destination is an
3478   // exception handling instruction.
3479   Assert(
3480       II.getUnwindDest()->isEHPad(),
3481       "The unwind destination does not have an exception handling instruction!",
3482       &II);
3483 
3484   visitTerminator(II);
3485 }
3486 
3487 /// visitUnaryOperator - Check the argument to the unary operator.
3488 ///
3489 void Verifier::visitUnaryOperator(UnaryOperator &U) {
3490   Assert(U.getType() == U.getOperand(0)->getType(),
3491          "Unary operators must have same type for"
3492          "operands and result!",
3493          &U);
3494 
3495   switch (U.getOpcode()) {
3496   // Check that floating-point arithmetic operators are only used with
3497   // floating-point operands.
3498   case Instruction::FNeg:
3499     Assert(U.getType()->isFPOrFPVectorTy(),
3500            "FNeg operator only works with float types!", &U);
3501     break;
3502   default:
3503     llvm_unreachable("Unknown UnaryOperator opcode!");
3504   }
3505 
3506   visitInstruction(U);
3507 }
3508 
3509 /// visitBinaryOperator - Check that both arguments to the binary operator are
3510 /// of the same type!
3511 ///
3512 void Verifier::visitBinaryOperator(BinaryOperator &B) {
3513   Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
3514          "Both operands to a binary operator are not of the same type!", &B);
3515 
3516   switch (B.getOpcode()) {
3517   // Check that integer arithmetic operators are only used with
3518   // integral operands.
3519   case Instruction::Add:
3520   case Instruction::Sub:
3521   case Instruction::Mul:
3522   case Instruction::SDiv:
3523   case Instruction::UDiv:
3524   case Instruction::SRem:
3525   case Instruction::URem:
3526     Assert(B.getType()->isIntOrIntVectorTy(),
3527            "Integer arithmetic operators only work with integral types!", &B);
3528     Assert(B.getType() == B.getOperand(0)->getType(),
3529            "Integer arithmetic operators must have same type "
3530            "for operands and result!",
3531            &B);
3532     break;
3533   // Check that floating-point arithmetic operators are only used with
3534   // floating-point operands.
3535   case Instruction::FAdd:
3536   case Instruction::FSub:
3537   case Instruction::FMul:
3538   case Instruction::FDiv:
3539   case Instruction::FRem:
3540     Assert(B.getType()->isFPOrFPVectorTy(),
3541            "Floating-point arithmetic operators only work with "
3542            "floating-point types!",
3543            &B);
3544     Assert(B.getType() == B.getOperand(0)->getType(),
3545            "Floating-point arithmetic operators must have same type "
3546            "for operands and result!",
3547            &B);
3548     break;
3549   // Check that logical operators are only used with integral operands.
3550   case Instruction::And:
3551   case Instruction::Or:
3552   case Instruction::Xor:
3553     Assert(B.getType()->isIntOrIntVectorTy(),
3554            "Logical operators only work with integral types!", &B);
3555     Assert(B.getType() == B.getOperand(0)->getType(),
3556            "Logical operators must have same type for operands and result!",
3557            &B);
3558     break;
3559   case Instruction::Shl:
3560   case Instruction::LShr:
3561   case Instruction::AShr:
3562     Assert(B.getType()->isIntOrIntVectorTy(),
3563            "Shifts only work with integral types!", &B);
3564     Assert(B.getType() == B.getOperand(0)->getType(),
3565            "Shift return type must be same as operands!", &B);
3566     break;
3567   default:
3568     llvm_unreachable("Unknown BinaryOperator opcode!");
3569   }
3570 
3571   visitInstruction(B);
3572 }
3573 
3574 void Verifier::visitICmpInst(ICmpInst &IC) {
3575   // Check that the operands are the same type
3576   Type *Op0Ty = IC.getOperand(0)->getType();
3577   Type *Op1Ty = IC.getOperand(1)->getType();
3578   Assert(Op0Ty == Op1Ty,
3579          "Both operands to ICmp instruction are not of the same type!", &IC);
3580   // Check that the operands are the right type
3581   Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
3582          "Invalid operand types for ICmp instruction", &IC);
3583   // Check that the predicate is valid.
3584   Assert(IC.isIntPredicate(),
3585          "Invalid predicate in ICmp instruction!", &IC);
3586 
3587   visitInstruction(IC);
3588 }
3589 
3590 void Verifier::visitFCmpInst(FCmpInst &FC) {
3591   // Check that the operands are the same type
3592   Type *Op0Ty = FC.getOperand(0)->getType();
3593   Type *Op1Ty = FC.getOperand(1)->getType();
3594   Assert(Op0Ty == Op1Ty,
3595          "Both operands to FCmp instruction are not of the same type!", &FC);
3596   // Check that the operands are the right type
3597   Assert(Op0Ty->isFPOrFPVectorTy(),
3598          "Invalid operand types for FCmp instruction", &FC);
3599   // Check that the predicate is valid.
3600   Assert(FC.isFPPredicate(),
3601          "Invalid predicate in FCmp instruction!", &FC);
3602 
3603   visitInstruction(FC);
3604 }
3605 
3606 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
3607   Assert(
3608       ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
3609       "Invalid extractelement operands!", &EI);
3610   visitInstruction(EI);
3611 }
3612 
3613 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
3614   Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
3615                                             IE.getOperand(2)),
3616          "Invalid insertelement operands!", &IE);
3617   visitInstruction(IE);
3618 }
3619 
3620 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
3621   Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
3622                                             SV.getShuffleMask()),
3623          "Invalid shufflevector operands!", &SV);
3624   visitInstruction(SV);
3625 }
3626 
3627 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3628   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
3629 
3630   Assert(isa<PointerType>(TargetTy),
3631          "GEP base pointer is not a vector or a vector of pointers", &GEP);
3632   Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
3633 
3634   SmallVector<Value *, 16> Idxs(GEP.indices());
3635   Assert(all_of(
3636       Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }),
3637       "GEP indexes must be integers", &GEP);
3638   Type *ElTy =
3639       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
3640   Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
3641 
3642   Assert(GEP.getType()->isPtrOrPtrVectorTy() &&
3643              GEP.getResultElementType() == ElTy,
3644          "GEP is not of right type for indices!", &GEP, ElTy);
3645 
3646   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
3647     // Additional checks for vector GEPs.
3648     ElementCount GEPWidth = GEPVTy->getElementCount();
3649     if (GEP.getPointerOperandType()->isVectorTy())
3650       Assert(
3651           GEPWidth ==
3652               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
3653           "Vector GEP result width doesn't match operand's", &GEP);
3654     for (Value *Idx : Idxs) {
3655       Type *IndexTy = Idx->getType();
3656       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3657         ElementCount IndexWidth = IndexVTy->getElementCount();
3658         Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
3659       }
3660       Assert(IndexTy->isIntOrIntVectorTy(),
3661              "All GEP indices should be of integer type");
3662     }
3663   }
3664 
3665   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3666     Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
3667            "GEP address space doesn't match type", &GEP);
3668   }
3669 
3670   visitInstruction(GEP);
3671 }
3672 
3673 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
3674   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
3675 }
3676 
3677 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3678   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
3679          "precondition violation");
3680 
3681   unsigned NumOperands = Range->getNumOperands();
3682   Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
3683   unsigned NumRanges = NumOperands / 2;
3684   Assert(NumRanges >= 1, "It should have at least one range!", Range);
3685 
3686   ConstantRange LastRange(1, true); // Dummy initial value
3687   for (unsigned i = 0; i < NumRanges; ++i) {
3688     ConstantInt *Low =
3689         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
3690     Assert(Low, "The lower limit must be an integer!", Low);
3691     ConstantInt *High =
3692         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
3693     Assert(High, "The upper limit must be an integer!", High);
3694     Assert(High->getType() == Low->getType() && High->getType() == Ty,
3695            "Range types must match instruction type!", &I);
3696 
3697     APInt HighV = High->getValue();
3698     APInt LowV = Low->getValue();
3699     ConstantRange CurRange(LowV, HighV);
3700     Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3701            "Range must not be empty!", Range);
3702     if (i != 0) {
3703       Assert(CurRange.intersectWith(LastRange).isEmptySet(),
3704              "Intervals are overlapping", Range);
3705       Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3706              Range);
3707       Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3708              Range);
3709     }
3710     LastRange = ConstantRange(LowV, HighV);
3711   }
3712   if (NumRanges > 2) {
3713     APInt FirstLow =
3714         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
3715     APInt FirstHigh =
3716         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
3717     ConstantRange FirstRange(FirstLow, FirstHigh);
3718     Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
3719            "Intervals are overlapping", Range);
3720     Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3721            Range);
3722   }
3723 }
3724 
3725 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3726   unsigned Size = DL.getTypeSizeInBits(Ty);
3727   Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3728   Assert(!(Size & (Size - 1)),
3729          "atomic memory access' operand must have a power-of-two size", Ty, I);
3730 }
3731 
3732 void Verifier::visitLoadInst(LoadInst &LI) {
3733   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
3734   Assert(PTy, "Load operand must be a pointer.", &LI);
3735   Type *ElTy = LI.getType();
3736   Assert(LI.getAlignment() <= Value::MaximumAlignment,
3737          "huge alignment values are unsupported", &LI);
3738   Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
3739   if (LI.isAtomic()) {
3740     Assert(LI.getOrdering() != AtomicOrdering::Release &&
3741                LI.getOrdering() != AtomicOrdering::AcquireRelease,
3742            "Load cannot have Release ordering", &LI);
3743     Assert(LI.getAlignment() != 0,
3744            "Atomic load must specify explicit alignment", &LI);
3745     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3746            "atomic load operand must have integer, pointer, or floating point "
3747            "type!",
3748            ElTy, &LI);
3749     checkAtomicMemAccessSize(ElTy, &LI);
3750   } else {
3751     Assert(LI.getSyncScopeID() == SyncScope::System,
3752            "Non-atomic load cannot have SynchronizationScope specified", &LI);
3753   }
3754 
3755   visitInstruction(LI);
3756 }
3757 
3758 void Verifier::visitStoreInst(StoreInst &SI) {
3759   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
3760   Assert(PTy, "Store operand must be a pointer.", &SI);
3761   Type *ElTy = SI.getOperand(0)->getType();
3762   Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
3763          "Stored value type does not match pointer operand type!", &SI, ElTy);
3764   Assert(SI.getAlignment() <= Value::MaximumAlignment,
3765          "huge alignment values are unsupported", &SI);
3766   Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
3767   if (SI.isAtomic()) {
3768     Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
3769                SI.getOrdering() != AtomicOrdering::AcquireRelease,
3770            "Store cannot have Acquire ordering", &SI);
3771     Assert(SI.getAlignment() != 0,
3772            "Atomic store must specify explicit alignment", &SI);
3773     Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
3774            "atomic store operand must have integer, pointer, or floating point "
3775            "type!",
3776            ElTy, &SI);
3777     checkAtomicMemAccessSize(ElTy, &SI);
3778   } else {
3779     Assert(SI.getSyncScopeID() == SyncScope::System,
3780            "Non-atomic store cannot have SynchronizationScope specified", &SI);
3781   }
3782   visitInstruction(SI);
3783 }
3784 
3785 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
3786 void Verifier::verifySwiftErrorCall(CallBase &Call,
3787                                     const Value *SwiftErrorVal) {
3788   for (const auto &I : llvm::enumerate(Call.args())) {
3789     if (I.value() == SwiftErrorVal) {
3790       Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError),
3791              "swifterror value when used in a callsite should be marked "
3792              "with swifterror attribute",
3793              SwiftErrorVal, Call);
3794     }
3795   }
3796 }
3797 
3798 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3799   // Check that swifterror value is only used by loads, stores, or as
3800   // a swifterror argument.
3801   for (const User *U : SwiftErrorVal->users()) {
3802     Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3803            isa<InvokeInst>(U),
3804            "swifterror value can only be loaded and stored from, or "
3805            "as a swifterror argument!",
3806            SwiftErrorVal, U);
3807     // If it is used by a store, check it is the second operand.
3808     if (auto StoreI = dyn_cast<StoreInst>(U))
3809       Assert(StoreI->getOperand(1) == SwiftErrorVal,
3810              "swifterror value should be the second operand when used "
3811              "by stores", SwiftErrorVal, U);
3812     if (auto *Call = dyn_cast<CallBase>(U))
3813       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
3814   }
3815 }
3816 
3817 void Verifier::visitAllocaInst(AllocaInst &AI) {
3818   SmallPtrSet<Type*, 4> Visited;
3819   Assert(AI.getAllocatedType()->isSized(&Visited),
3820          "Cannot allocate unsized type", &AI);
3821   Assert(AI.getArraySize()->getType()->isIntegerTy(),
3822          "Alloca array size must have integer type", &AI);
3823   Assert(AI.getAlignment() <= Value::MaximumAlignment,
3824          "huge alignment values are unsupported", &AI);
3825 
3826   if (AI.isSwiftError()) {
3827     verifySwiftErrorValue(&AI);
3828   }
3829 
3830   visitInstruction(AI);
3831 }
3832 
3833 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
3834   Type *ElTy = CXI.getOperand(1)->getType();
3835   Assert(ElTy->isIntOrPtrTy(),
3836          "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
3837   checkAtomicMemAccessSize(ElTy, &CXI);
3838   visitInstruction(CXI);
3839 }
3840 
3841 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
3842   Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
3843          "atomicrmw instructions cannot be unordered.", &RMWI);
3844   auto Op = RMWI.getOperation();
3845   Type *ElTy = RMWI.getOperand(1)->getType();
3846   if (Op == AtomicRMWInst::Xchg) {
3847     Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " +
3848            AtomicRMWInst::getOperationName(Op) +
3849            " operand must have integer or floating point type!",
3850            &RMWI, ElTy);
3851   } else if (AtomicRMWInst::isFPOperation(Op)) {
3852     Assert(ElTy->isFloatingPointTy(), "atomicrmw " +
3853            AtomicRMWInst::getOperationName(Op) +
3854            " operand must have floating point type!",
3855            &RMWI, ElTy);
3856   } else {
3857     Assert(ElTy->isIntegerTy(), "atomicrmw " +
3858            AtomicRMWInst::getOperationName(Op) +
3859            " operand must have integer type!",
3860            &RMWI, ElTy);
3861   }
3862   checkAtomicMemAccessSize(ElTy, &RMWI);
3863   Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
3864          "Invalid binary operation!", &RMWI);
3865   visitInstruction(RMWI);
3866 }
3867 
3868 void Verifier::visitFenceInst(FenceInst &FI) {
3869   const AtomicOrdering Ordering = FI.getOrdering();
3870   Assert(Ordering == AtomicOrdering::Acquire ||
3871              Ordering == AtomicOrdering::Release ||
3872              Ordering == AtomicOrdering::AcquireRelease ||
3873              Ordering == AtomicOrdering::SequentiallyConsistent,
3874          "fence instructions may only have acquire, release, acq_rel, or "
3875          "seq_cst ordering.",
3876          &FI);
3877   visitInstruction(FI);
3878 }
3879 
3880 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
3881   Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
3882                                           EVI.getIndices()) == EVI.getType(),
3883          "Invalid ExtractValueInst operands!", &EVI);
3884 
3885   visitInstruction(EVI);
3886 }
3887 
3888 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
3889   Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
3890                                           IVI.getIndices()) ==
3891              IVI.getOperand(1)->getType(),
3892          "Invalid InsertValueInst operands!", &IVI);
3893 
3894   visitInstruction(IVI);
3895 }
3896 
3897 static Value *getParentPad(Value *EHPad) {
3898   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3899     return FPI->getParentPad();
3900 
3901   return cast<CatchSwitchInst>(EHPad)->getParentPad();
3902 }
3903 
3904 void Verifier::visitEHPadPredecessors(Instruction &I) {
3905   assert(I.isEHPad());
3906 
3907   BasicBlock *BB = I.getParent();
3908   Function *F = BB->getParent();
3909 
3910   Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
3911 
3912   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3913     // The landingpad instruction defines its parent as a landing pad block. The
3914     // landing pad block may be branched to only by the unwind edge of an
3915     // invoke.
3916     for (BasicBlock *PredBB : predecessors(BB)) {
3917       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3918       Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
3919              "Block containing LandingPadInst must be jumped to "
3920              "only by the unwind edge of an invoke.",
3921              LPI);
3922     }
3923     return;
3924   }
3925   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3926     if (!pred_empty(BB))
3927       Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3928              "Block containg CatchPadInst must be jumped to "
3929              "only by its catchswitch.",
3930              CPI);
3931     Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3932            "Catchswitch cannot unwind to one of its catchpads",
3933            CPI->getCatchSwitch(), CPI);
3934     return;
3935   }
3936 
3937   // Verify that each pred has a legal terminator with a legal to/from EH
3938   // pad relationship.
3939   Instruction *ToPad = &I;
3940   Value *ToPadParent = getParentPad(ToPad);
3941   for (BasicBlock *PredBB : predecessors(BB)) {
3942     Instruction *TI = PredBB->getTerminator();
3943     Value *FromPad;
3944     if (auto *II = dyn_cast<InvokeInst>(TI)) {
3945       Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
3946              "EH pad must be jumped to via an unwind edge", ToPad, II);
3947       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3948         FromPad = Bundle->Inputs[0];
3949       else
3950         FromPad = ConstantTokenNone::get(II->getContext());
3951     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3952       FromPad = CRI->getOperand(0);
3953       Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3954     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3955       FromPad = CSI;
3956     } else {
3957       Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3958     }
3959 
3960     // The edge may exit from zero or more nested pads.
3961     SmallSet<Value *, 8> Seen;
3962     for (;; FromPad = getParentPad(FromPad)) {
3963       Assert(FromPad != ToPad,
3964              "EH pad cannot handle exceptions raised within it", FromPad, TI);
3965       if (FromPad == ToPadParent) {
3966         // This is a legal unwind edge.
3967         break;
3968       }
3969       Assert(!isa<ConstantTokenNone>(FromPad),
3970              "A single unwind edge may only enter one EH pad", TI);
3971       Assert(Seen.insert(FromPad).second,
3972              "EH pad jumps through a cycle of pads", FromPad);
3973     }
3974   }
3975 }
3976 
3977 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
3978   // The landingpad instruction is ill-formed if it doesn't have any clauses and
3979   // isn't a cleanup.
3980   Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3981          "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
3982 
3983   visitEHPadPredecessors(LPI);
3984 
3985   if (!LandingPadResultTy)
3986     LandingPadResultTy = LPI.getType();
3987   else
3988     Assert(LandingPadResultTy == LPI.getType(),
3989            "The landingpad instruction should have a consistent result type "
3990            "inside a function.",
3991            &LPI);
3992 
3993   Function *F = LPI.getParent()->getParent();
3994   Assert(F->hasPersonalityFn(),
3995          "LandingPadInst needs to be in a function with a personality.", &LPI);
3996 
3997   // The landingpad instruction must be the first non-PHI instruction in the
3998   // block.
3999   Assert(LPI.getParent()->getLandingPadInst() == &LPI,
4000          "LandingPadInst not the first non-PHI instruction in the block.",
4001          &LPI);
4002 
4003   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
4004     Constant *Clause = LPI.getClause(i);
4005     if (LPI.isCatch(i)) {
4006       Assert(isa<PointerType>(Clause->getType()),
4007              "Catch operand does not have pointer type!", &LPI);
4008     } else {
4009       Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
4010       Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
4011              "Filter operand is not an array of constants!", &LPI);
4012     }
4013   }
4014 
4015   visitInstruction(LPI);
4016 }
4017 
4018 void Verifier::visitResumeInst(ResumeInst &RI) {
4019   Assert(RI.getFunction()->hasPersonalityFn(),
4020          "ResumeInst needs to be in a function with a personality.", &RI);
4021 
4022   if (!LandingPadResultTy)
4023     LandingPadResultTy = RI.getValue()->getType();
4024   else
4025     Assert(LandingPadResultTy == RI.getValue()->getType(),
4026            "The resume instruction should have a consistent result type "
4027            "inside a function.",
4028            &RI);
4029 
4030   visitTerminator(RI);
4031 }
4032 
4033 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4034   BasicBlock *BB = CPI.getParent();
4035 
4036   Function *F = BB->getParent();
4037   Assert(F->hasPersonalityFn(),
4038          "CatchPadInst needs to be in a function with a personality.", &CPI);
4039 
4040   Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
4041          "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4042          CPI.getParentPad());
4043 
4044   // The catchpad instruction must be the first non-PHI instruction in the
4045   // block.
4046   Assert(BB->getFirstNonPHI() == &CPI,
4047          "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4048 
4049   visitEHPadPredecessors(CPI);
4050   visitFuncletPadInst(CPI);
4051 }
4052 
4053 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4054   Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
4055          "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4056          CatchReturn.getOperand(0));
4057 
4058   visitTerminator(CatchReturn);
4059 }
4060 
4061 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4062   BasicBlock *BB = CPI.getParent();
4063 
4064   Function *F = BB->getParent();
4065   Assert(F->hasPersonalityFn(),
4066          "CleanupPadInst needs to be in a function with a personality.", &CPI);
4067 
4068   // The cleanuppad instruction must be the first non-PHI instruction in the
4069   // block.
4070   Assert(BB->getFirstNonPHI() == &CPI,
4071          "CleanupPadInst not the first non-PHI instruction in the block.",
4072          &CPI);
4073 
4074   auto *ParentPad = CPI.getParentPad();
4075   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4076          "CleanupPadInst has an invalid parent.", &CPI);
4077 
4078   visitEHPadPredecessors(CPI);
4079   visitFuncletPadInst(CPI);
4080 }
4081 
4082 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4083   User *FirstUser = nullptr;
4084   Value *FirstUnwindPad = nullptr;
4085   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
4086   SmallSet<FuncletPadInst *, 8> Seen;
4087 
4088   while (!Worklist.empty()) {
4089     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4090     Assert(Seen.insert(CurrentPad).second,
4091            "FuncletPadInst must not be nested within itself", CurrentPad);
4092     Value *UnresolvedAncestorPad = nullptr;
4093     for (User *U : CurrentPad->users()) {
4094       BasicBlock *UnwindDest;
4095       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4096         UnwindDest = CRI->getUnwindDest();
4097       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4098         // We allow catchswitch unwind to caller to nest
4099         // within an outer pad that unwinds somewhere else,
4100         // because catchswitch doesn't have a nounwind variant.
4101         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
4102         if (CSI->unwindsToCaller())
4103           continue;
4104         UnwindDest = CSI->getUnwindDest();
4105       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
4106         UnwindDest = II->getUnwindDest();
4107       } else if (isa<CallInst>(U)) {
4108         // Calls which don't unwind may be found inside funclet
4109         // pads that unwind somewhere else.  We don't *require*
4110         // such calls to be annotated nounwind.
4111         continue;
4112       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4113         // The unwind dest for a cleanup can only be found by
4114         // recursive search.  Add it to the worklist, and we'll
4115         // search for its first use that determines where it unwinds.
4116         Worklist.push_back(CPI);
4117         continue;
4118       } else {
4119         Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
4120         continue;
4121       }
4122 
4123       Value *UnwindPad;
4124       bool ExitsFPI;
4125       if (UnwindDest) {
4126         UnwindPad = UnwindDest->getFirstNonPHI();
4127         if (!cast<Instruction>(UnwindPad)->isEHPad())
4128           continue;
4129         Value *UnwindParent = getParentPad(UnwindPad);
4130         // Ignore unwind edges that don't exit CurrentPad.
4131         if (UnwindParent == CurrentPad)
4132           continue;
4133         // Determine whether the original funclet pad is exited,
4134         // and if we are scanning nested pads determine how many
4135         // of them are exited so we can stop searching their
4136         // children.
4137         Value *ExitedPad = CurrentPad;
4138         ExitsFPI = false;
4139         do {
4140           if (ExitedPad == &FPI) {
4141             ExitsFPI = true;
4142             // Now we can resolve any ancestors of CurrentPad up to
4143             // FPI, but not including FPI since we need to make sure
4144             // to check all direct users of FPI for consistency.
4145             UnresolvedAncestorPad = &FPI;
4146             break;
4147           }
4148           Value *ExitedParent = getParentPad(ExitedPad);
4149           if (ExitedParent == UnwindParent) {
4150             // ExitedPad is the ancestor-most pad which this unwind
4151             // edge exits, so we can resolve up to it, meaning that
4152             // ExitedParent is the first ancestor still unresolved.
4153             UnresolvedAncestorPad = ExitedParent;
4154             break;
4155           }
4156           ExitedPad = ExitedParent;
4157         } while (!isa<ConstantTokenNone>(ExitedPad));
4158       } else {
4159         // Unwinding to caller exits all pads.
4160         UnwindPad = ConstantTokenNone::get(FPI.getContext());
4161         ExitsFPI = true;
4162         UnresolvedAncestorPad = &FPI;
4163       }
4164 
4165       if (ExitsFPI) {
4166         // This unwind edge exits FPI.  Make sure it agrees with other
4167         // such edges.
4168         if (FirstUser) {
4169           Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
4170                                               "pad must have the same unwind "
4171                                               "dest",
4172                  &FPI, U, FirstUser);
4173         } else {
4174           FirstUser = U;
4175           FirstUnwindPad = UnwindPad;
4176           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
4177           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4178               getParentPad(UnwindPad) == getParentPad(&FPI))
4179             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4180         }
4181       }
4182       // Make sure we visit all uses of FPI, but for nested pads stop as
4183       // soon as we know where they unwind to.
4184       if (CurrentPad != &FPI)
4185         break;
4186     }
4187     if (UnresolvedAncestorPad) {
4188       if (CurrentPad == UnresolvedAncestorPad) {
4189         // When CurrentPad is FPI itself, we don't mark it as resolved even if
4190         // we've found an unwind edge that exits it, because we need to verify
4191         // all direct uses of FPI.
4192         assert(CurrentPad == &FPI);
4193         continue;
4194       }
4195       // Pop off the worklist any nested pads that we've found an unwind
4196       // destination for.  The pads on the worklist are the uncles,
4197       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
4198       // for all ancestors of CurrentPad up to but not including
4199       // UnresolvedAncestorPad.
4200       Value *ResolvedPad = CurrentPad;
4201       while (!Worklist.empty()) {
4202         Value *UnclePad = Worklist.back();
4203         Value *AncestorPad = getParentPad(UnclePad);
4204         // Walk ResolvedPad up the ancestor list until we either find the
4205         // uncle's parent or the last resolved ancestor.
4206         while (ResolvedPad != AncestorPad) {
4207           Value *ResolvedParent = getParentPad(ResolvedPad);
4208           if (ResolvedParent == UnresolvedAncestorPad) {
4209             break;
4210           }
4211           ResolvedPad = ResolvedParent;
4212         }
4213         // If the resolved ancestor search didn't find the uncle's parent,
4214         // then the uncle is not yet resolved.
4215         if (ResolvedPad != AncestorPad)
4216           break;
4217         // This uncle is resolved, so pop it from the worklist.
4218         Worklist.pop_back();
4219       }
4220     }
4221   }
4222 
4223   if (FirstUnwindPad) {
4224     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
4225       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4226       Value *SwitchUnwindPad;
4227       if (SwitchUnwindDest)
4228         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
4229       else
4230         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
4231       Assert(SwitchUnwindPad == FirstUnwindPad,
4232              "Unwind edges out of a catch must have the same unwind dest as "
4233              "the parent catchswitch",
4234              &FPI, FirstUser, CatchSwitch);
4235     }
4236   }
4237 
4238   visitInstruction(FPI);
4239 }
4240 
4241 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
4242   BasicBlock *BB = CatchSwitch.getParent();
4243 
4244   Function *F = BB->getParent();
4245   Assert(F->hasPersonalityFn(),
4246          "CatchSwitchInst needs to be in a function with a personality.",
4247          &CatchSwitch);
4248 
4249   // The catchswitch instruction must be the first non-PHI instruction in the
4250   // block.
4251   Assert(BB->getFirstNonPHI() == &CatchSwitch,
4252          "CatchSwitchInst not the first non-PHI instruction in the block.",
4253          &CatchSwitch);
4254 
4255   auto *ParentPad = CatchSwitch.getParentPad();
4256   Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4257          "CatchSwitchInst has an invalid parent.", ParentPad);
4258 
4259   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
4260     Instruction *I = UnwindDest->getFirstNonPHI();
4261     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
4262            "CatchSwitchInst must unwind to an EH block which is not a "
4263            "landingpad.",
4264            &CatchSwitch);
4265 
4266     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
4267     if (getParentPad(I) == ParentPad)
4268       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4269   }
4270 
4271   Assert(CatchSwitch.getNumHandlers() != 0,
4272          "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4273 
4274   for (BasicBlock *Handler : CatchSwitch.handlers()) {
4275     Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4276            "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4277   }
4278 
4279   visitEHPadPredecessors(CatchSwitch);
4280   visitTerminator(CatchSwitch);
4281 }
4282 
4283 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
4284   Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
4285          "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4286          CRI.getOperand(0));
4287 
4288   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
4289     Instruction *I = UnwindDest->getFirstNonPHI();
4290     Assert(I->isEHPad() && !isa<LandingPadInst>(I),
4291            "CleanupReturnInst must unwind to an EH block which is not a "
4292            "landingpad.",
4293            &CRI);
4294   }
4295 
4296   visitTerminator(CRI);
4297 }
4298 
4299 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
4300   Instruction *Op = cast<Instruction>(I.getOperand(i));
4301   // If the we have an invalid invoke, don't try to compute the dominance.
4302   // We already reject it in the invoke specific checks and the dominance
4303   // computation doesn't handle multiple edges.
4304   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4305     if (II->getNormalDest() == II->getUnwindDest())
4306       return;
4307   }
4308 
4309   // Quick check whether the def has already been encountered in the same block.
4310   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
4311   // uses are defined to happen on the incoming edge, not at the instruction.
4312   //
4313   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
4314   // wrapping an SSA value, assert that we've already encountered it.  See
4315   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
4316   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4317     return;
4318 
4319   const Use &U = I.getOperandUse(i);
4320   Assert(DT.dominates(Op, U),
4321          "Instruction does not dominate all uses!", Op, &I);
4322 }
4323 
4324 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
4325   Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
4326          "apply only to pointer types", &I);
4327   Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
4328          "dereferenceable, dereferenceable_or_null apply only to load"
4329          " and inttoptr instructions, use attributes for calls or invokes", &I);
4330   Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
4331          "take one operand!", &I);
4332   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
4333   Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
4334          "dereferenceable_or_null metadata value must be an i64!", &I);
4335 }
4336 
4337 void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
4338   Assert(MD->getNumOperands() >= 2,
4339          "!prof annotations should have no less than 2 operands", MD);
4340 
4341   // Check first operand.
4342   Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
4343   Assert(isa<MDString>(MD->getOperand(0)),
4344          "expected string with name of the !prof annotation", MD);
4345   MDString *MDS = cast<MDString>(MD->getOperand(0));
4346   StringRef ProfName = MDS->getString();
4347 
4348   // Check consistency of !prof branch_weights metadata.
4349   if (ProfName.equals("branch_weights")) {
4350     if (isa<InvokeInst>(&I)) {
4351       Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
4352              "Wrong number of InvokeInst branch_weights operands", MD);
4353     } else {
4354       unsigned ExpectedNumOperands = 0;
4355       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
4356         ExpectedNumOperands = BI->getNumSuccessors();
4357       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4358         ExpectedNumOperands = SI->getNumSuccessors();
4359       else if (isa<CallInst>(&I))
4360         ExpectedNumOperands = 1;
4361       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
4362         ExpectedNumOperands = IBI->getNumDestinations();
4363       else if (isa<SelectInst>(&I))
4364         ExpectedNumOperands = 2;
4365       else
4366         CheckFailed("!prof branch_weights are not allowed for this instruction",
4367                     MD);
4368 
4369       Assert(MD->getNumOperands() == 1 + ExpectedNumOperands,
4370              "Wrong number of operands", MD);
4371     }
4372     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
4373       auto &MDO = MD->getOperand(i);
4374       Assert(MDO, "second operand should not be null", MD);
4375       Assert(mdconst::dyn_extract<ConstantInt>(MDO),
4376              "!prof brunch_weights operand is not a const int");
4377     }
4378   }
4379 }
4380 
4381 void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
4382   Assert(isa<MDTuple>(Annotation), "annotation must be a tuple");
4383   Assert(Annotation->getNumOperands() >= 1,
4384          "annotation must have at least one operand");
4385   for (const MDOperand &Op : Annotation->operands())
4386     Assert(isa<MDString>(Op.get()), "operands must be strings");
4387 }
4388 
4389 void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4390   unsigned NumOps = MD->getNumOperands();
4391   Assert(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4392          MD);
4393   Assert(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4394          "first scope operand must be self-referential or string", MD);
4395   if (NumOps == 3)
4396     Assert(isa<MDString>(MD->getOperand(2)),
4397            "third scope operand must be string (if used)", MD);
4398 
4399   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
4400   Assert(Domain != nullptr, "second scope operand must be MDNode", MD);
4401 
4402   unsigned NumDomainOps = Domain->getNumOperands();
4403   Assert(NumDomainOps >= 1 && NumDomainOps <= 2,
4404          "domain must have one or two operands", Domain);
4405   Assert(Domain->getOperand(0).get() == Domain ||
4406              isa<MDString>(Domain->getOperand(0)),
4407          "first domain operand must be self-referential or string", Domain);
4408   if (NumDomainOps == 2)
4409     Assert(isa<MDString>(Domain->getOperand(1)),
4410            "second domain operand must be string (if used)", Domain);
4411 }
4412 
4413 void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4414   for (const MDOperand &Op : MD->operands()) {
4415     const MDNode *OpMD = dyn_cast<MDNode>(Op);
4416     Assert(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4417     visitAliasScopeMetadata(OpMD);
4418   }
4419 }
4420 
4421 /// verifyInstruction - Verify that an instruction is well formed.
4422 ///
4423 void Verifier::visitInstruction(Instruction &I) {
4424   BasicBlock *BB = I.getParent();
4425   Assert(BB, "Instruction not embedded in basic block!", &I);
4426 
4427   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
4428     for (User *U : I.users()) {
4429       Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
4430              "Only PHI nodes may reference their own value!", &I);
4431     }
4432   }
4433 
4434   // Check that void typed values don't have names
4435   Assert(!I.getType()->isVoidTy() || !I.hasName(),
4436          "Instruction has a name, but provides a void value!", &I);
4437 
4438   // Check that the return value of the instruction is either void or a legal
4439   // value type.
4440   Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
4441          "Instruction returns a non-scalar type!", &I);
4442 
4443   // Check that the instruction doesn't produce metadata. Calls are already
4444   // checked against the callee type.
4445   Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
4446          "Invalid use of metadata!", &I);
4447 
4448   // Check that all uses of the instruction, if they are instructions
4449   // themselves, actually have parent basic blocks.  If the use is not an
4450   // instruction, it is an error!
4451   for (Use &U : I.uses()) {
4452     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
4453       Assert(Used->getParent() != nullptr,
4454              "Instruction referencing"
4455              " instruction not embedded in a basic block!",
4456              &I, Used);
4457     else {
4458       CheckFailed("Use of instruction is not an instruction!", U);
4459       return;
4460     }
4461   }
4462 
4463   // Get a pointer to the call base of the instruction if it is some form of
4464   // call.
4465   const CallBase *CBI = dyn_cast<CallBase>(&I);
4466 
4467   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
4468     Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
4469 
4470     // Check to make sure that only first-class-values are operands to
4471     // instructions.
4472     if (!I.getOperand(i)->getType()->isFirstClassType()) {
4473       Assert(false, "Instruction operands must be first-class values!", &I);
4474     }
4475 
4476     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4477       // This code checks whether the function is used as the operand of a
4478       // clang_arc_attachedcall operand bundle.
4479       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4480                                       int Idx) {
4481         return CBI && CBI->isOperandBundleOfType(
4482                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4483       };
4484 
4485       // Check to make sure that the "address of" an intrinsic function is never
4486       // taken. Ignore cases where the address of the intrinsic function is used
4487       // as the argument of operand bundle "clang.arc.attachedcall" as those
4488       // cases are handled in verifyAttachedCallBundle.
4489       Assert((!F->isIntrinsic() ||
4490               (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4491               IsAttachedCallOperand(F, CBI, i)),
4492              "Cannot take the address of an intrinsic!", &I);
4493       Assert(
4494           !F->isIntrinsic() || isa<CallInst>(I) ||
4495               F->getIntrinsicID() == Intrinsic::donothing ||
4496               F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4497               F->getIntrinsicID() == Intrinsic::seh_try_end ||
4498               F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4499               F->getIntrinsicID() == Intrinsic::seh_scope_end ||
4500               F->getIntrinsicID() == Intrinsic::coro_resume ||
4501               F->getIntrinsicID() == Intrinsic::coro_destroy ||
4502               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
4503               F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
4504               F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4505               F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4506               IsAttachedCallOperand(F, CBI, i),
4507           "Cannot invoke an intrinsic other than donothing, patchpoint, "
4508           "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
4509           &I);
4510       Assert(F->getParent() == &M, "Referencing function in another module!",
4511              &I, &M, F, F->getParent());
4512     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
4513       Assert(OpBB->getParent() == BB->getParent(),
4514              "Referring to a basic block in another function!", &I);
4515     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
4516       Assert(OpArg->getParent() == BB->getParent(),
4517              "Referring to an argument in another function!", &I);
4518     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
4519       Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
4520              &M, GV, GV->getParent());
4521     } else if (isa<Instruction>(I.getOperand(i))) {
4522       verifyDominatesUse(I, i);
4523     } else if (isa<InlineAsm>(I.getOperand(i))) {
4524       Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
4525              "Cannot take the address of an inline asm!", &I);
4526     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4527       if (CE->getType()->isPtrOrPtrVectorTy()) {
4528         // If we have a ConstantExpr pointer, we need to see if it came from an
4529         // illegal bitcast.
4530         visitConstantExprsRecursively(CE);
4531       }
4532     }
4533   }
4534 
4535   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
4536     Assert(I.getType()->isFPOrFPVectorTy(),
4537            "fpmath requires a floating point result!", &I);
4538     Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
4539     if (ConstantFP *CFP0 =
4540             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
4541       const APFloat &Accuracy = CFP0->getValueAPF();
4542       Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
4543              "fpmath accuracy must have float type", &I);
4544       Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
4545              "fpmath accuracy not a positive number!", &I);
4546     } else {
4547       Assert(false, "invalid fpmath accuracy!", &I);
4548     }
4549   }
4550 
4551   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
4552     Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
4553            "Ranges are only for loads, calls and invokes!", &I);
4554     visitRangeMetadata(I, Range, I.getType());
4555   }
4556 
4557   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
4558     Assert(isa<LoadInst>(I) || isa<StoreInst>(I),
4559            "invariant.group metadata is only for loads and stores", &I);
4560   }
4561 
4562   if (I.getMetadata(LLVMContext::MD_nonnull)) {
4563     Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
4564            &I);
4565     Assert(isa<LoadInst>(I),
4566            "nonnull applies only to load instructions, use attributes"
4567            " for calls or invokes",
4568            &I);
4569   }
4570 
4571   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
4572     visitDereferenceableMetadata(I, MD);
4573 
4574   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
4575     visitDereferenceableMetadata(I, MD);
4576 
4577   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
4578     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
4579 
4580   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
4581     visitAliasScopeListMetadata(MD);
4582   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
4583     visitAliasScopeListMetadata(MD);
4584 
4585   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
4586     Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
4587            &I);
4588     Assert(isa<LoadInst>(I), "align applies only to load instructions, "
4589            "use attributes for calls or invokes", &I);
4590     Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
4591     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4592     Assert(CI && CI->getType()->isIntegerTy(64),
4593            "align metadata value must be an i64!", &I);
4594     uint64_t Align = CI->getZExtValue();
4595     Assert(isPowerOf2_64(Align),
4596            "align metadata value must be a power of 2!", &I);
4597     Assert(Align <= Value::MaximumAlignment,
4598            "alignment is larger that implementation defined limit", &I);
4599   }
4600 
4601   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
4602     visitProfMetadata(I, MD);
4603 
4604   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
4605     visitAnnotationMetadata(Annotation);
4606 
4607   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
4608     AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
4609     visitMDNode(*N, AreDebugLocsAllowed::Yes);
4610   }
4611 
4612   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
4613     verifyFragmentExpression(*DII);
4614     verifyNotEntryValue(*DII);
4615   }
4616 
4617   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
4618   I.getAllMetadata(MDs);
4619   for (auto Attachment : MDs) {
4620     unsigned Kind = Attachment.first;
4621     auto AllowLocs =
4622         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
4623             ? AreDebugLocsAllowed::Yes
4624             : AreDebugLocsAllowed::No;
4625     visitMDNode(*Attachment.second, AllowLocs);
4626   }
4627 
4628   InstsInThisBlock.insert(&I);
4629 }
4630 
4631 /// Allow intrinsics to be verified in different ways.
4632 void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
4633   Function *IF = Call.getCalledFunction();
4634   Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
4635          IF);
4636 
4637   // Verify that the intrinsic prototype lines up with what the .td files
4638   // describe.
4639   FunctionType *IFTy = IF->getFunctionType();
4640   bool IsVarArg = IFTy->isVarArg();
4641 
4642   SmallVector<Intrinsic::IITDescriptor, 8> Table;
4643   getIntrinsicInfoTableEntries(ID, Table);
4644   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
4645 
4646   // Walk the descriptors to extract overloaded types.
4647   SmallVector<Type *, 4> ArgTys;
4648   Intrinsic::MatchIntrinsicTypesResult Res =
4649       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
4650   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
4651          "Intrinsic has incorrect return type!", IF);
4652   Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
4653          "Intrinsic has incorrect argument type!", IF);
4654 
4655   // Verify if the intrinsic call matches the vararg property.
4656   if (IsVarArg)
4657     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4658            "Intrinsic was not defined with variable arguments!", IF);
4659   else
4660     Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
4661            "Callsite was not defined with variable arguments!", IF);
4662 
4663   // All descriptors should be absorbed by now.
4664   Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
4665 
4666   // Now that we have the intrinsic ID and the actual argument types (and we
4667   // know they are legal for the intrinsic!) get the intrinsic name through the
4668   // usual means.  This allows us to verify the mangling of argument types into
4669   // the name.
4670   const std::string ExpectedName =
4671       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
4672   Assert(ExpectedName == IF->getName(),
4673          "Intrinsic name not mangled correctly for type arguments! "
4674          "Should be: " +
4675              ExpectedName,
4676          IF);
4677 
4678   // If the intrinsic takes MDNode arguments, verify that they are either global
4679   // or are local to *this* function.
4680   for (Value *V : Call.args()) {
4681     if (auto *MD = dyn_cast<MetadataAsValue>(V))
4682       visitMetadataAsValue(*MD, Call.getCaller());
4683     if (auto *Const = dyn_cast<Constant>(V))
4684       Assert(!Const->getType()->isX86_AMXTy(),
4685              "const x86_amx is not allowed in argument!");
4686   }
4687 
4688   switch (ID) {
4689   default:
4690     break;
4691   case Intrinsic::assume: {
4692     for (auto &Elem : Call.bundle_op_infos()) {
4693       Assert(Elem.Tag->getKey() == "ignore" ||
4694                  Attribute::isExistingAttribute(Elem.Tag->getKey()),
4695              "tags must be valid attribute names", Call);
4696       Attribute::AttrKind Kind =
4697           Attribute::getAttrKindFromName(Elem.Tag->getKey());
4698       unsigned ArgCount = Elem.End - Elem.Begin;
4699       if (Kind == Attribute::Alignment) {
4700         Assert(ArgCount <= 3 && ArgCount >= 2,
4701                "alignment assumptions should have 2 or 3 arguments", Call);
4702         Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
4703                "first argument should be a pointer", Call);
4704         Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
4705                "second argument should be an integer", Call);
4706         if (ArgCount == 3)
4707           Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
4708                  "third argument should be an integer if present", Call);
4709         return;
4710       }
4711       Assert(ArgCount <= 2, "too many arguments", Call);
4712       if (Kind == Attribute::None)
4713         break;
4714       if (Attribute::isIntAttrKind(Kind)) {
4715         Assert(ArgCount == 2, "this attribute should have 2 arguments", Call);
4716         Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
4717                "the second argument should be a constant integral value", Call);
4718       } else if (Attribute::canUseAsParamAttr(Kind)) {
4719         Assert((ArgCount) == 1, "this attribute should have one argument",
4720                Call);
4721       } else if (Attribute::canUseAsFnAttr(Kind)) {
4722         Assert((ArgCount) == 0, "this attribute has no argument", Call);
4723       }
4724     }
4725     break;
4726   }
4727   case Intrinsic::coro_id: {
4728     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
4729     if (isa<ConstantPointerNull>(InfoArg))
4730       break;
4731     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
4732     Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
4733            "info argument of llvm.coro.id must refer to an initialized "
4734            "constant");
4735     Constant *Init = GV->getInitializer();
4736     Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4737            "info argument of llvm.coro.id must refer to either a struct or "
4738            "an array");
4739     break;
4740   }
4741 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
4742   case Intrinsic::INTRINSIC:
4743 #include "llvm/IR/ConstrainedOps.def"
4744     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
4745     break;
4746   case Intrinsic::dbg_declare: // llvm.dbg.declare
4747     Assert(isa<MetadataAsValue>(Call.getArgOperand(0)),
4748            "invalid llvm.dbg.declare intrinsic call 1", Call);
4749     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
4750     break;
4751   case Intrinsic::dbg_addr: // llvm.dbg.addr
4752     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
4753     break;
4754   case Intrinsic::dbg_value: // llvm.dbg.value
4755     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
4756     break;
4757   case Intrinsic::dbg_label: // llvm.dbg.label
4758     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
4759     break;
4760   case Intrinsic::memcpy:
4761   case Intrinsic::memcpy_inline:
4762   case Intrinsic::memmove:
4763   case Intrinsic::memset: {
4764     const auto *MI = cast<MemIntrinsic>(&Call);
4765     auto IsValidAlignment = [&](unsigned Alignment) -> bool {
4766       return Alignment == 0 || isPowerOf2_32(Alignment);
4767     };
4768     Assert(IsValidAlignment(MI->getDestAlignment()),
4769            "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
4770            Call);
4771     if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) {
4772       Assert(IsValidAlignment(MTI->getSourceAlignment()),
4773              "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
4774              Call);
4775     }
4776 
4777     break;
4778   }
4779   case Intrinsic::memcpy_element_unordered_atomic:
4780   case Intrinsic::memmove_element_unordered_atomic:
4781   case Intrinsic::memset_element_unordered_atomic: {
4782     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
4783 
4784     ConstantInt *ElementSizeCI =
4785         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
4786     const APInt &ElementSizeVal = ElementSizeCI->getValue();
4787     Assert(ElementSizeVal.isPowerOf2(),
4788            "element size of the element-wise atomic memory intrinsic "
4789            "must be a power of 2",
4790            Call);
4791 
4792     auto IsValidAlignment = [&](uint64_t Alignment) {
4793       return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
4794     };
4795     uint64_t DstAlignment = AMI->getDestAlignment();
4796     Assert(IsValidAlignment(DstAlignment),
4797            "incorrect alignment of the destination argument", Call);
4798     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
4799       uint64_t SrcAlignment = AMT->getSourceAlignment();
4800       Assert(IsValidAlignment(SrcAlignment),
4801              "incorrect alignment of the source argument", Call);
4802     }
4803     break;
4804   }
4805   case Intrinsic::call_preallocated_setup: {
4806     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
4807     Assert(NumArgs != nullptr,
4808            "llvm.call.preallocated.setup argument must be a constant");
4809     bool FoundCall = false;
4810     for (User *U : Call.users()) {
4811       auto *UseCall = dyn_cast<CallBase>(U);
4812       Assert(UseCall != nullptr,
4813              "Uses of llvm.call.preallocated.setup must be calls");
4814       const Function *Fn = UseCall->getCalledFunction();
4815       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
4816         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
4817         Assert(AllocArgIndex != nullptr,
4818                "llvm.call.preallocated.alloc arg index must be a constant");
4819         auto AllocArgIndexInt = AllocArgIndex->getValue();
4820         Assert(AllocArgIndexInt.sge(0) &&
4821                    AllocArgIndexInt.slt(NumArgs->getValue()),
4822                "llvm.call.preallocated.alloc arg index must be between 0 and "
4823                "corresponding "
4824                "llvm.call.preallocated.setup's argument count");
4825       } else if (Fn && Fn->getIntrinsicID() ==
4826                            Intrinsic::call_preallocated_teardown) {
4827         // nothing to do
4828       } else {
4829         Assert(!FoundCall, "Can have at most one call corresponding to a "
4830                            "llvm.call.preallocated.setup");
4831         FoundCall = true;
4832         size_t NumPreallocatedArgs = 0;
4833         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
4834           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
4835             ++NumPreallocatedArgs;
4836           }
4837         }
4838         Assert(NumPreallocatedArgs != 0,
4839                "cannot use preallocated intrinsics on a call without "
4840                "preallocated arguments");
4841         Assert(NumArgs->equalsInt(NumPreallocatedArgs),
4842                "llvm.call.preallocated.setup arg size must be equal to number "
4843                "of preallocated arguments "
4844                "at call site",
4845                Call, *UseCall);
4846         // getOperandBundle() cannot be called if more than one of the operand
4847         // bundle exists. There is already a check elsewhere for this, so skip
4848         // here if we see more than one.
4849         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
4850             1) {
4851           return;
4852         }
4853         auto PreallocatedBundle =
4854             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
4855         Assert(PreallocatedBundle,
4856                "Use of llvm.call.preallocated.setup outside intrinsics "
4857                "must be in \"preallocated\" operand bundle");
4858         Assert(PreallocatedBundle->Inputs.front().get() == &Call,
4859                "preallocated bundle must have token from corresponding "
4860                "llvm.call.preallocated.setup");
4861       }
4862     }
4863     break;
4864   }
4865   case Intrinsic::call_preallocated_arg: {
4866     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4867     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4868                         Intrinsic::call_preallocated_setup,
4869            "llvm.call.preallocated.arg token argument must be a "
4870            "llvm.call.preallocated.setup");
4871     Assert(Call.hasFnAttr(Attribute::Preallocated),
4872            "llvm.call.preallocated.arg must be called with a \"preallocated\" "
4873            "call site attribute");
4874     break;
4875   }
4876   case Intrinsic::call_preallocated_teardown: {
4877     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
4878     Assert(Token && Token->getCalledFunction()->getIntrinsicID() ==
4879                         Intrinsic::call_preallocated_setup,
4880            "llvm.call.preallocated.teardown token argument must be a "
4881            "llvm.call.preallocated.setup");
4882     break;
4883   }
4884   case Intrinsic::gcroot:
4885   case Intrinsic::gcwrite:
4886   case Intrinsic::gcread:
4887     if (ID == Intrinsic::gcroot) {
4888       AllocaInst *AI =
4889           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
4890       Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
4891       Assert(isa<Constant>(Call.getArgOperand(1)),
4892              "llvm.gcroot parameter #2 must be a constant.", Call);
4893       if (!AI->getAllocatedType()->isPointerTy()) {
4894         Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
4895                "llvm.gcroot parameter #1 must either be a pointer alloca, "
4896                "or argument #2 must be a non-null constant.",
4897                Call);
4898       }
4899     }
4900 
4901     Assert(Call.getParent()->getParent()->hasGC(),
4902            "Enclosing function does not use GC.", Call);
4903     break;
4904   case Intrinsic::init_trampoline:
4905     Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
4906            "llvm.init_trampoline parameter #2 must resolve to a function.",
4907            Call);
4908     break;
4909   case Intrinsic::prefetch:
4910     Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 &&
4911            cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
4912            "invalid arguments to llvm.prefetch", Call);
4913     break;
4914   case Intrinsic::stackprotector:
4915     Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
4916            "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
4917     break;
4918   case Intrinsic::localescape: {
4919     BasicBlock *BB = Call.getParent();
4920     Assert(BB == &BB->getParent()->front(),
4921            "llvm.localescape used outside of entry block", Call);
4922     Assert(!SawFrameEscape,
4923            "multiple calls to llvm.localescape in one function", Call);
4924     for (Value *Arg : Call.args()) {
4925       if (isa<ConstantPointerNull>(Arg))
4926         continue; // Null values are allowed as placeholders.
4927       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
4928       Assert(AI && AI->isStaticAlloca(),
4929              "llvm.localescape only accepts static allocas", Call);
4930     }
4931     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
4932     SawFrameEscape = true;
4933     break;
4934   }
4935   case Intrinsic::localrecover: {
4936     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
4937     Function *Fn = dyn_cast<Function>(FnArg);
4938     Assert(Fn && !Fn->isDeclaration(),
4939            "llvm.localrecover first "
4940            "argument must be function defined in this module",
4941            Call);
4942     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
4943     auto &Entry = FrameEscapeInfo[Fn];
4944     Entry.second = unsigned(
4945         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
4946     break;
4947   }
4948 
4949   case Intrinsic::experimental_gc_statepoint:
4950     if (auto *CI = dyn_cast<CallInst>(&Call))
4951       Assert(!CI->isInlineAsm(),
4952              "gc.statepoint support for inline assembly unimplemented", CI);
4953     Assert(Call.getParent()->getParent()->hasGC(),
4954            "Enclosing function does not use GC.", Call);
4955 
4956     verifyStatepoint(Call);
4957     break;
4958   case Intrinsic::experimental_gc_result: {
4959     Assert(Call.getParent()->getParent()->hasGC(),
4960            "Enclosing function does not use GC.", Call);
4961     // Are we tied to a statepoint properly?
4962     const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0));
4963     const Function *StatepointFn =
4964         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
4965     Assert(StatepointFn && StatepointFn->isDeclaration() &&
4966                StatepointFn->getIntrinsicID() ==
4967                    Intrinsic::experimental_gc_statepoint,
4968            "gc.result operand #1 must be from a statepoint", Call,
4969            Call.getArgOperand(0));
4970 
4971     // Assert that result type matches wrapped callee.
4972     const Value *Target = StatepointCall->getArgOperand(2);
4973     auto *PT = cast<PointerType>(Target->getType());
4974     auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
4975     Assert(Call.getType() == TargetFuncType->getReturnType(),
4976            "gc.result result type does not match wrapped callee", Call);
4977     break;
4978   }
4979   case Intrinsic::experimental_gc_relocate: {
4980     Assert(Call.arg_size() == 3, "wrong number of arguments", Call);
4981 
4982     Assert(isa<PointerType>(Call.getType()->getScalarType()),
4983            "gc.relocate must return a pointer or a vector of pointers", Call);
4984 
4985     // Check that this relocate is correctly tied to the statepoint
4986 
4987     // This is case for relocate on the unwinding path of an invoke statepoint
4988     if (LandingPadInst *LandingPad =
4989             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
4990 
4991       const BasicBlock *InvokeBB =
4992           LandingPad->getParent()->getUniquePredecessor();
4993 
4994       // Landingpad relocates should have only one predecessor with invoke
4995       // statepoint terminator
4996       Assert(InvokeBB, "safepoints should have unique landingpads",
4997              LandingPad->getParent());
4998       Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
4999              InvokeBB);
5000       Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()),
5001              "gc relocate should be linked to a statepoint", InvokeBB);
5002     } else {
5003       // In all other cases relocate should be tied to the statepoint directly.
5004       // This covers relocates on a normal return path of invoke statepoint and
5005       // relocates of a call statepoint.
5006       auto Token = Call.getArgOperand(0);
5007       Assert(isa<GCStatepointInst>(Token),
5008              "gc relocate is incorrectly tied to the statepoint", Call, Token);
5009     }
5010 
5011     // Verify rest of the relocate arguments.
5012     const CallBase &StatepointCall =
5013       *cast<GCRelocateInst>(Call).getStatepoint();
5014 
5015     // Both the base and derived must be piped through the safepoint.
5016     Value *Base = Call.getArgOperand(1);
5017     Assert(isa<ConstantInt>(Base),
5018            "gc.relocate operand #2 must be integer offset", Call);
5019 
5020     Value *Derived = Call.getArgOperand(2);
5021     Assert(isa<ConstantInt>(Derived),
5022            "gc.relocate operand #3 must be integer offset", Call);
5023 
5024     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
5025     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
5026 
5027     // Check the bounds
5028     if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) {
5029       Assert(BaseIndex < Opt->Inputs.size(),
5030              "gc.relocate: statepoint base index out of bounds", Call);
5031       Assert(DerivedIndex < Opt->Inputs.size(),
5032              "gc.relocate: statepoint derived index out of bounds", Call);
5033     }
5034 
5035     // Relocated value must be either a pointer type or vector-of-pointer type,
5036     // but gc_relocate does not need to return the same pointer type as the
5037     // relocated pointer. It can be casted to the correct type later if it's
5038     // desired. However, they must have the same address space and 'vectorness'
5039     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5040     Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
5041            "gc.relocate: relocated value must be a gc pointer", Call);
5042 
5043     auto ResultType = Call.getType();
5044     auto DerivedType = Relocate.getDerivedPtr()->getType();
5045     Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
5046            "gc.relocate: vector relocates to vector and pointer to pointer",
5047            Call);
5048     Assert(
5049         ResultType->getPointerAddressSpace() ==
5050             DerivedType->getPointerAddressSpace(),
5051         "gc.relocate: relocating a pointer shouldn't change its address space",
5052         Call);
5053     break;
5054   }
5055   case Intrinsic::eh_exceptioncode:
5056   case Intrinsic::eh_exceptionpointer: {
5057     Assert(isa<CatchPadInst>(Call.getArgOperand(0)),
5058            "eh.exceptionpointer argument must be a catchpad", Call);
5059     break;
5060   }
5061   case Intrinsic::get_active_lane_mask: {
5062     Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a "
5063            "vector", Call);
5064     auto *ElemTy = Call.getType()->getScalarType();
5065     Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not "
5066            "i1", Call);
5067     break;
5068   }
5069   case Intrinsic::masked_load: {
5070     Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector",
5071            Call);
5072 
5073     Value *Ptr = Call.getArgOperand(0);
5074     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
5075     Value *Mask = Call.getArgOperand(2);
5076     Value *PassThru = Call.getArgOperand(3);
5077     Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
5078            Call);
5079     Assert(Alignment->getValue().isPowerOf2(),
5080            "masked_load: alignment must be a power of 2", Call);
5081 
5082     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5083     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),
5084            "masked_load: return must match pointer type", Call);
5085     Assert(PassThru->getType() == Call.getType(),
5086            "masked_load: pass through and return type must match", Call);
5087     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5088                cast<VectorType>(Call.getType())->getElementCount(),
5089            "masked_load: vector mask must be same length as return", Call);
5090     break;
5091   }
5092   case Intrinsic::masked_store: {
5093     Value *Val = Call.getArgOperand(0);
5094     Value *Ptr = Call.getArgOperand(1);
5095     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
5096     Value *Mask = Call.getArgOperand(3);
5097     Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
5098            Call);
5099     Assert(Alignment->getValue().isPowerOf2(),
5100            "masked_store: alignment must be a power of 2", Call);
5101 
5102     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
5103     Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),
5104            "masked_store: storee must match pointer type", Call);
5105     Assert(cast<VectorType>(Mask->getType())->getElementCount() ==
5106                cast<VectorType>(Val->getType())->getElementCount(),
5107            "masked_store: vector mask must be same length as value", Call);
5108     break;
5109   }
5110 
5111   case Intrinsic::masked_gather: {
5112     const APInt &Alignment =
5113         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
5114     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
5115            "masked_gather: alignment must be 0 or a power of 2", Call);
5116     break;
5117   }
5118   case Intrinsic::masked_scatter: {
5119     const APInt &Alignment =
5120         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
5121     Assert(Alignment.isZero() || Alignment.isPowerOf2(),
5122            "masked_scatter: alignment must be 0 or a power of 2", Call);
5123     break;
5124   }
5125 
5126   case Intrinsic::experimental_guard: {
5127     Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
5128     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
5129            "experimental_guard must have exactly one "
5130            "\"deopt\" operand bundle");
5131     break;
5132   }
5133 
5134   case Intrinsic::experimental_deoptimize: {
5135     Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
5136            Call);
5137     Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
5138            "experimental_deoptimize must have exactly one "
5139            "\"deopt\" operand bundle");
5140     Assert(Call.getType() == Call.getFunction()->getReturnType(),
5141            "experimental_deoptimize return type must match caller return type");
5142 
5143     if (isa<CallInst>(Call)) {
5144       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
5145       Assert(RI,
5146              "calls to experimental_deoptimize must be followed by a return");
5147 
5148       if (!Call.getType()->isVoidTy() && RI)
5149         Assert(RI->getReturnValue() == &Call,
5150                "calls to experimental_deoptimize must be followed by a return "
5151                "of the value computed by experimental_deoptimize");
5152     }
5153 
5154     break;
5155   }
5156   case Intrinsic::vector_reduce_and:
5157   case Intrinsic::vector_reduce_or:
5158   case Intrinsic::vector_reduce_xor:
5159   case Intrinsic::vector_reduce_add:
5160   case Intrinsic::vector_reduce_mul:
5161   case Intrinsic::vector_reduce_smax:
5162   case Intrinsic::vector_reduce_smin:
5163   case Intrinsic::vector_reduce_umax:
5164   case Intrinsic::vector_reduce_umin: {
5165     Type *ArgTy = Call.getArgOperand(0)->getType();
5166     Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5167            "Intrinsic has incorrect argument type!");
5168     break;
5169   }
5170   case Intrinsic::vector_reduce_fmax:
5171   case Intrinsic::vector_reduce_fmin: {
5172     Type *ArgTy = Call.getArgOperand(0)->getType();
5173     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5174            "Intrinsic has incorrect argument type!");
5175     break;
5176   }
5177   case Intrinsic::vector_reduce_fadd:
5178   case Intrinsic::vector_reduce_fmul: {
5179     // Unlike the other reductions, the first argument is a start value. The
5180     // second argument is the vector to be reduced.
5181     Type *ArgTy = Call.getArgOperand(1)->getType();
5182     Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5183            "Intrinsic has incorrect argument type!");
5184     break;
5185   }
5186   case Intrinsic::smul_fix:
5187   case Intrinsic::smul_fix_sat:
5188   case Intrinsic::umul_fix:
5189   case Intrinsic::umul_fix_sat:
5190   case Intrinsic::sdiv_fix:
5191   case Intrinsic::sdiv_fix_sat:
5192   case Intrinsic::udiv_fix:
5193   case Intrinsic::udiv_fix_sat: {
5194     Value *Op1 = Call.getArgOperand(0);
5195     Value *Op2 = Call.getArgOperand(1);
5196     Assert(Op1->getType()->isIntOrIntVectorTy(),
5197            "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5198            "vector of ints");
5199     Assert(Op2->getType()->isIntOrIntVectorTy(),
5200            "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5201            "vector of ints");
5202 
5203     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5204     Assert(Op3->getType()->getBitWidth() <= 32,
5205            "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
5206 
5207     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
5208         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
5209       Assert(
5210           Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5211           "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5212           "the operands");
5213     } else {
5214       Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5215              "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5216              "to the width of the operands");
5217     }
5218     break;
5219   }
5220   case Intrinsic::lround:
5221   case Intrinsic::llround:
5222   case Intrinsic::lrint:
5223   case Intrinsic::llrint: {
5224     Type *ValTy = Call.getArgOperand(0)->getType();
5225     Type *ResultTy = Call.getType();
5226     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5227            "Intrinsic does not support vectors", &Call);
5228     break;
5229   }
5230   case Intrinsic::bswap: {
5231     Type *Ty = Call.getType();
5232     unsigned Size = Ty->getScalarSizeInBits();
5233     Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
5234     break;
5235   }
5236   case Intrinsic::invariant_start: {
5237     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
5238     Assert(InvariantSize &&
5239                (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5240            "invariant_start parameter must be -1, 0 or a positive number",
5241            &Call);
5242     break;
5243   }
5244   case Intrinsic::matrix_multiply:
5245   case Intrinsic::matrix_transpose:
5246   case Intrinsic::matrix_column_major_load:
5247   case Intrinsic::matrix_column_major_store: {
5248     Function *IF = Call.getCalledFunction();
5249     ConstantInt *Stride = nullptr;
5250     ConstantInt *NumRows;
5251     ConstantInt *NumColumns;
5252     VectorType *ResultTy;
5253     Type *Op0ElemTy = nullptr;
5254     Type *Op1ElemTy = nullptr;
5255     switch (ID) {
5256     case Intrinsic::matrix_multiply:
5257       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
5258       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5259       ResultTy = cast<VectorType>(Call.getType());
5260       Op0ElemTy =
5261           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5262       Op1ElemTy =
5263           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
5264       break;
5265     case Intrinsic::matrix_transpose:
5266       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
5267       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
5268       ResultTy = cast<VectorType>(Call.getType());
5269       Op0ElemTy =
5270           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5271       break;
5272     case Intrinsic::matrix_column_major_load:
5273       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
5274       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
5275       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
5276       ResultTy = cast<VectorType>(Call.getType());
5277       Op0ElemTy =
5278           cast<PointerType>(Call.getArgOperand(0)->getType())->getElementType();
5279       break;
5280     case Intrinsic::matrix_column_major_store:
5281       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
5282       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
5283       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
5284       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
5285       Op0ElemTy =
5286           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
5287       Op1ElemTy =
5288           cast<PointerType>(Call.getArgOperand(1)->getType())->getElementType();
5289       break;
5290     default:
5291       llvm_unreachable("unexpected intrinsic");
5292     }
5293 
5294     Assert(ResultTy->getElementType()->isIntegerTy() ||
5295            ResultTy->getElementType()->isFloatingPointTy(),
5296            "Result type must be an integer or floating-point type!", IF);
5297 
5298     Assert(ResultTy->getElementType() == Op0ElemTy,
5299            "Vector element type mismatch of the result and first operand "
5300            "vector!", IF);
5301 
5302     if (Op1ElemTy)
5303       Assert(ResultTy->getElementType() == Op1ElemTy,
5304              "Vector element type mismatch of the result and second operand "
5305              "vector!", IF);
5306 
5307     Assert(cast<FixedVectorType>(ResultTy)->getNumElements() ==
5308                NumRows->getZExtValue() * NumColumns->getZExtValue(),
5309            "Result of a matrix operation does not fit in the returned vector!");
5310 
5311     if (Stride)
5312       Assert(Stride->getZExtValue() >= NumRows->getZExtValue(),
5313              "Stride must be greater or equal than the number of rows!", IF);
5314 
5315     break;
5316   }
5317   case Intrinsic::experimental_stepvector: {
5318     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
5319     Assert(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5320                VecTy->getScalarSizeInBits() >= 8,
5321            "experimental_stepvector only supported for vectors of integers "
5322            "with a bitwidth of at least 8.",
5323            &Call);
5324     break;
5325   }
5326   case Intrinsic::experimental_vector_insert: {
5327     Value *Vec = Call.getArgOperand(0);
5328     Value *SubVec = Call.getArgOperand(1);
5329     Value *Idx = Call.getArgOperand(2);
5330     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5331 
5332     VectorType *VecTy = cast<VectorType>(Vec->getType());
5333     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5334 
5335     ElementCount VecEC = VecTy->getElementCount();
5336     ElementCount SubVecEC = SubVecTy->getElementCount();
5337     Assert(VecTy->getElementType() == SubVecTy->getElementType(),
5338            "experimental_vector_insert parameters must have the same element "
5339            "type.",
5340            &Call);
5341     Assert(IdxN % SubVecEC.getKnownMinValue() == 0,
5342            "experimental_vector_insert index must be a constant multiple of "
5343            "the subvector's known minimum vector length.");
5344 
5345     // If this insertion is not the 'mixed' case where a fixed vector is
5346     // inserted into a scalable vector, ensure that the insertion of the
5347     // subvector does not overrun the parent vector.
5348     if (VecEC.isScalable() == SubVecEC.isScalable()) {
5349       Assert(
5350           IdxN < VecEC.getKnownMinValue() &&
5351               IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5352           "subvector operand of experimental_vector_insert would overrun the "
5353           "vector being inserted into.");
5354     }
5355     break;
5356   }
5357   case Intrinsic::experimental_vector_extract: {
5358     Value *Vec = Call.getArgOperand(0);
5359     Value *Idx = Call.getArgOperand(1);
5360     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5361 
5362     VectorType *ResultTy = cast<VectorType>(Call.getType());
5363     VectorType *VecTy = cast<VectorType>(Vec->getType());
5364 
5365     ElementCount VecEC = VecTy->getElementCount();
5366     ElementCount ResultEC = ResultTy->getElementCount();
5367 
5368     Assert(ResultTy->getElementType() == VecTy->getElementType(),
5369            "experimental_vector_extract result must have the same element "
5370            "type as the input vector.",
5371            &Call);
5372     Assert(IdxN % ResultEC.getKnownMinValue() == 0,
5373            "experimental_vector_extract index must be a constant multiple of "
5374            "the result type's known minimum vector length.");
5375 
5376     // If this extraction is not the 'mixed' case where a fixed vector is is
5377     // extracted from a scalable vector, ensure that the extraction does not
5378     // overrun the parent vector.
5379     if (VecEC.isScalable() == ResultEC.isScalable()) {
5380       Assert(IdxN < VecEC.getKnownMinValue() &&
5381                  IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
5382              "experimental_vector_extract would overrun.");
5383     }
5384     break;
5385   }
5386   case Intrinsic::experimental_noalias_scope_decl: {
5387     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5388     break;
5389   }
5390   case Intrinsic::preserve_array_access_index:
5391   case Intrinsic::preserve_struct_access_index: {
5392     Type *ElemTy = Call.getAttributes().getParamElementType(0);
5393     Assert(ElemTy,
5394            "Intrinsic requires elementtype attribute on first argument.",
5395            &Call);
5396     break;
5397   }
5398   };
5399 }
5400 
5401 /// Carefully grab the subprogram from a local scope.
5402 ///
5403 /// This carefully grabs the subprogram from a local scope, avoiding the
5404 /// built-in assertions that would typically fire.
5405 static DISubprogram *getSubprogram(Metadata *LocalScope) {
5406   if (!LocalScope)
5407     return nullptr;
5408 
5409   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
5410     return SP;
5411 
5412   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
5413     return getSubprogram(LB->getRawScope());
5414 
5415   // Just return null; broken scope chains are checked elsewhere.
5416   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
5417   return nullptr;
5418 }
5419 
5420 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5421   unsigned NumOperands;
5422   bool HasRoundingMD;
5423   switch (FPI.getIntrinsicID()) {
5424 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
5425   case Intrinsic::INTRINSIC:                                                   \
5426     NumOperands = NARG;                                                        \
5427     HasRoundingMD = ROUND_MODE;                                                \
5428     break;
5429 #include "llvm/IR/ConstrainedOps.def"
5430   default:
5431     llvm_unreachable("Invalid constrained FP intrinsic!");
5432   }
5433   NumOperands += (1 + HasRoundingMD);
5434   // Compare intrinsics carry an extra predicate metadata operand.
5435   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5436     NumOperands += 1;
5437   Assert((FPI.arg_size() == NumOperands),
5438          "invalid arguments for constrained FP intrinsic", &FPI);
5439 
5440   switch (FPI.getIntrinsicID()) {
5441   case Intrinsic::experimental_constrained_lrint:
5442   case Intrinsic::experimental_constrained_llrint: {
5443     Type *ValTy = FPI.getArgOperand(0)->getType();
5444     Type *ResultTy = FPI.getType();
5445     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5446            "Intrinsic does not support vectors", &FPI);
5447   }
5448     break;
5449 
5450   case Intrinsic::experimental_constrained_lround:
5451   case Intrinsic::experimental_constrained_llround: {
5452     Type *ValTy = FPI.getArgOperand(0)->getType();
5453     Type *ResultTy = FPI.getType();
5454     Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
5455            "Intrinsic does not support vectors", &FPI);
5456     break;
5457   }
5458 
5459   case Intrinsic::experimental_constrained_fcmp:
5460   case Intrinsic::experimental_constrained_fcmps: {
5461     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
5462     Assert(CmpInst::isFPPredicate(Pred),
5463            "invalid predicate for constrained FP comparison intrinsic", &FPI);
5464     break;
5465   }
5466 
5467   case Intrinsic::experimental_constrained_fptosi:
5468   case Intrinsic::experimental_constrained_fptoui: {
5469     Value *Operand = FPI.getArgOperand(0);
5470     uint64_t NumSrcElem = 0;
5471     Assert(Operand->getType()->isFPOrFPVectorTy(),
5472            "Intrinsic first argument must be floating point", &FPI);
5473     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5474       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5475     }
5476 
5477     Operand = &FPI;
5478     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5479            "Intrinsic first argument and result disagree on vector use", &FPI);
5480     Assert(Operand->getType()->isIntOrIntVectorTy(),
5481            "Intrinsic result must be an integer", &FPI);
5482     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5483       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5484              "Intrinsic first argument and result vector lengths must be equal",
5485              &FPI);
5486     }
5487   }
5488     break;
5489 
5490   case Intrinsic::experimental_constrained_sitofp:
5491   case Intrinsic::experimental_constrained_uitofp: {
5492     Value *Operand = FPI.getArgOperand(0);
5493     uint64_t NumSrcElem = 0;
5494     Assert(Operand->getType()->isIntOrIntVectorTy(),
5495            "Intrinsic first argument must be integer", &FPI);
5496     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5497       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5498     }
5499 
5500     Operand = &FPI;
5501     Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5502            "Intrinsic first argument and result disagree on vector use", &FPI);
5503     Assert(Operand->getType()->isFPOrFPVectorTy(),
5504            "Intrinsic result must be a floating point", &FPI);
5505     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5506       Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
5507              "Intrinsic first argument and result vector lengths must be equal",
5508              &FPI);
5509     }
5510   } break;
5511 
5512   case Intrinsic::experimental_constrained_fptrunc:
5513   case Intrinsic::experimental_constrained_fpext: {
5514     Value *Operand = FPI.getArgOperand(0);
5515     Type *OperandTy = Operand->getType();
5516     Value *Result = &FPI;
5517     Type *ResultTy = Result->getType();
5518     Assert(OperandTy->isFPOrFPVectorTy(),
5519            "Intrinsic first argument must be FP or FP vector", &FPI);
5520     Assert(ResultTy->isFPOrFPVectorTy(),
5521            "Intrinsic result must be FP or FP vector", &FPI);
5522     Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
5523            "Intrinsic first argument and result disagree on vector use", &FPI);
5524     if (OperandTy->isVectorTy()) {
5525       Assert(cast<FixedVectorType>(OperandTy)->getNumElements() ==
5526                  cast<FixedVectorType>(ResultTy)->getNumElements(),
5527              "Intrinsic first argument and result vector lengths must be equal",
5528              &FPI);
5529     }
5530     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
5531       Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
5532              "Intrinsic first argument's type must be larger than result type",
5533              &FPI);
5534     } else {
5535       Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
5536              "Intrinsic first argument's type must be smaller than result type",
5537              &FPI);
5538     }
5539   }
5540     break;
5541 
5542   default:
5543     break;
5544   }
5545 
5546   // If a non-metadata argument is passed in a metadata slot then the
5547   // error will be caught earlier when the incorrect argument doesn't
5548   // match the specification in the intrinsic call table. Thus, no
5549   // argument type check is needed here.
5550 
5551   Assert(FPI.getExceptionBehavior().hasValue(),
5552          "invalid exception behavior argument", &FPI);
5553   if (HasRoundingMD) {
5554     Assert(FPI.getRoundingMode().hasValue(),
5555            "invalid rounding mode argument", &FPI);
5556   }
5557 }
5558 
5559 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
5560   auto *MD = DII.getRawLocation();
5561   AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
5562                (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
5563            "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
5564   AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
5565          "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
5566          DII.getRawVariable());
5567   AssertDI(isa<DIExpression>(DII.getRawExpression()),
5568          "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
5569          DII.getRawExpression());
5570 
5571   // Ignore broken !dbg attachments; they're checked elsewhere.
5572   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
5573     if (!isa<DILocation>(N))
5574       return;
5575 
5576   BasicBlock *BB = DII.getParent();
5577   Function *F = BB ? BB->getParent() : nullptr;
5578 
5579   // The scopes for variables and !dbg attachments must agree.
5580   DILocalVariable *Var = DII.getVariable();
5581   DILocation *Loc = DII.getDebugLoc();
5582   AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
5583            &DII, BB, F);
5584 
5585   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
5586   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5587   if (!VarSP || !LocSP)
5588     return; // Broken scope chains are checked elsewhere.
5589 
5590   AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
5591                                " variable and !dbg attachment",
5592            &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
5593            Loc->getScope()->getSubprogram());
5594 
5595   // This check is redundant with one in visitLocalVariable().
5596   AssertDI(isType(Var->getRawType()), "invalid type ref", Var,
5597            Var->getRawType());
5598   verifyFnArgs(DII);
5599 }
5600 
5601 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
5602   AssertDI(isa<DILabel>(DLI.getRawLabel()),
5603          "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
5604          DLI.getRawLabel());
5605 
5606   // Ignore broken !dbg attachments; they're checked elsewhere.
5607   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
5608     if (!isa<DILocation>(N))
5609       return;
5610 
5611   BasicBlock *BB = DLI.getParent();
5612   Function *F = BB ? BB->getParent() : nullptr;
5613 
5614   // The scopes for variables and !dbg attachments must agree.
5615   DILabel *Label = DLI.getLabel();
5616   DILocation *Loc = DLI.getDebugLoc();
5617   Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
5618          &DLI, BB, F);
5619 
5620   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
5621   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
5622   if (!LabelSP || !LocSP)
5623     return;
5624 
5625   AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
5626                              " label and !dbg attachment",
5627            &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
5628            Loc->getScope()->getSubprogram());
5629 }
5630 
5631 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
5632   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
5633   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5634 
5635   // We don't know whether this intrinsic verified correctly.
5636   if (!V || !E || !E->isValid())
5637     return;
5638 
5639   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
5640   auto Fragment = E->getFragmentInfo();
5641   if (!Fragment)
5642     return;
5643 
5644   // The frontend helps out GDB by emitting the members of local anonymous
5645   // unions as artificial local variables with shared storage. When SROA splits
5646   // the storage for artificial local variables that are smaller than the entire
5647   // union, the overhang piece will be outside of the allotted space for the
5648   // variable and this check fails.
5649   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
5650   if (V->isArtificial())
5651     return;
5652 
5653   verifyFragmentExpression(*V, *Fragment, &I);
5654 }
5655 
5656 template <typename ValueOrMetadata>
5657 void Verifier::verifyFragmentExpression(const DIVariable &V,
5658                                         DIExpression::FragmentInfo Fragment,
5659                                         ValueOrMetadata *Desc) {
5660   // If there's no size, the type is broken, but that should be checked
5661   // elsewhere.
5662   auto VarSize = V.getSizeInBits();
5663   if (!VarSize)
5664     return;
5665 
5666   unsigned FragSize = Fragment.SizeInBits;
5667   unsigned FragOffset = Fragment.OffsetInBits;
5668   AssertDI(FragSize + FragOffset <= *VarSize,
5669          "fragment is larger than or outside of variable", Desc, &V);
5670   AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
5671 }
5672 
5673 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
5674   // This function does not take the scope of noninlined function arguments into
5675   // account. Don't run it if current function is nodebug, because it may
5676   // contain inlined debug intrinsics.
5677   if (!HasDebugInfo)
5678     return;
5679 
5680   // For performance reasons only check non-inlined ones.
5681   if (I.getDebugLoc()->getInlinedAt())
5682     return;
5683 
5684   DILocalVariable *Var = I.getVariable();
5685   AssertDI(Var, "dbg intrinsic without variable");
5686 
5687   unsigned ArgNo = Var->getArg();
5688   if (!ArgNo)
5689     return;
5690 
5691   // Verify there are no duplicate function argument debug info entries.
5692   // These will cause hard-to-debug assertions in the DWARF backend.
5693   if (DebugFnArgs.size() < ArgNo)
5694     DebugFnArgs.resize(ArgNo, nullptr);
5695 
5696   auto *Prev = DebugFnArgs[ArgNo - 1];
5697   DebugFnArgs[ArgNo - 1] = Var;
5698   AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
5699            Prev, Var);
5700 }
5701 
5702 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
5703   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
5704 
5705   // We don't know whether this intrinsic verified correctly.
5706   if (!E || !E->isValid())
5707     return;
5708 
5709   AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
5710 }
5711 
5712 void Verifier::verifyCompileUnits() {
5713   // When more than one Module is imported into the same context, such as during
5714   // an LTO build before linking the modules, ODR type uniquing may cause types
5715   // to point to a different CU. This check does not make sense in this case.
5716   if (M.getContext().isODRUniquingDebugTypes())
5717     return;
5718   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
5719   SmallPtrSet<const Metadata *, 2> Listed;
5720   if (CUs)
5721     Listed.insert(CUs->op_begin(), CUs->op_end());
5722   for (auto *CU : CUVisited)
5723     AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
5724   CUVisited.clear();
5725 }
5726 
5727 void Verifier::verifyDeoptimizeCallingConvs() {
5728   if (DeoptimizeDeclarations.empty())
5729     return;
5730 
5731   const Function *First = DeoptimizeDeclarations[0];
5732   for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
5733     Assert(First->getCallingConv() == F->getCallingConv(),
5734            "All llvm.experimental.deoptimize declarations must have the same "
5735            "calling convention",
5736            First, F);
5737   }
5738 }
5739 
5740 void Verifier::verifyAttachedCallBundle(const CallBase &Call,
5741                                         const OperandBundleUse &BU) {
5742   FunctionType *FTy = Call.getFunctionType();
5743 
5744   Assert((FTy->getReturnType()->isPointerTy() ||
5745           (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
5746          "a call with operand bundle \"clang.arc.attachedcall\" must call a "
5747          "function returning a pointer or a non-returning function that has a "
5748          "void return type",
5749          Call);
5750 
5751   Assert((BU.Inputs.empty() ||
5752           (BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()))),
5753          "operand bundle \"clang.arc.attachedcall\" can take either no "
5754          "arguments or one function as an argument",
5755          Call);
5756 
5757   if (BU.Inputs.empty())
5758     return;
5759 
5760   auto *Fn = cast<Function>(BU.Inputs.front());
5761   Intrinsic::ID IID = Fn->getIntrinsicID();
5762 
5763   if (IID) {
5764     Assert((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
5765             IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
5766            "invalid function argument", Call);
5767   } else {
5768     StringRef FnName = Fn->getName();
5769     Assert((FnName == "objc_retainAutoreleasedReturnValue" ||
5770             FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
5771            "invalid function argument", Call);
5772   }
5773 }
5774 
5775 void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
5776   bool HasSource = F.getSource().hasValue();
5777   if (!HasSourceDebugInfo.count(&U))
5778     HasSourceDebugInfo[&U] = HasSource;
5779   AssertDI(HasSource == HasSourceDebugInfo[&U],
5780            "inconsistent use of embedded source");
5781 }
5782 
5783 void Verifier::verifyNoAliasScopeDecl() {
5784   if (NoAliasScopeDecls.empty())
5785     return;
5786 
5787   // only a single scope must be declared at a time.
5788   for (auto *II : NoAliasScopeDecls) {
5789     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
5790            "Not a llvm.experimental.noalias.scope.decl ?");
5791     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
5792         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5793     Assert(ScopeListMV != nullptr,
5794            "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
5795            "argument",
5796            II);
5797 
5798     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
5799     Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode",
5800            II);
5801     Assert(ScopeListMD->getNumOperands() == 1,
5802            "!id.scope.list must point to a list with a single scope", II);
5803     visitAliasScopeListMetadata(ScopeListMD);
5804   }
5805 
5806   // Only check the domination rule when requested. Once all passes have been
5807   // adapted this option can go away.
5808   if (!VerifyNoAliasScopeDomination)
5809     return;
5810 
5811   // Now sort the intrinsics based on the scope MDNode so that declarations of
5812   // the same scopes are next to each other.
5813   auto GetScope = [](IntrinsicInst *II) {
5814     const auto *ScopeListMV = cast<MetadataAsValue>(
5815         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
5816     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
5817   };
5818 
5819   // We are sorting on MDNode pointers here. For valid input IR this is ok.
5820   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
5821   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
5822     return GetScope(Lhs) < GetScope(Rhs);
5823   };
5824 
5825   llvm::sort(NoAliasScopeDecls, Compare);
5826 
5827   // Go over the intrinsics and check that for the same scope, they are not
5828   // dominating each other.
5829   auto ItCurrent = NoAliasScopeDecls.begin();
5830   while (ItCurrent != NoAliasScopeDecls.end()) {
5831     auto CurScope = GetScope(*ItCurrent);
5832     auto ItNext = ItCurrent;
5833     do {
5834       ++ItNext;
5835     } while (ItNext != NoAliasScopeDecls.end() &&
5836              GetScope(*ItNext) == CurScope);
5837 
5838     // [ItCurrent, ItNext) represents the declarations for the same scope.
5839     // Ensure they are not dominating each other.. but only if it is not too
5840     // expensive.
5841     if (ItNext - ItCurrent < 32)
5842       for (auto *I : llvm::make_range(ItCurrent, ItNext))
5843         for (auto *J : llvm::make_range(ItCurrent, ItNext))
5844           if (I != J)
5845             Assert(!DT.dominates(I, J),
5846                    "llvm.experimental.noalias.scope.decl dominates another one "
5847                    "with the same scope",
5848                    I);
5849     ItCurrent = ItNext;
5850   }
5851 }
5852 
5853 //===----------------------------------------------------------------------===//
5854 //  Implement the public interfaces to this file...
5855 //===----------------------------------------------------------------------===//
5856 
5857 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
5858   Function &F = const_cast<Function &>(f);
5859 
5860   // Don't use a raw_null_ostream.  Printing IR is expensive.
5861   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
5862 
5863   // Note that this function's return value is inverted from what you would
5864   // expect of a function called "verify".
5865   return !V.verify(F);
5866 }
5867 
5868 bool llvm::verifyModule(const Module &M, raw_ostream *OS,
5869                         bool *BrokenDebugInfo) {
5870   // Don't use a raw_null_ostream.  Printing IR is expensive.
5871   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
5872 
5873   bool Broken = false;
5874   for (const Function &F : M)
5875     Broken |= !V.verify(F);
5876 
5877   Broken |= !V.verify();
5878   if (BrokenDebugInfo)
5879     *BrokenDebugInfo = V.hasBrokenDebugInfo();
5880   // Note that this function's return value is inverted from what you would
5881   // expect of a function called "verify".
5882   return Broken;
5883 }
5884 
5885 namespace {
5886 
5887 struct VerifierLegacyPass : public FunctionPass {
5888   static char ID;
5889 
5890   std::unique_ptr<Verifier> V;
5891   bool FatalErrors = true;
5892 
5893   VerifierLegacyPass() : FunctionPass(ID) {
5894     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5895   }
5896   explicit VerifierLegacyPass(bool FatalErrors)
5897       : FunctionPass(ID),
5898         FatalErrors(FatalErrors) {
5899     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5900   }
5901 
5902   bool doInitialization(Module &M) override {
5903     V = std::make_unique<Verifier>(
5904         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
5905     return false;
5906   }
5907 
5908   bool runOnFunction(Function &F) override {
5909     if (!V->verify(F) && FatalErrors) {
5910       errs() << "in function " << F.getName() << '\n';
5911       report_fatal_error("Broken function found, compilation aborted!");
5912     }
5913     return false;
5914   }
5915 
5916   bool doFinalization(Module &M) override {
5917     bool HasErrors = false;
5918     for (Function &F : M)
5919       if (F.isDeclaration())
5920         HasErrors |= !V->verify(F);
5921 
5922     HasErrors |= !V->verify();
5923     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
5924       report_fatal_error("Broken module found, compilation aborted!");
5925     return false;
5926   }
5927 
5928   void getAnalysisUsage(AnalysisUsage &AU) const override {
5929     AU.setPreservesAll();
5930   }
5931 };
5932 
5933 } // end anonymous namespace
5934 
5935 /// Helper to issue failure from the TBAA verification
5936 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
5937   if (Diagnostic)
5938     return Diagnostic->CheckFailed(Args...);
5939 }
5940 
5941 #define AssertTBAA(C, ...)                                                     \
5942   do {                                                                         \
5943     if (!(C)) {                                                                \
5944       CheckFailed(__VA_ARGS__);                                                \
5945       return false;                                                            \
5946     }                                                                          \
5947   } while (false)
5948 
5949 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
5950 /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
5951 /// struct-type node describing an aggregate data structure (like a struct).
5952 TBAAVerifier::TBAABaseNodeSummary
5953 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
5954                                  bool IsNewFormat) {
5955   if (BaseNode->getNumOperands() < 2) {
5956     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
5957     return {true, ~0u};
5958   }
5959 
5960   auto Itr = TBAABaseNodes.find(BaseNode);
5961   if (Itr != TBAABaseNodes.end())
5962     return Itr->second;
5963 
5964   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
5965   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
5966   (void)InsertResult;
5967   assert(InsertResult.second && "We just checked!");
5968   return Result;
5969 }
5970 
5971 TBAAVerifier::TBAABaseNodeSummary
5972 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
5973                                      bool IsNewFormat) {
5974   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
5975 
5976   if (BaseNode->getNumOperands() == 2) {
5977     // Scalar nodes can only be accessed at offset 0.
5978     return isValidScalarTBAANode(BaseNode)
5979                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
5980                : InvalidNode;
5981   }
5982 
5983   if (IsNewFormat) {
5984     if (BaseNode->getNumOperands() % 3 != 0) {
5985       CheckFailed("Access tag nodes must have the number of operands that is a "
5986                   "multiple of 3!", BaseNode);
5987       return InvalidNode;
5988     }
5989   } else {
5990     if (BaseNode->getNumOperands() % 2 != 1) {
5991       CheckFailed("Struct tag nodes must have an odd number of operands!",
5992                   BaseNode);
5993       return InvalidNode;
5994     }
5995   }
5996 
5997   // Check the type size field.
5998   if (IsNewFormat) {
5999     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6000         BaseNode->getOperand(1));
6001     if (!TypeSizeNode) {
6002       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
6003       return InvalidNode;
6004     }
6005   }
6006 
6007   // Check the type name field. In the new format it can be anything.
6008   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
6009     CheckFailed("Struct tag nodes have a string as their first operand",
6010                 BaseNode);
6011     return InvalidNode;
6012   }
6013 
6014   bool Failed = false;
6015 
6016   Optional<APInt> PrevOffset;
6017   unsigned BitWidth = ~0u;
6018 
6019   // We've already checked that BaseNode is not a degenerate root node with one
6020   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
6021   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6022   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6023   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6024            Idx += NumOpsPerField) {
6025     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
6026     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
6027     if (!isa<MDNode>(FieldTy)) {
6028       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
6029       Failed = true;
6030       continue;
6031     }
6032 
6033     auto *OffsetEntryCI =
6034         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
6035     if (!OffsetEntryCI) {
6036       CheckFailed("Offset entries must be constants!", &I, BaseNode);
6037       Failed = true;
6038       continue;
6039     }
6040 
6041     if (BitWidth == ~0u)
6042       BitWidth = OffsetEntryCI->getBitWidth();
6043 
6044     if (OffsetEntryCI->getBitWidth() != BitWidth) {
6045       CheckFailed(
6046           "Bitwidth between the offsets and struct type entries must match", &I,
6047           BaseNode);
6048       Failed = true;
6049       continue;
6050     }
6051 
6052     // NB! As far as I can tell, we generate a non-strictly increasing offset
6053     // sequence only from structs that have zero size bit fields.  When
6054     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
6055     // pick the field lexically the latest in struct type metadata node.  This
6056     // mirrors the actual behavior of the alias analysis implementation.
6057     bool IsAscending =
6058         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
6059 
6060     if (!IsAscending) {
6061       CheckFailed("Offsets must be increasing!", &I, BaseNode);
6062       Failed = true;
6063     }
6064 
6065     PrevOffset = OffsetEntryCI->getValue();
6066 
6067     if (IsNewFormat) {
6068       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6069           BaseNode->getOperand(Idx + 2));
6070       if (!MemberSizeNode) {
6071         CheckFailed("Member size entries must be constants!", &I, BaseNode);
6072         Failed = true;
6073         continue;
6074       }
6075     }
6076   }
6077 
6078   return Failed ? InvalidNode
6079                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
6080 }
6081 
6082 static bool IsRootTBAANode(const MDNode *MD) {
6083   return MD->getNumOperands() < 2;
6084 }
6085 
6086 static bool IsScalarTBAANodeImpl(const MDNode *MD,
6087                                  SmallPtrSetImpl<const MDNode *> &Visited) {
6088   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
6089     return false;
6090 
6091   if (!isa<MDString>(MD->getOperand(0)))
6092     return false;
6093 
6094   if (MD->getNumOperands() == 3) {
6095     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
6096     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
6097       return false;
6098   }
6099 
6100   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6101   return Parent && Visited.insert(Parent).second &&
6102          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
6103 }
6104 
6105 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
6106   auto ResultIt = TBAAScalarNodes.find(MD);
6107   if (ResultIt != TBAAScalarNodes.end())
6108     return ResultIt->second;
6109 
6110   SmallPtrSet<const MDNode *, 4> Visited;
6111   bool Result = IsScalarTBAANodeImpl(MD, Visited);
6112   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
6113   (void)InsertResult;
6114   assert(InsertResult.second && "Just checked!");
6115 
6116   return Result;
6117 }
6118 
6119 /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
6120 /// Offset in place to be the offset within the field node returned.
6121 ///
6122 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
6123 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
6124                                                    const MDNode *BaseNode,
6125                                                    APInt &Offset,
6126                                                    bool IsNewFormat) {
6127   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
6128 
6129   // Scalar nodes have only one possible "field" -- their parent in the access
6130   // hierarchy.  Offset must be zero at this point, but our caller is supposed
6131   // to Assert that.
6132   if (BaseNode->getNumOperands() == 2)
6133     return cast<MDNode>(BaseNode->getOperand(1));
6134 
6135   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
6136   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
6137   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
6138            Idx += NumOpsPerField) {
6139     auto *OffsetEntryCI =
6140         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
6141     if (OffsetEntryCI->getValue().ugt(Offset)) {
6142       if (Idx == FirstFieldOpNo) {
6143         CheckFailed("Could not find TBAA parent in struct type node", &I,
6144                     BaseNode, &Offset);
6145         return nullptr;
6146       }
6147 
6148       unsigned PrevIdx = Idx - NumOpsPerField;
6149       auto *PrevOffsetEntryCI =
6150           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
6151       Offset -= PrevOffsetEntryCI->getValue();
6152       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
6153     }
6154   }
6155 
6156   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
6157   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
6158       BaseNode->getOperand(LastIdx + 1));
6159   Offset -= LastOffsetEntryCI->getValue();
6160   return cast<MDNode>(BaseNode->getOperand(LastIdx));
6161 }
6162 
6163 static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
6164   if (!Type || Type->getNumOperands() < 3)
6165     return false;
6166 
6167   // In the new format type nodes shall have a reference to the parent type as
6168   // its first operand.
6169   return isa_and_nonnull<MDNode>(Type->getOperand(0));
6170 }
6171 
6172 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
6173   AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
6174                  isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
6175                  isa<AtomicCmpXchgInst>(I),
6176              "This instruction shall not have a TBAA access tag!", &I);
6177 
6178   bool IsStructPathTBAA =
6179       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
6180 
6181   AssertTBAA(
6182       IsStructPathTBAA,
6183       "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
6184 
6185   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
6186   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
6187 
6188   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
6189 
6190   if (IsNewFormat) {
6191     AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
6192                "Access tag metadata must have either 4 or 5 operands", &I, MD);
6193   } else {
6194     AssertTBAA(MD->getNumOperands() < 5,
6195                "Struct tag metadata must have either 3 or 4 operands", &I, MD);
6196   }
6197 
6198   // Check the access size field.
6199   if (IsNewFormat) {
6200     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
6201         MD->getOperand(3));
6202     AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
6203   }
6204 
6205   // Check the immutability flag.
6206   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
6207   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
6208     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
6209         MD->getOperand(ImmutabilityFlagOpNo));
6210     AssertTBAA(IsImmutableCI,
6211                "Immutability tag on struct tag metadata must be a constant",
6212                &I, MD);
6213     AssertTBAA(
6214         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
6215         "Immutability part of the struct tag metadata must be either 0 or 1",
6216         &I, MD);
6217   }
6218 
6219   AssertTBAA(BaseNode && AccessType,
6220              "Malformed struct tag metadata: base and access-type "
6221              "should be non-null and point to Metadata nodes",
6222              &I, MD, BaseNode, AccessType);
6223 
6224   if (!IsNewFormat) {
6225     AssertTBAA(isValidScalarTBAANode(AccessType),
6226                "Access type node must be a valid scalar type", &I, MD,
6227                AccessType);
6228   }
6229 
6230   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
6231   AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
6232 
6233   APInt Offset = OffsetCI->getValue();
6234   bool SeenAccessTypeInPath = false;
6235 
6236   SmallPtrSet<MDNode *, 4> StructPath;
6237 
6238   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
6239        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
6240                                                IsNewFormat)) {
6241     if (!StructPath.insert(BaseNode).second) {
6242       CheckFailed("Cycle detected in struct path", &I, MD);
6243       return false;
6244     }
6245 
6246     bool Invalid;
6247     unsigned BaseNodeBitWidth;
6248     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
6249                                                              IsNewFormat);
6250 
6251     // If the base node is invalid in itself, then we've already printed all the
6252     // errors we wanted to print.
6253     if (Invalid)
6254       return false;
6255 
6256     SeenAccessTypeInPath |= BaseNode == AccessType;
6257 
6258     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
6259       AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
6260                  &I, MD, &Offset);
6261 
6262     AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
6263                    (BaseNodeBitWidth == 0 && Offset == 0) ||
6264                    (IsNewFormat && BaseNodeBitWidth == ~0u),
6265                "Access bit-width not the same as description bit-width", &I, MD,
6266                BaseNodeBitWidth, Offset.getBitWidth());
6267 
6268     if (IsNewFormat && SeenAccessTypeInPath)
6269       break;
6270   }
6271 
6272   AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
6273              &I, MD);
6274   return true;
6275 }
6276 
6277 char VerifierLegacyPass::ID = 0;
6278 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
6279 
6280 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
6281   return new VerifierLegacyPass(FatalErrors);
6282 }
6283 
6284 AnalysisKey VerifierAnalysis::Key;
6285 VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
6286                                                ModuleAnalysisManager &) {
6287   Result Res;
6288   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
6289   return Res;
6290 }
6291 
6292 VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
6293                                                FunctionAnalysisManager &) {
6294   return { llvm::verifyFunction(F, &dbgs()), false };
6295 }
6296 
6297 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
6298   auto Res = AM.getResult<VerifierAnalysis>(M);
6299   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
6300     report_fatal_error("Broken module found, compilation aborted!");
6301 
6302   return PreservedAnalyses::all();
6303 }
6304 
6305 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
6306   auto res = AM.getResult<VerifierAnalysis>(F);
6307   if (res.IRBroken && FatalErrors)
6308     report_fatal_error("Broken function found, compilation aborted!");
6309 
6310   return PreservedAnalyses::all();
6311 }
6312