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