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