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