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