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