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