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