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