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