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