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