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