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