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