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