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