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