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