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