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