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