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