xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the function verifier interface, that can be used for some
104824e7fdSDimitry Andric // basic correctness checking of input to the system.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // Note that this does not provide full `Java style' security and verifications,
130b57cec5SDimitry Andric // instead it just tries to ensure that code is well-formed.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //  * Both of a binary operator's parameters are of the same type
160b57cec5SDimitry Andric //  * Verify that the indices of mem access instructions match other operands
170b57cec5SDimitry Andric //  * Verify that arithmetic and other things are only performed on first-class
180b57cec5SDimitry Andric //    types.  Verify that shifts & logicals only happen on integrals f.e.
190b57cec5SDimitry Andric //  * All of the constants in a switch statement are of the correct type
200b57cec5SDimitry Andric //  * The code is in valid SSA form
210b57cec5SDimitry Andric //  * It should be illegal to put a label into any other type (like a structure)
220b57cec5SDimitry Andric //    or to return one. [except constant arrays!]
230b57cec5SDimitry Andric //  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
240b57cec5SDimitry Andric //  * PHI nodes must have an entry for each predecessor, with no extras.
250b57cec5SDimitry Andric //  * PHI nodes must be the first thing in a basic block, all grouped together
260b57cec5SDimitry Andric //  * All basic blocks should only end with terminator insts, not contain them
270b57cec5SDimitry Andric //  * The entry node to a function must not have predecessors
280b57cec5SDimitry Andric //  * All Instructions must be embedded into a basic block
290b57cec5SDimitry Andric //  * Functions cannot take a void-typed parameter
300b57cec5SDimitry Andric //  * Verify that a function's argument list agrees with it's declared type.
310b57cec5SDimitry Andric //  * It is illegal to specify a name for a void value.
320b57cec5SDimitry Andric //  * It is illegal to have a internal global value with no initializer
330b57cec5SDimitry Andric //  * It is illegal to have a ret instruction that returns a value that does not
340b57cec5SDimitry Andric //    agree with the function return value type.
350b57cec5SDimitry Andric //  * Function call argument types match the function prototype
360b57cec5SDimitry Andric //  * A landing pad is defined by a landingpad instruction, and can be jumped to
370b57cec5SDimitry Andric //    only by the unwind edge of an invoke instruction.
380b57cec5SDimitry Andric //  * A landingpad instruction must be the first non-PHI instruction in the
390b57cec5SDimitry Andric //    block.
400b57cec5SDimitry Andric //  * Landingpad instructions must be in a function with a personality function.
410b57cec5SDimitry Andric //  * All other things that are tested by asserts spread about the code...
420b57cec5SDimitry Andric //
430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
460b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
470b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
480b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
490b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
500b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
510b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
520b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
530b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
540b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
550b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
560b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
570b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
580b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
590b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
600b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
610b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
620b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
630b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
640b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
650b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
660b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
670b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
680b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
690b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
70*bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
710b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
720b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
730b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
740b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
750b57cec5SDimitry Andric #include "llvm/IR/Function.h"
76*bdd1243dSDimitry Andric #include "llvm/IR/GCStrategy.h"
770b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
780b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
790b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
800b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
810b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
820b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
830b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
840b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
850b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
860b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
8781ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
8881ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
89480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
900b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
910b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
920b57cec5SDimitry Andric #include "llvm/IR/Module.h"
930b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
940b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
950b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
960b57cec5SDimitry Andric #include "llvm/IR/Type.h"
970b57cec5SDimitry Andric #include "llvm/IR/Use.h"
980b57cec5SDimitry Andric #include "llvm/IR/User.h"
990b57cec5SDimitry Andric #include "llvm/IR/Value.h"
100480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1010b57cec5SDimitry Andric #include "llvm/Pass.h"
1020b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1030b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1040b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1050b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1060b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
1070b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1080b57cec5SDimitry Andric #include <algorithm>
1090b57cec5SDimitry Andric #include <cassert>
1100b57cec5SDimitry Andric #include <cstdint>
1110b57cec5SDimitry Andric #include <memory>
112*bdd1243dSDimitry Andric #include <optional>
1130b57cec5SDimitry Andric #include <string>
1140b57cec5SDimitry Andric #include <utility>
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric using namespace llvm;
1170b57cec5SDimitry Andric 
118e8d8bef9SDimitry Andric static cl::opt<bool> VerifyNoAliasScopeDomination(
119e8d8bef9SDimitry Andric     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
120e8d8bef9SDimitry Andric     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
121e8d8bef9SDimitry Andric              "scopes are not dominating"));
122e8d8bef9SDimitry Andric 
1230b57cec5SDimitry Andric namespace llvm {
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric struct VerifierSupport {
1260b57cec5SDimitry Andric   raw_ostream *OS;
1270b57cec5SDimitry Andric   const Module &M;
1280b57cec5SDimitry Andric   ModuleSlotTracker MST;
1298bcb0991SDimitry Andric   Triple TT;
1300b57cec5SDimitry Andric   const DataLayout &DL;
1310b57cec5SDimitry Andric   LLVMContext &Context;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1340b57cec5SDimitry Andric   bool Broken = false;
1350b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1360b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1370b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1380b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
1418bcb0991SDimitry Andric       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
1428bcb0991SDimitry Andric         Context(M.getContext()) {}
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric private:
1450b57cec5SDimitry Andric   void Write(const Module *M) {
1460b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1470b57cec5SDimitry Andric   }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   void Write(const Value *V) {
1500b57cec5SDimitry Andric     if (V)
1510b57cec5SDimitry Andric       Write(*V);
1520b57cec5SDimitry Andric   }
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   void Write(const Value &V) {
1550b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1560b57cec5SDimitry Andric       V.print(*OS, MST);
1570b57cec5SDimitry Andric       *OS << '\n';
1580b57cec5SDimitry Andric     } else {
1590b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1600b57cec5SDimitry Andric       *OS << '\n';
1610b57cec5SDimitry Andric     }
1620b57cec5SDimitry Andric   }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   void Write(const Metadata *MD) {
1650b57cec5SDimitry Andric     if (!MD)
1660b57cec5SDimitry Andric       return;
1670b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
1680b57cec5SDimitry Andric     *OS << '\n';
1690b57cec5SDimitry Andric   }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
1720b57cec5SDimitry Andric     Write(MD.get());
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
1760b57cec5SDimitry Andric     if (!NMD)
1770b57cec5SDimitry Andric       return;
1780b57cec5SDimitry Andric     NMD->print(*OS, MST);
1790b57cec5SDimitry Andric     *OS << '\n';
1800b57cec5SDimitry Andric   }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   void Write(Type *T) {
1830b57cec5SDimitry Andric     if (!T)
1840b57cec5SDimitry Andric       return;
1850b57cec5SDimitry Andric     *OS << ' ' << *T;
1860b57cec5SDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   void Write(const Comdat *C) {
1890b57cec5SDimitry Andric     if (!C)
1900b57cec5SDimitry Andric       return;
1910b57cec5SDimitry Andric     *OS << *C;
1920b57cec5SDimitry Andric   }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   void Write(const APInt *AI) {
1950b57cec5SDimitry Andric     if (!AI)
1960b57cec5SDimitry Andric       return;
1970b57cec5SDimitry Andric     *OS << *AI << '\n';
1980b57cec5SDimitry Andric   }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
2010b57cec5SDimitry Andric 
202fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
203fe6060f1SDimitry Andric   void Write(const Attribute *A) {
204fe6060f1SDimitry Andric     if (!A)
205fe6060f1SDimitry Andric       return;
206fe6060f1SDimitry Andric     *OS << A->getAsString() << '\n';
207fe6060f1SDimitry Andric   }
208fe6060f1SDimitry Andric 
209fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
210fe6060f1SDimitry Andric   void Write(const AttributeSet *AS) {
211fe6060f1SDimitry Andric     if (!AS)
212fe6060f1SDimitry Andric       return;
213fe6060f1SDimitry Andric     *OS << AS->getAsString() << '\n';
214fe6060f1SDimitry Andric   }
215fe6060f1SDimitry Andric 
216fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
217fe6060f1SDimitry Andric   void Write(const AttributeList *AL) {
218fe6060f1SDimitry Andric     if (!AL)
219fe6060f1SDimitry Andric       return;
220fe6060f1SDimitry Andric     AL->print(*OS);
221fe6060f1SDimitry Andric   }
222fe6060f1SDimitry Andric 
2230b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
2240b57cec5SDimitry Andric     for (const T &V : Vs)
2250b57cec5SDimitry Andric       Write(V);
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2290b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2300b57cec5SDimitry Andric     Write(V1);
2310b57cec5SDimitry Andric     WriteTs(Vs...);
2320b57cec5SDimitry Andric   }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric public:
2370b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2380b57cec5SDimitry Andric   ///
2390b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2400b57cec5SDimitry Andric   /// something is not correct.
2410b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2420b57cec5SDimitry Andric     if (OS)
2430b57cec5SDimitry Andric       *OS << Message << '\n';
2440b57cec5SDimitry Andric     Broken = true;
2450b57cec5SDimitry Andric   }
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric   /// A check failed (with values to print).
2480b57cec5SDimitry Andric   ///
2490b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2500b57cec5SDimitry Andric   /// breakpoint on.
2510b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2520b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2530b57cec5SDimitry Andric     CheckFailed(Message);
2540b57cec5SDimitry Andric     if (OS)
2550b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2560b57cec5SDimitry Andric   }
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   /// A debug info check failed.
2590b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
2600b57cec5SDimitry Andric     if (OS)
2610b57cec5SDimitry Andric       *OS << Message << '\n';
2620b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
2630b57cec5SDimitry Andric     BrokenDebugInfo = true;
2640b57cec5SDimitry Andric   }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
2670b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2680b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
2690b57cec5SDimitry Andric                             const Ts &... Vs) {
2700b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
2710b57cec5SDimitry Andric     if (OS)
2720b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric };
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric } // namespace llvm
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric namespace {
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
2810b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
2820b57cec5SDimitry Andric 
28381ad6265SDimitry Andric   // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
28481ad6265SDimitry Andric   // the alignment size should not exceed 2^15. Since encode(Align)
28581ad6265SDimitry Andric   // would plus the shift value by 1, the alignment size should
28681ad6265SDimitry Andric   // not exceed 2^14, otherwise it can NOT be properly lowered
28781ad6265SDimitry Andric   // in backend.
28881ad6265SDimitry Andric   static constexpr unsigned ParamMaxAlignment = 1 << 14;
2890b57cec5SDimitry Andric   DominatorTree DT;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
2920b57cec5SDimitry Andric   /// instructions we have seen so far.
2930b57cec5SDimitry Andric   ///
2940b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
2950b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
2960b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
2990b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
3020b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
3050b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   /// The result type for a landingpad.
3080b57cec5SDimitry Andric   Type *LandingPadResultTy;
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
3110b57cec5SDimitry Andric   /// already.
3120b57cec5SDimitry Andric   bool SawFrameEscape;
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
3150b57cec5SDimitry Andric   bool HasDebugInfo = false;
3160b57cec5SDimitry Andric 
317e8d8bef9SDimitry Andric   /// The current source language.
318e8d8bef9SDimitry Andric   dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
319e8d8bef9SDimitry Andric 
3200b57cec5SDimitry Andric   /// Whether source was present on the first DIFile encountered in each CU.
3210b57cec5SDimitry Andric   DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
3240b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
3250b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
3280b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
3290b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
3320b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
3350b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
3360b57cec5SDimitry Andric 
337fe6060f1SDimitry Andric   /// Cache of attribute lists verified.
338fe6060f1SDimitry Andric   SmallPtrSet<const void *, 32> AttributeListsVisited;
339fe6060f1SDimitry Andric 
3400b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3410b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3420b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3430b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3440b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3470b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3500b57cec5SDimitry Andric 
351e8d8bef9SDimitry Andric   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
352e8d8bef9SDimitry Andric 
3530b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric public:
3560b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3570b57cec5SDimitry Andric                     const Module &M)
3580b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3590b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3600b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3610b57cec5SDimitry Andric   }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   bool verify(const Function &F) {
3660b57cec5SDimitry Andric     assert(F.getParent() == &M &&
3670b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
3700b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
3710b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
3720b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
3730b57cec5SDimitry Andric     // this code outside of a pass manager.
3740b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
3750b57cec5SDimitry Andric     if (!F.empty())
3760b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
3790b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
3800b57cec5SDimitry Andric         continue;
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric       if (OS) {
3830b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
3840b57cec5SDimitry Andric             << "' does not have terminator!\n";
3850b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
3860b57cec5SDimitry Andric         *OS << "\n";
3870b57cec5SDimitry Andric       }
3880b57cec5SDimitry Andric       return false;
3890b57cec5SDimitry Andric     }
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric     Broken = false;
3920b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
3930b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
3940b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
3950b57cec5SDimitry Andric     InstsInThisBlock.clear();
3960b57cec5SDimitry Andric     DebugFnArgs.clear();
3970b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
3980b57cec5SDimitry Andric     SawFrameEscape = false;
3990b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
400e8d8bef9SDimitry Andric     verifyNoAliasScopeDecl();
401e8d8bef9SDimitry Andric     NoAliasScopeDecls.clear();
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric     return !Broken;
4040b57cec5SDimitry Andric   }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
4070b57cec5SDimitry Andric   bool verify() {
4080b57cec5SDimitry Andric     Broken = false;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
4110b57cec5SDimitry Andric     for (const Function &F : M)
4120b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
4130b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
4160b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
4170b57cec5SDimitry Andric     verifyFrameRecoverIndices();
4180b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
4190b57cec5SDimitry Andric       visitGlobalVariable(GV);
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
4220b57cec5SDimitry Andric       visitGlobalAlias(GA);
4230b57cec5SDimitry Andric 
424349cc55cSDimitry Andric     for (const GlobalIFunc &GI : M.ifuncs())
425349cc55cSDimitry Andric       visitGlobalIFunc(GI);
426349cc55cSDimitry Andric 
4270b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
4280b57cec5SDimitry Andric       visitNamedMDNode(NMD);
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
4310b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
4320b57cec5SDimitry Andric 
433349cc55cSDimitry Andric     visitModuleFlags();
434349cc55cSDimitry Andric     visitModuleIdents();
435349cc55cSDimitry Andric     visitModuleCommandLines();
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric     verifyCompileUnits();
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
4400b57cec5SDimitry Andric     DISubprogramAttachments.clear();
4410b57cec5SDimitry Andric     return !Broken;
4420b57cec5SDimitry Andric   }
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric private:
4455ffd83dbSDimitry Andric   /// Whether a metadata node is allowed to be, or contain, a DILocation.
4465ffd83dbSDimitry Andric   enum class AreDebugLocsAllowed { No, Yes };
4475ffd83dbSDimitry Andric 
4480b57cec5SDimitry Andric   // Verification methods...
4490b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4500b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4510b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
452349cc55cSDimitry Andric   void visitGlobalIFunc(const GlobalIFunc &GI);
4530b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
4540b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
4550b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
4560b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
4575ffd83dbSDimitry Andric   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
4580b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
4590b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
4600b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
461349cc55cSDimitry Andric   void visitModuleIdents();
462349cc55cSDimitry Andric   void visitModuleCommandLines();
463349cc55cSDimitry Andric   void visitModuleFlags();
4640b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
4650b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
4660b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
4670b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
4680b57cec5SDimitry Andric   void visitFunction(const Function &F);
4690b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
4700b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
4710b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
4728bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
473fcaf7f86SDimitry Andric   void visitCallStackMetadata(MDNode *MD);
474fcaf7f86SDimitry Andric   void visitMemProfMetadata(Instruction &I, MDNode *MD);
475fcaf7f86SDimitry Andric   void visitCallsiteMetadata(Instruction &I, MDNode *MD);
476*bdd1243dSDimitry Andric   void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
477e8d8bef9SDimitry Andric   void visitAnnotationMetadata(MDNode *Annotation);
478349cc55cSDimitry Andric   void visitAliasScopeMetadata(const MDNode *MD);
479349cc55cSDimitry Andric   void visitAliasScopeListMetadata(const MDNode *MD);
48081ad6265SDimitry Andric   void visitAccessGroupMetadata(const MDNode *MD);
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
4830b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
4840b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
4850b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
4860b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
4870b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
4880b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   // InstVisitor overrides...
4930b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
4940b57cec5SDimitry Andric   void visit(Instruction &I);
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
4970b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
4980b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
4990b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
5000b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
5010b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
5020b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
5030b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
5040b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
5050b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
5060b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
5070b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
5080b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
5090b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
5100b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
5110b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
5120b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
5130b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
5140b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
5150b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
5160b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
5170b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
5180b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
5190b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
5200b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
5210b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
5220b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
5230b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
5240b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
5250b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
5260b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
5270b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
5280b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
5290b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
5300b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
5310b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
5320b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
5330b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
5340b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
5350b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
5360b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
53781ad6265SDimitry Andric   void visitVPIntrinsic(VPIntrinsic &VPI);
5380b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
5390b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
5400b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
5410b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
5420b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
5430b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
5440b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
5450b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
5460b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
5470b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
5480b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
5490b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
5500b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
5510b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
5520b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
5530b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
5540b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
5570b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
5580eae32dcSDimitry Andric   void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
5590b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
5600b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
561fe6060f1SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
5620b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
563fe6060f1SDimitry Andric   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
564fe6060f1SDimitry Andric                                     const Value *V);
5650b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
56604eeddc0SDimitry Andric                            const Value *V, bool IsIntrinsic, bool IsInlineAsm);
5670b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
5700b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
57104eeddc0SDimitry Andric   void verifyInlineAsmCall(const CallBase &Call);
5720b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
5730b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
5740b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
5770b57cec5SDimitry Andric   template <typename ValueOrMetadata>
5780b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
5790b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
5800b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
5810b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
5828bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   /// Module-level debug info verification...
5850b57cec5SDimitry Andric   void verifyCompileUnits();
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
5880b57cec5SDimitry Andric   /// declarations share the same calling convention.
5890b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
5900b57cec5SDimitry Andric 
591349cc55cSDimitry Andric   void verifyAttachedCallBundle(const CallBase &Call,
592349cc55cSDimitry Andric                                 const OperandBundleUse &BU);
593349cc55cSDimitry Andric 
5940b57cec5SDimitry Andric   /// Verify all-or-nothing property of DIFile source attribute within a CU.
5950b57cec5SDimitry Andric   void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F);
596e8d8bef9SDimitry Andric 
597e8d8bef9SDimitry Andric   /// Verify the llvm.experimental.noalias.scope.decl declarations
598e8d8bef9SDimitry Andric   void verifyNoAliasScopeDecl();
5990b57cec5SDimitry Andric };
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric } // end anonymous namespace
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
60481ad6265SDimitry Andric #define Check(C, ...)                                                          \
60581ad6265SDimitry Andric   do {                                                                         \
60681ad6265SDimitry Andric     if (!(C)) {                                                                \
60781ad6265SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
60881ad6265SDimitry Andric       return;                                                                  \
60981ad6265SDimitry Andric     }                                                                          \
61081ad6265SDimitry Andric   } while (false)
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
6130b57cec5SDimitry Andric /// an error message.
61481ad6265SDimitry Andric #define CheckDI(C, ...)                                                        \
61581ad6265SDimitry Andric   do {                                                                         \
61681ad6265SDimitry Andric     if (!(C)) {                                                                \
61781ad6265SDimitry Andric       DebugInfoCheckFailed(__VA_ARGS__);                                       \
61881ad6265SDimitry Andric       return;                                                                  \
61981ad6265SDimitry Andric     }                                                                          \
62081ad6265SDimitry Andric   } while (false)
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
6230b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
62481ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Operand is null", &I);
6250b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric 
6280eae32dcSDimitry Andric // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
6290b57cec5SDimitry Andric static void forEachUser(const Value *User,
6300b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
6310b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
6320b57cec5SDimitry Andric   if (!Visited.insert(User).second)
6330b57cec5SDimitry Andric     return;
6340eae32dcSDimitry Andric 
6350eae32dcSDimitry Andric   SmallVector<const Value *> WorkList;
6360eae32dcSDimitry Andric   append_range(WorkList, User->materialized_users());
6370eae32dcSDimitry Andric   while (!WorkList.empty()) {
6380eae32dcSDimitry Andric    const Value *Cur = WorkList.pop_back_val();
6390eae32dcSDimitry Andric     if (!Visited.insert(Cur).second)
6400eae32dcSDimitry Andric       continue;
6410eae32dcSDimitry Andric     if (Callback(Cur))
6420eae32dcSDimitry Andric       append_range(WorkList, Cur->materialized_users());
6430eae32dcSDimitry Andric   }
6440b57cec5SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
64781ad6265SDimitry Andric   Check(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
6480b57cec5SDimitry Andric         "Global is external, but doesn't have external or weak linkage!", &GV);
6490b57cec5SDimitry Andric 
6500eae32dcSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
6510eae32dcSDimitry Andric 
6520eae32dcSDimitry Andric     if (MaybeAlign A = GO->getAlign()) {
65381ad6265SDimitry Andric       Check(A->value() <= Value::MaximumAlignment,
6545ffd83dbSDimitry Andric             "huge alignment values are unsupported", GO);
6550eae32dcSDimitry Andric     }
6560eae32dcSDimitry Andric   }
65781ad6265SDimitry Andric   Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
6580b57cec5SDimitry Andric         "Only global variables can have appending linkage!", &GV);
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
6610b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
66281ad6265SDimitry Andric     Check(GVar && GVar->getValueType()->isArrayTy(),
6630b57cec5SDimitry Andric           "Only global arrays can have appending linkage!", GVar);
6640b57cec5SDimitry Andric   }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
66781ad6265SDimitry Andric     Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
6680b57cec5SDimitry Andric 
669*bdd1243dSDimitry Andric   if (GV.hasDLLExportStorageClass()) {
670*bdd1243dSDimitry Andric     Check(!GV.hasHiddenVisibility(),
671*bdd1243dSDimitry Andric           "dllexport GlobalValue must have default or protected visibility",
672*bdd1243dSDimitry Andric           &GV);
673*bdd1243dSDimitry Andric   }
6740b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
675*bdd1243dSDimitry Andric     Check(GV.hasDefaultVisibility(),
676*bdd1243dSDimitry Andric           "dllimport GlobalValue must have default visibility", &GV);
67781ad6265SDimitry Andric     Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
67881ad6265SDimitry Andric           &GV);
6790b57cec5SDimitry Andric 
68081ad6265SDimitry Andric     Check((GV.isDeclaration() &&
681e8d8bef9SDimitry Andric            (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
6820b57cec5SDimitry Andric               GV.hasAvailableExternallyLinkage(),
6830b57cec5SDimitry Andric           "Global is marked as dllimport, but not external", &GV);
6840b57cec5SDimitry Andric   }
6850b57cec5SDimitry Andric 
6865ffd83dbSDimitry Andric   if (GV.isImplicitDSOLocal())
68781ad6265SDimitry Andric     Check(GV.isDSOLocal(),
6885ffd83dbSDimitry Andric           "GlobalValue with local linkage or non-default "
6895ffd83dbSDimitry Andric           "visibility must be dso_local!",
6900b57cec5SDimitry Andric           &GV);
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
6930b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
6940b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
6950b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
6960b57cec5SDimitry Andric                     I);
6970b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
6980b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
6990b57cec5SDimitry Andric                     I->getParent()->getParent(),
7000b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
7010b57cec5SDimitry Andric       return false;
7020b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
7030b57cec5SDimitry Andric       if (F->getParent() != &M)
7040b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
7050b57cec5SDimitry Andric                     F, F->getParent());
7060b57cec5SDimitry Andric       return false;
7070b57cec5SDimitry Andric     }
7080b57cec5SDimitry Andric     return true;
7090b57cec5SDimitry Andric   });
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
7130b57cec5SDimitry Andric   if (GV.hasInitializer()) {
71481ad6265SDimitry Andric     Check(GV.getInitializer()->getType() == GV.getValueType(),
7150b57cec5SDimitry Andric           "Global variable initializer type does not match global "
7160b57cec5SDimitry Andric           "variable type!",
7170b57cec5SDimitry Andric           &GV);
7180b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
7190b57cec5SDimitry Andric     // cannot be constant.
7200b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
72181ad6265SDimitry Andric       Check(GV.getInitializer()->isNullValue(),
7220b57cec5SDimitry Andric             "'common' global must have a zero initializer!", &GV);
72381ad6265SDimitry Andric       Check(!GV.isConstant(), "'common' global may not be marked constant!",
7240b57cec5SDimitry Andric             &GV);
72581ad6265SDimitry Andric       Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
7260b57cec5SDimitry Andric     }
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
7300b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
73181ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
7320b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
733*bdd1243dSDimitry Andric     Check(GV.materialized_use_empty(),
734*bdd1243dSDimitry Andric           "invalid uses of intrinsic global variable", &GV);
735*bdd1243dSDimitry Andric 
7360b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
7370b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
7380b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
7390b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
7400b57cec5SDimitry Andric       PointerType *FuncPtrTy =
7410b57cec5SDimitry Andric           FunctionType::get(Type::getVoidTy(Context), false)->
7420b57cec5SDimitry Andric           getPointerTo(DL.getProgramAddressSpace());
74381ad6265SDimitry Andric       Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
7440b57cec5SDimitry Andric                 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
7450b57cec5SDimitry Andric                 STy->getTypeAtIndex(1) == FuncPtrTy,
7460b57cec5SDimitry Andric             "wrong type for intrinsic global variable", &GV);
74781ad6265SDimitry Andric       Check(STy->getNumElements() == 3,
7480b57cec5SDimitry Andric             "the third field of the element type is mandatory, "
749*bdd1243dSDimitry Andric             "specify ptr null to migrate from the obsoleted 2-field form");
7500b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
751fe6060f1SDimitry Andric       Type *Int8Ty = Type::getInt8Ty(ETy->getContext());
75281ad6265SDimitry Andric       Check(ETy->isPointerTy() &&
753fe6060f1SDimitry Andric                 cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty),
7540b57cec5SDimitry Andric             "wrong type for intrinsic global variable", &GV);
7550b57cec5SDimitry Andric     }
7560b57cec5SDimitry Andric   }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
7590b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
76081ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
7610b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
762*bdd1243dSDimitry Andric     Check(GV.materialized_use_empty(),
763*bdd1243dSDimitry Andric           "invalid uses of intrinsic global variable", &GV);
764*bdd1243dSDimitry Andric 
7650b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
7660b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
7670b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
76881ad6265SDimitry Andric       Check(PTy, "wrong type for intrinsic global variable", &GV);
7690b57cec5SDimitry Andric       if (GV.hasInitializer()) {
7700b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
7710b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
77281ad6265SDimitry Andric         Check(InitArray, "wrong initalizer for intrinsic global variable",
7730b57cec5SDimitry Andric               Init);
7740b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
7758bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
77681ad6265SDimitry Andric           Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
7770b57cec5SDimitry Andric                     isa<GlobalAlias>(V),
7780eae32dcSDimitry Andric                 Twine("invalid ") + GV.getName() + " member", V);
77981ad6265SDimitry Andric           Check(V->hasName(),
7800eae32dcSDimitry Andric                 Twine("members of ") + GV.getName() + " must be named", V);
7810b57cec5SDimitry Andric         }
7820b57cec5SDimitry Andric       }
7830b57cec5SDimitry Andric     }
7840b57cec5SDimitry Andric   }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   // Visit any debug info attachments.
7870b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
7880b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
7890b57cec5SDimitry Andric   for (auto *MD : MDs) {
7900b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
7910b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
7920b57cec5SDimitry Andric     else
79381ad6265SDimitry Andric       CheckDI(false, "!dbg attachment of global variable must be a "
7940b57cec5SDimitry Andric                      "DIGlobalVariableExpression");
7950b57cec5SDimitry Andric   }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
798e8d8bef9SDimitry Andric   // the runtime size. If the global is an array containing scalable vectors,
799e8d8bef9SDimitry Andric   // that will be caught by the isValidElementType methods in StructType or
800e8d8bef9SDimitry Andric   // ArrayType instead.
80181ad6265SDimitry Andric   Check(!isa<ScalableVectorType>(GV.getValueType()),
8025ffd83dbSDimitry Andric         "Globals cannot contain scalable vectors", &GV);
8030b57cec5SDimitry Andric 
804e8d8bef9SDimitry Andric   if (auto *STy = dyn_cast<StructType>(GV.getValueType()))
80581ad6265SDimitry Andric     Check(!STy->containsScalableVectorType(),
806e8d8bef9SDimitry Andric           "Globals cannot contain scalable vectors", &GV);
807e8d8bef9SDimitry Andric 
808*bdd1243dSDimitry Andric   // Check if it's a target extension type that disallows being used as a
809*bdd1243dSDimitry Andric   // global.
810*bdd1243dSDimitry Andric   if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
811*bdd1243dSDimitry Andric     Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
812*bdd1243dSDimitry Andric           "Global @" + GV.getName() + " has illegal target extension type",
813*bdd1243dSDimitry Andric           TTy);
814*bdd1243dSDimitry Andric 
8150b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
8160b57cec5SDimitry Andric     visitGlobalValue(GV);
8170b57cec5SDimitry Andric     return;
8180b57cec5SDimitry Andric   }
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
8210b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   visitGlobalValue(GV);
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
8270b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
8280b57cec5SDimitry Andric   Visited.insert(&GA);
8290b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
8300b57cec5SDimitry Andric }
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
8330b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
834*bdd1243dSDimitry Andric   if (GA.hasAvailableExternallyLinkage()) {
835*bdd1243dSDimitry Andric     Check(isa<GlobalValue>(C) &&
836*bdd1243dSDimitry Andric               cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
837*bdd1243dSDimitry Andric           "available_externally alias must point to available_externally "
838*bdd1243dSDimitry Andric           "global value",
839*bdd1243dSDimitry Andric           &GA);
840*bdd1243dSDimitry Andric   }
8410b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
842*bdd1243dSDimitry Andric     if (!GA.hasAvailableExternallyLinkage()) {
84381ad6265SDimitry Andric       Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
8440b57cec5SDimitry Andric             &GA);
845*bdd1243dSDimitry Andric     }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
84881ad6265SDimitry Andric       Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
8490b57cec5SDimitry Andric 
85081ad6265SDimitry Andric       Check(!GA2->isInterposable(),
85181ad6265SDimitry Andric             "Alias cannot point to an interposable alias", &GA);
8520b57cec5SDimitry Andric     } else {
8530b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
8540b57cec5SDimitry Andric       // Do not recurse into global initializers.
8550b57cec5SDimitry Andric       return;
8560b57cec5SDimitry Andric     }
8570b57cec5SDimitry Andric   }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
8600b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
8630b57cec5SDimitry Andric     Value *V = &*U;
8640b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
8650b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
8660b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
8670b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
8680b57cec5SDimitry Andric   }
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
87281ad6265SDimitry Andric   Check(GlobalAlias::isValidLinkage(GA.getLinkage()),
8730b57cec5SDimitry Andric         "Alias should have private, internal, linkonce, weak, linkonce_odr, "
874*bdd1243dSDimitry Andric         "weak_odr, external, or available_externally linkage!",
8750b57cec5SDimitry Andric         &GA);
8760b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
87781ad6265SDimitry Andric   Check(Aliasee, "Aliasee cannot be NULL!", &GA);
87881ad6265SDimitry Andric   Check(GA.getType() == Aliasee->getType(),
8790b57cec5SDimitry Andric         "Alias and aliasee types should match!", &GA);
8800b57cec5SDimitry Andric 
88181ad6265SDimitry Andric   Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
8820b57cec5SDimitry Andric         "Aliasee should be either GlobalValue or ConstantExpr", &GA);
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric   visitGlobalValue(GA);
8870b57cec5SDimitry Andric }
8880b57cec5SDimitry Andric 
889349cc55cSDimitry Andric void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
89081ad6265SDimitry Andric   Check(GlobalIFunc::isValidLinkage(GI.getLinkage()),
89181ad6265SDimitry Andric         "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
89281ad6265SDimitry Andric         "weak_odr, or external linkage!",
89381ad6265SDimitry Andric         &GI);
894349cc55cSDimitry Andric   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
89581ad6265SDimitry Andric   // is a Function definition.
896349cc55cSDimitry Andric   const Function *Resolver = GI.getResolverFunction();
89781ad6265SDimitry Andric   Check(Resolver, "IFunc must have a Function resolver", &GI);
89881ad6265SDimitry Andric   Check(!Resolver->isDeclarationForLinker(),
89981ad6265SDimitry Andric         "IFunc resolver must be a definition", &GI);
900349cc55cSDimitry Andric 
901349cc55cSDimitry Andric   // Check that the immediate resolver operand (prior to any bitcasts) has the
90281ad6265SDimitry Andric   // correct type.
903349cc55cSDimitry Andric   const Type *ResolverTy = GI.getResolver()->getType();
904*bdd1243dSDimitry Andric 
905*bdd1243dSDimitry Andric   Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
906*bdd1243dSDimitry Andric         "IFunc resolver must return a pointer", &GI);
907*bdd1243dSDimitry Andric 
908349cc55cSDimitry Andric   const Type *ResolverFuncTy =
909349cc55cSDimitry Andric       GlobalIFunc::getResolverFunctionType(GI.getValueType());
910*bdd1243dSDimitry Andric   Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
911349cc55cSDimitry Andric         "IFunc resolver has incorrect type", &GI);
912349cc55cSDimitry Andric }
913349cc55cSDimitry Andric 
9140b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
9150b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
9160b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
9170b57cec5SDimitry Andric   if (NMD.getName().startswith("llvm.dbg."))
91881ad6265SDimitry Andric     CheckDI(NMD.getName() == "llvm.dbg.cu",
91981ad6265SDimitry Andric             "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
9200b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
9210b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
92281ad6265SDimitry Andric       CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric     if (!MD)
9250b57cec5SDimitry Andric       continue;
9260b57cec5SDimitry Andric 
9275ffd83dbSDimitry Andric     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
9280b57cec5SDimitry Andric   }
9290b57cec5SDimitry Andric }
9300b57cec5SDimitry Andric 
9315ffd83dbSDimitry Andric void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
9320b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
9330b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
9340b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
9350b57cec5SDimitry Andric     return;
9360b57cec5SDimitry Andric 
93781ad6265SDimitry Andric   Check(&MD.getContext() == &Context,
938fe6060f1SDimitry Andric         "MDNode context does not match Module context!", &MD);
939fe6060f1SDimitry Andric 
9400b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
9410b57cec5SDimitry Andric   default:
9420b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
9430b57cec5SDimitry Andric   case Metadata::MDTupleKind:
9440b57cec5SDimitry Andric     break;
9450b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
9460b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
9470b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
9480b57cec5SDimitry Andric     break;
9490b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
9500b57cec5SDimitry Andric   }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
9530b57cec5SDimitry Andric     if (!Op)
9540b57cec5SDimitry Andric       continue;
95581ad6265SDimitry Andric     Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
9560b57cec5SDimitry Andric           &MD, Op);
95781ad6265SDimitry Andric     CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
9585ffd83dbSDimitry Andric             "DILocation not allowed within this metadata node", &MD, Op);
9590b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
9605ffd83dbSDimitry Andric       visitMDNode(*N, AllowLocs);
9610b57cec5SDimitry Andric       continue;
9620b57cec5SDimitry Andric     }
9630b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
9640b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
9650b57cec5SDimitry Andric       continue;
9660b57cec5SDimitry Andric     }
9670b57cec5SDimitry Andric   }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
97081ad6265SDimitry Andric   Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
97181ad6265SDimitry Andric   Check(MD.isResolved(), "All nodes should be resolved!", &MD);
9720b57cec5SDimitry Andric }
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
97581ad6265SDimitry Andric   Check(MD.getValue(), "Expected valid value", &MD);
97681ad6265SDimitry Andric   Check(!MD.getValue()->getType()->isMetadataTy(),
9770b57cec5SDimitry Andric         "Unexpected metadata round-trip through values", &MD, MD.getValue());
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
9800b57cec5SDimitry Andric   if (!L)
9810b57cec5SDimitry Andric     return;
9820b57cec5SDimitry Andric 
98381ad6265SDimitry Andric   Check(F, "function-local metadata used outside a function", L);
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
9860b57cec5SDimitry Andric   // function that we expect.
9870b57cec5SDimitry Andric   Function *ActualF = nullptr;
9880b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
98981ad6265SDimitry Andric     Check(I->getParent(), "function-local metadata not in basic block", L, I);
9900b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
9910b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
9920b57cec5SDimitry Andric     ActualF = BB->getParent();
9930b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
9940b57cec5SDimitry Andric     ActualF = A->getParent();
9950b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
9960b57cec5SDimitry Andric 
99781ad6265SDimitry Andric   Check(ActualF == F, "function-local metadata used in wrong function", L);
9980b57cec5SDimitry Andric }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
10010b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
10020b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
10035ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::No);
10040b57cec5SDimitry Andric     return;
10050b57cec5SDimitry Andric   }
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
10080b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
10090b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
10100b57cec5SDimitry Andric     return;
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
10130b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
10170b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
10180b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
102181ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
10220b57cec5SDimitry Andric           "location requires a valid scope", &N, N.getRawScope());
10230b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
102481ad6265SDimitry Andric     CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
10250b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
102681ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
103081ad6265SDimitry Andric   CheckDI(N.getTag(), "invalid tag", &N);
10310b57cec5SDimitry Andric }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
10340b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
103581ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
10360b57cec5SDimitry Andric }
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
103981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1040e8d8bef9SDimitry Andric   bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
104181ad6265SDimitry Andric   CheckDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
1042e8d8bef9SDimitry Andric               N.getRawUpperBound(),
10435ffd83dbSDimitry Andric           "Subrange must contain count or upperBound", &N);
104481ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
10455ffd83dbSDimitry Andric           "Subrange can have any one of count or upperBound", &N);
1046fe6060f1SDimitry Andric   auto *CBound = N.getRawCountNode();
104781ad6265SDimitry Andric   CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1048fe6060f1SDimitry Andric               isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1049fe6060f1SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
10500b57cec5SDimitry Andric   auto Count = N.getCount();
105181ad6265SDimitry Andric   CheckDI(!Count || !Count.is<ConstantInt *>() ||
10520b57cec5SDimitry Andric               Count.get<ConstantInt *>()->getSExtValue() >= -1,
10530b57cec5SDimitry Andric           "invalid subrange count", &N);
10545ffd83dbSDimitry Andric   auto *LBound = N.getRawLowerBound();
105581ad6265SDimitry Andric   CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
10565ffd83dbSDimitry Andric               isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
10575ffd83dbSDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
10585ffd83dbSDimitry Andric           &N);
10595ffd83dbSDimitry Andric   auto *UBound = N.getRawUpperBound();
106081ad6265SDimitry Andric   CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
10615ffd83dbSDimitry Andric               isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
10625ffd83dbSDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
10635ffd83dbSDimitry Andric           &N);
10645ffd83dbSDimitry Andric   auto *Stride = N.getRawStride();
106581ad6265SDimitry Andric   CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
10665ffd83dbSDimitry Andric               isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
10675ffd83dbSDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
10680b57cec5SDimitry Andric }
10690b57cec5SDimitry Andric 
1070e8d8bef9SDimitry Andric void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
107181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
107281ad6265SDimitry Andric   CheckDI(N.getRawCountNode() || N.getRawUpperBound(),
1073e8d8bef9SDimitry Andric           "GenericSubrange must contain count or upperBound", &N);
107481ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1075e8d8bef9SDimitry Andric           "GenericSubrange can have any one of count or upperBound", &N);
1076e8d8bef9SDimitry Andric   auto *CBound = N.getRawCountNode();
107781ad6265SDimitry Andric   CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1078e8d8bef9SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
1079e8d8bef9SDimitry Andric   auto *LBound = N.getRawLowerBound();
108081ad6265SDimitry Andric   CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
108181ad6265SDimitry Andric   CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1082e8d8bef9SDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
1083e8d8bef9SDimitry Andric           &N);
1084e8d8bef9SDimitry Andric   auto *UBound = N.getRawUpperBound();
108581ad6265SDimitry Andric   CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1086e8d8bef9SDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
1087e8d8bef9SDimitry Andric           &N);
1088e8d8bef9SDimitry Andric   auto *Stride = N.getRawStride();
108981ad6265SDimitry Andric   CheckDI(Stride, "GenericSubrange must contain stride", &N);
109081ad6265SDimitry Andric   CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1091e8d8bef9SDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
1092e8d8bef9SDimitry Andric }
1093e8d8bef9SDimitry Andric 
10940b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
109581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
109981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1100e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_unspecified_type ||
1101e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_string_type,
11020b57cec5SDimitry Andric           "invalid tag", &N);
1103e8d8bef9SDimitry Andric }
1104e8d8bef9SDimitry Andric 
1105e8d8bef9SDimitry Andric void Verifier::visitDIStringType(const DIStringType &N) {
110681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
110781ad6265SDimitry Andric   CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
110881ad6265SDimitry Andric           &N);
11090b57cec5SDimitry Andric }
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
11120b57cec5SDimitry Andric   // Common scope checks.
11130b57cec5SDimitry Andric   visitDIScope(N);
11140b57cec5SDimitry Andric 
111581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
11160b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_pointer_type ||
11170b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
11180b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_reference_type ||
11190b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
11200b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_const_type ||
112104eeddc0SDimitry Andric               N.getTag() == dwarf::DW_TAG_immutable_type ||
11220b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_volatile_type ||
11230b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_restrict_type ||
11240b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_atomic_type ||
11250b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_member ||
11260b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_inheritance ||
1127fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_friend ||
1128fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_set_type,
11290b57cec5SDimitry Andric           "invalid tag", &N);
11300b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
113181ad6265SDimitry Andric     CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
11320b57cec5SDimitry Andric             N.getRawExtraData());
11330b57cec5SDimitry Andric   }
11340b57cec5SDimitry Andric 
1135fe6060f1SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_set_type) {
1136fe6060f1SDimitry Andric     if (auto *T = N.getRawBaseType()) {
1137fe6060f1SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1138fe6060f1SDimitry Andric       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
113981ad6265SDimitry Andric       CheckDI(
1140fe6060f1SDimitry Andric           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1141fe6060f1SDimitry Andric               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1142fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1143fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1144fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1145fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1146fe6060f1SDimitry Andric           "invalid set base type", &N, T);
1147fe6060f1SDimitry Andric     }
1148fe6060f1SDimitry Andric   }
1149fe6060f1SDimitry Andric 
115081ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
115181ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
11520b57cec5SDimitry Andric           N.getRawBaseType());
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
115581ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
11560b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_reference_type ||
11570b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
11580b57cec5SDimitry Andric             "DWARF address space only applies to pointer or reference types",
11590b57cec5SDimitry Andric             &N);
11600b57cec5SDimitry Andric   }
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric /// Detect mutually exclusive flags.
11640b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
11650b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
11660b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
11670b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
11680b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
11690b57cec5SDimitry Andric }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
11720b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
117381ad6265SDimitry Andric   CheckDI(Params, "invalid template params", &N, &RawParams);
11740b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
117581ad6265SDimitry Andric     CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
11760b57cec5SDimitry Andric             &N, Params, Op);
11770b57cec5SDimitry Andric   }
11780b57cec5SDimitry Andric }
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
11810b57cec5SDimitry Andric   // Common scope checks.
11820b57cec5SDimitry Andric   visitDIScope(N);
11830b57cec5SDimitry Andric 
118481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
11850b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_structure_type ||
11860b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_union_type ||
11870b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_enumeration_type ||
11880b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_class_type ||
1189349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_variant_part ||
1190349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_namelist,
11910b57cec5SDimitry Andric           "invalid tag", &N);
11920b57cec5SDimitry Andric 
119381ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
119481ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
11950b57cec5SDimitry Andric           N.getRawBaseType());
11960b57cec5SDimitry Andric 
119781ad6265SDimitry Andric   CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
11980b57cec5SDimitry Andric           "invalid composite elements", &N, N.getRawElements());
119981ad6265SDimitry Andric   CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
12000b57cec5SDimitry Andric           N.getRawVTableHolder());
120181ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
12020b57cec5SDimitry Andric           "invalid reference flags", &N);
12038bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
120481ad6265SDimitry Andric   CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
12058bcb0991SDimitry Andric           "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   if (N.isVector()) {
12080b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
120981ad6265SDimitry Andric     CheckDI(Elements.size() == 1 &&
12100b57cec5SDimitry Andric                 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
12110b57cec5SDimitry Andric             "invalid vector, expected one element of type subrange", &N);
12120b57cec5SDimitry Andric   }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
12150b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
121881ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
12190b57cec5SDimitry Andric             "discriminator can only appear on variant part");
12200b57cec5SDimitry Andric   }
12215ffd83dbSDimitry Andric 
12225ffd83dbSDimitry Andric   if (N.getRawDataLocation()) {
122381ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
12245ffd83dbSDimitry Andric             "dataLocation can only appear in array type");
12255ffd83dbSDimitry Andric   }
1226e8d8bef9SDimitry Andric 
1227e8d8bef9SDimitry Andric   if (N.getRawAssociated()) {
122881ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1229e8d8bef9SDimitry Andric             "associated can only appear in array type");
1230e8d8bef9SDimitry Andric   }
1231e8d8bef9SDimitry Andric 
1232e8d8bef9SDimitry Andric   if (N.getRawAllocated()) {
123381ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1234e8d8bef9SDimitry Andric             "allocated can only appear in array type");
1235e8d8bef9SDimitry Andric   }
1236e8d8bef9SDimitry Andric 
1237e8d8bef9SDimitry Andric   if (N.getRawRank()) {
123881ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1239e8d8bef9SDimitry Andric             "rank can only appear in array type");
1240e8d8bef9SDimitry Andric   }
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
124481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
12450b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
124681ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
12470b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
124881ad6265SDimitry Andric       CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
12490b57cec5SDimitry Andric     }
12500b57cec5SDimitry Andric   }
125181ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
12520b57cec5SDimitry Andric           "invalid reference flags", &N);
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
125681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1257*bdd1243dSDimitry Andric   std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
12580b57cec5SDimitry Andric   if (Checksum) {
125981ad6265SDimitry Andric     CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
12600b57cec5SDimitry Andric             "invalid checksum kind", &N);
12610b57cec5SDimitry Andric     size_t Size;
12620b57cec5SDimitry Andric     switch (Checksum->Kind) {
12630b57cec5SDimitry Andric     case DIFile::CSK_MD5:
12640b57cec5SDimitry Andric       Size = 32;
12650b57cec5SDimitry Andric       break;
12660b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
12670b57cec5SDimitry Andric       Size = 40;
12680b57cec5SDimitry Andric       break;
12695ffd83dbSDimitry Andric     case DIFile::CSK_SHA256:
12705ffd83dbSDimitry Andric       Size = 64;
12715ffd83dbSDimitry Andric       break;
12720b57cec5SDimitry Andric     }
127381ad6265SDimitry Andric     CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
127481ad6265SDimitry Andric     CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
12750b57cec5SDimitry Andric             "invalid checksum", &N);
12760b57cec5SDimitry Andric   }
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
128081ad6265SDimitry Andric   CheckDI(N.isDistinct(), "compile units must be distinct", &N);
128181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
12840b57cec5SDimitry Andric   // as those could be empty.
128581ad6265SDimitry Andric   CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
12860b57cec5SDimitry Andric           N.getRawFile());
128781ad6265SDimitry Andric   CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
12880b57cec5SDimitry Andric           N.getFile());
12890b57cec5SDimitry Andric 
1290e8d8bef9SDimitry Andric   CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1291e8d8bef9SDimitry Andric 
12920b57cec5SDimitry Andric   verifySourceDebugInfo(N, *N.getFile());
12930b57cec5SDimitry Andric 
129481ad6265SDimitry Andric   CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
12950b57cec5SDimitry Andric           "invalid emission kind", &N);
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
129881ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
12990b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
13000b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
130181ad6265SDimitry Andric       CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
13020b57cec5SDimitry Andric               "invalid enum type", &N, N.getEnumTypes(), Op);
13030b57cec5SDimitry Andric     }
13040b57cec5SDimitry Andric   }
13050b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
130681ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
13070b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
130881ad6265SDimitry Andric       CheckDI(
130981ad6265SDimitry Andric           Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
13100b57cec5SDimitry Andric                                      !cast<DISubprogram>(Op)->isDefinition())),
13110b57cec5SDimitry Andric           "invalid retained type", &N, Op);
13120b57cec5SDimitry Andric     }
13130b57cec5SDimitry Andric   }
13140b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
131581ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
13160b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
131781ad6265SDimitry Andric       CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
13180b57cec5SDimitry Andric               "invalid global variable ref", &N, Op);
13190b57cec5SDimitry Andric     }
13200b57cec5SDimitry Andric   }
13210b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
132281ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
13230b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
132481ad6265SDimitry Andric       CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
13250b57cec5SDimitry Andric               &N, Op);
13260b57cec5SDimitry Andric     }
13270b57cec5SDimitry Andric   }
13280b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
132981ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
13300b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
133181ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
13320b57cec5SDimitry Andric     }
13330b57cec5SDimitry Andric   }
13340b57cec5SDimitry Andric   CUVisited.insert(&N);
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
133881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
133981ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
13400b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
134181ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
13420b57cec5SDimitry Andric   else
134381ad6265SDimitry Andric     CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
13440b57cec5SDimitry Andric   if (auto *T = N.getRawType())
134581ad6265SDimitry Andric     CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
134681ad6265SDimitry Andric   CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
13470b57cec5SDimitry Andric           N.getRawContainingType());
13480b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
13490b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
13500b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
135181ad6265SDimitry Andric     CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
13520b57cec5SDimitry Andric             "invalid subprogram declaration", &N, S);
13530b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
13540b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
135581ad6265SDimitry Andric     CheckDI(Node, "invalid retained nodes list", &N, RawNode);
13560b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
135781ad6265SDimitry Andric       CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)),
135881ad6265SDimitry Andric               "invalid retained nodes, expected DILocalVariable or DILabel", &N,
135981ad6265SDimitry Andric               Node, Op);
13600b57cec5SDimitry Andric     }
13610b57cec5SDimitry Andric   }
136281ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
13630b57cec5SDimitry Andric           "invalid reference flags", &N);
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
13660b57cec5SDimitry Andric   if (N.isDefinition()) {
13670b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
136881ad6265SDimitry Andric     CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
136981ad6265SDimitry Andric     CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
137081ad6265SDimitry Andric     CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
13710b57cec5SDimitry Andric     if (N.getFile())
13720b57cec5SDimitry Andric       verifySourceDebugInfo(*N.getUnit(), *N.getFile());
13730b57cec5SDimitry Andric   } else {
13740b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
137581ad6265SDimitry Andric     CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
13790b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
138081ad6265SDimitry Andric     CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
13810b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
138281ad6265SDimitry Andric       CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
13830b57cec5SDimitry Andric               Op);
13840b57cec5SDimitry Andric   }
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
138781ad6265SDimitry Andric     CheckDI(N.isDefinition(),
13880b57cec5SDimitry Andric             "DIFlagAllCallsDescribed must be attached to a definition");
13890b57cec5SDimitry Andric }
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
139281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
139381ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
13940b57cec5SDimitry Andric           "invalid local scope", &N, N.getRawScope());
13950b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
139681ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
14000b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
14010b57cec5SDimitry Andric 
140281ad6265SDimitry Andric   CheckDI(N.getLine() || !N.getColumn(),
14030b57cec5SDimitry Andric           "cannot have column info without line info", &N);
14040b57cec5SDimitry Andric }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
14070b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
14080b57cec5SDimitry Andric }
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
141181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
14120b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
141381ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
14140b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
141581ad6265SDimitry Andric     CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
141981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
14200b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
142181ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
14220b57cec5SDimitry Andric }
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
142581ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
14260b57cec5SDimitry Andric               N.getMacinfoType() == dwarf::DW_MACINFO_undef,
14270b57cec5SDimitry Andric           "invalid macinfo type", &N);
142881ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous macro", &N);
14290b57cec5SDimitry Andric   if (!N.getValue().empty()) {
14300b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
14310b57cec5SDimitry Andric   }
14320b57cec5SDimitry Andric }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
143581ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
14360b57cec5SDimitry Andric           "invalid macinfo type", &N);
14370b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
143881ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
14390b57cec5SDimitry Andric 
14400b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
144181ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
14420b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
144381ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
14440b57cec5SDimitry Andric     }
14450b57cec5SDimitry Andric   }
14460b57cec5SDimitry Andric }
14470b57cec5SDimitry Andric 
1448fe6060f1SDimitry Andric void Verifier::visitDIArgList(const DIArgList &N) {
144981ad6265SDimitry Andric   CheckDI(!N.getNumOperands(),
1450fe6060f1SDimitry Andric           "DIArgList should have no operands other than a list of "
1451fe6060f1SDimitry Andric           "ValueAsMetadata",
1452fe6060f1SDimitry Andric           &N);
1453fe6060f1SDimitry Andric }
1454fe6060f1SDimitry Andric 
14550b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
145681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
145781ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous module", &N);
14580b57cec5SDimitry Andric }
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
146181ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
14620b57cec5SDimitry Andric }
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
14650b57cec5SDimitry Andric   visitDITemplateParameter(N);
14660b57cec5SDimitry Andric 
146781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
14680b57cec5SDimitry Andric           &N);
14690b57cec5SDimitry Andric }
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
14720b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
14730b57cec5SDimitry Andric   visitDITemplateParameter(N);
14740b57cec5SDimitry Andric 
147581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
14760b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
14770b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
14780b57cec5SDimitry Andric           "invalid tag", &N);
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
14820b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
148381ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
14840b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
148581ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
14860b57cec5SDimitry Andric }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
14890b57cec5SDimitry Andric   // Checks common to all variables.
14900b57cec5SDimitry Andric   visitDIVariable(N);
14910b57cec5SDimitry Andric 
149281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
149381ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
149481ad6265SDimitry Andric   // Check only if the global variable is not an extern
14955ffd83dbSDimitry Andric   if (N.isDefinition())
149681ad6265SDimitry Andric     CheckDI(N.getType(), "missing global variable type", &N);
14970b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
149881ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(Member),
14990b57cec5SDimitry Andric             "invalid static data member declaration", &N, Member);
15000b57cec5SDimitry Andric   }
15010b57cec5SDimitry Andric }
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
15040b57cec5SDimitry Andric   // Checks common to all variables.
15050b57cec5SDimitry Andric   visitDIVariable(N);
15060b57cec5SDimitry Andric 
150781ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
150881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
150981ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15100b57cec5SDimitry Andric           "local variable requires a valid scope", &N, N.getRawScope());
15110b57cec5SDimitry Andric   if (auto Ty = N.getType())
151281ad6265SDimitry Andric     CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
15130b57cec5SDimitry Andric }
15140b57cec5SDimitry Andric 
1515*bdd1243dSDimitry Andric void Verifier::visitDIAssignID(const DIAssignID &N) {
1516*bdd1243dSDimitry Andric   CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1517*bdd1243dSDimitry Andric   CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1518*bdd1243dSDimitry Andric }
1519*bdd1243dSDimitry Andric 
15200b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
15210b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
152281ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
15230b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
152481ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15250b57cec5SDimitry Andric 
152681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
152781ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15280b57cec5SDimitry Andric           "label requires a valid scope", &N, N.getRawScope());
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
153281ad6265SDimitry Andric   CheckDI(N.isValid(), "invalid expression", &N);
15330b57cec5SDimitry Andric }
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
15360b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
153781ad6265SDimitry Andric   CheckDI(GVE.getVariable(), "missing variable");
15380b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
15390b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
15400b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
15410b57cec5SDimitry Andric     visitDIExpression(*Expr);
15420b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
15430b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
15440b57cec5SDimitry Andric   }
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
154881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
15490b57cec5SDimitry Andric   if (auto *T = N.getRawType())
155081ad6265SDimitry Andric     CheckDI(isType(T), "invalid type ref", &N, T);
15510b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
155281ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15530b57cec5SDimitry Andric }
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
155681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
15570b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_imported_declaration,
15580b57cec5SDimitry Andric           "invalid tag", &N);
15590b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
156081ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
156181ad6265SDimitry Andric   CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
15620b57cec5SDimitry Andric           N.getRawEntity());
15630b57cec5SDimitry Andric }
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
15668bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
15678bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
15688bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
15690b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
157081ad6265SDimitry Andric       Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
157181ad6265SDimitry Andric             GV);
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
1574349cc55cSDimitry Andric void Verifier::visitModuleIdents() {
15750b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
15760b57cec5SDimitry Andric   if (!Idents)
15770b57cec5SDimitry Andric     return;
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
15800b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
15810b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
158281ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
15830b57cec5SDimitry Andric           "incorrect number of operands in llvm.ident metadata", N);
158481ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
15850b57cec5SDimitry Andric           ("invalid value for llvm.ident metadata entry operand"
15860b57cec5SDimitry Andric            "(the operand should be a string)"),
15870b57cec5SDimitry Andric           N->getOperand(0));
15880b57cec5SDimitry Andric   }
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
1591349cc55cSDimitry Andric void Verifier::visitModuleCommandLines() {
15920b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
15930b57cec5SDimitry Andric   if (!CommandLines)
15940b57cec5SDimitry Andric     return;
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
15970b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
15980b57cec5SDimitry Andric   // requirement is met.
15990b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
160081ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
16010b57cec5SDimitry Andric           "incorrect number of operands in llvm.commandline metadata", N);
160281ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
16030b57cec5SDimitry Andric           ("invalid value for llvm.commandline metadata entry operand"
16040b57cec5SDimitry Andric            "(the operand should be a string)"),
16050b57cec5SDimitry Andric           N->getOperand(0));
16060b57cec5SDimitry Andric   }
16070b57cec5SDimitry Andric }
16080b57cec5SDimitry Andric 
1609349cc55cSDimitry Andric void Verifier::visitModuleFlags() {
16100b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
16110b57cec5SDimitry Andric   if (!Flags) return;
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
16140b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
16150b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
16160b57cec5SDimitry Andric   for (const MDNode *MDN : Flags->operands())
16170b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
16200b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
16210b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
16220b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
16250b57cec5SDimitry Andric     if (!Op) {
16260b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
16270b57cec5SDimitry Andric                   Flag);
16280b57cec5SDimitry Andric       continue;
16290b57cec5SDimitry Andric     }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
16320b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
16330b57cec5SDimitry Andric                    "flag does not have the required value"),
16340b57cec5SDimitry Andric                   Flag);
16350b57cec5SDimitry Andric       continue;
16360b57cec5SDimitry Andric     }
16370b57cec5SDimitry Andric   }
16380b57cec5SDimitry Andric }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric void
16410b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
16420b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
16430b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
16440b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
16450b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
164681ad6265SDimitry Andric   Check(Op->getNumOperands() == 3,
16470b57cec5SDimitry Andric         "incorrect number of operands in module flag", Op);
16480b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
16490b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
165081ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
16510b57cec5SDimitry Andric           "invalid behavior operand in module flag (expected constant integer)",
16520b57cec5SDimitry Andric           Op->getOperand(0));
165381ad6265SDimitry Andric     Check(false,
16540b57cec5SDimitry Andric           "invalid behavior operand in module flag (unexpected constant)",
16550b57cec5SDimitry Andric           Op->getOperand(0));
16560b57cec5SDimitry Andric   }
16570b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
165881ad6265SDimitry Andric   Check(ID, "invalid ID operand in module flag (expected metadata string)",
16590b57cec5SDimitry Andric         Op->getOperand(1));
16600b57cec5SDimitry Andric 
16614824e7fdSDimitry Andric   // Check the values for behaviors with additional requirements.
16620b57cec5SDimitry Andric   switch (MFB) {
16630b57cec5SDimitry Andric   case Module::Error:
16640b57cec5SDimitry Andric   case Module::Warning:
16650b57cec5SDimitry Andric   case Module::Override:
16660b57cec5SDimitry Andric     // These behavior types accept any value.
16670b57cec5SDimitry Andric     break;
16680b57cec5SDimitry Andric 
166981ad6265SDimitry Andric   case Module::Min: {
1670fcaf7f86SDimitry Andric     auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1671fcaf7f86SDimitry Andric     Check(V && V->getValue().isNonNegative(),
1672fcaf7f86SDimitry Andric           "invalid value for 'min' module flag (expected constant non-negative "
1673fcaf7f86SDimitry Andric           "integer)",
167481ad6265SDimitry Andric           Op->getOperand(2));
167581ad6265SDimitry Andric     break;
167681ad6265SDimitry Andric   }
167781ad6265SDimitry Andric 
16780b57cec5SDimitry Andric   case Module::Max: {
167981ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
16800b57cec5SDimitry Andric           "invalid value for 'max' module flag (expected constant integer)",
16810b57cec5SDimitry Andric           Op->getOperand(2));
16820b57cec5SDimitry Andric     break;
16830b57cec5SDimitry Andric   }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   case Module::Require: {
16860b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
16870b57cec5SDimitry Andric     // MDString), and a value.
16880b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
168981ad6265SDimitry Andric     Check(Value && Value->getNumOperands() == 2,
16900b57cec5SDimitry Andric           "invalid value for 'require' module flag (expected metadata pair)",
16910b57cec5SDimitry Andric           Op->getOperand(2));
169281ad6265SDimitry Andric     Check(isa<MDString>(Value->getOperand(0)),
16930b57cec5SDimitry Andric           ("invalid value for 'require' module flag "
16940b57cec5SDimitry Andric            "(first value operand should be a string)"),
16950b57cec5SDimitry Andric           Value->getOperand(0));
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
16980b57cec5SDimitry Andric     // scanned.
16990b57cec5SDimitry Andric     Requirements.push_back(Value);
17000b57cec5SDimitry Andric     break;
17010b57cec5SDimitry Andric   }
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   case Module::Append:
17040b57cec5SDimitry Andric   case Module::AppendUnique: {
17050b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
170681ad6265SDimitry Andric     Check(isa<MDNode>(Op->getOperand(2)),
17070b57cec5SDimitry Andric           "invalid value for 'append'-type module flag "
17080b57cec5SDimitry Andric           "(expected a metadata node)",
17090b57cec5SDimitry Andric           Op->getOperand(2));
17100b57cec5SDimitry Andric     break;
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric   }
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
17150b57cec5SDimitry Andric   if (MFB != Module::Require) {
17160b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
171781ad6265SDimitry Andric     Check(Inserted,
17180b57cec5SDimitry Andric           "module flag identifiers must be unique (or of 'require' type)", ID);
17190b57cec5SDimitry Andric   }
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
17220b57cec5SDimitry Andric     ConstantInt *Value
17230b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
172481ad6265SDimitry Andric     Check(Value, "wchar_size metadata requires constant integer argument");
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
17280b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
17290b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
17300b57cec5SDimitry Andric     // have been created by a client directly.
173181ad6265SDimitry Andric     Check(M.getNamedMetadata("llvm.linker.options"),
17320b57cec5SDimitry Andric           "'Linker Options' named metadata no longer supported");
17330b57cec5SDimitry Andric   }
17340b57cec5SDimitry Andric 
17355ffd83dbSDimitry Andric   if (ID->getString() == "SemanticInterposition") {
17365ffd83dbSDimitry Andric     ConstantInt *Value =
17375ffd83dbSDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
173881ad6265SDimitry Andric     Check(Value,
17395ffd83dbSDimitry Andric           "SemanticInterposition metadata requires constant integer argument");
17405ffd83dbSDimitry Andric   }
17415ffd83dbSDimitry Andric 
17420b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
17430b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
17440b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
17450b57cec5SDimitry Andric   }
17460b57cec5SDimitry Andric }
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
17490b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
17500b57cec5SDimitry Andric     if (!FuncMDO)
17510b57cec5SDimitry Andric       return;
17520b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
175381ad6265SDimitry Andric     Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
1754e8d8bef9SDimitry Andric           "expected a Function or null", FuncMDO);
17550b57cec5SDimitry Andric   };
17560b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
175781ad6265SDimitry Andric   Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
17580b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
17590b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
17600b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
176181ad6265SDimitry Andric   Check(Count && Count->getType()->isIntegerTy(),
17620b57cec5SDimitry Andric         "expected an integer constant", Node->getOperand(2));
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
1765fe6060f1SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
17660b57cec5SDimitry Andric   for (Attribute A : Attrs) {
1767fe6060f1SDimitry Andric 
1768fe6060f1SDimitry Andric     if (A.isStringAttribute()) {
1769fe6060f1SDimitry Andric #define GET_ATTR_NAMES
1770fe6060f1SDimitry Andric #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1771fe6060f1SDimitry Andric #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1772fe6060f1SDimitry Andric   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1773fe6060f1SDimitry Andric     auto V = A.getValueAsString();                                             \
1774fe6060f1SDimitry Andric     if (!(V.empty() || V == "true" || V == "false"))                           \
1775fe6060f1SDimitry Andric       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1776fe6060f1SDimitry Andric                   "");                                                         \
1777fe6060f1SDimitry Andric   }
1778fe6060f1SDimitry Andric 
1779fe6060f1SDimitry Andric #include "llvm/IR/Attributes.inc"
17800b57cec5SDimitry Andric       continue;
1781fe6060f1SDimitry Andric     }
17820b57cec5SDimitry Andric 
1783fe6060f1SDimitry Andric     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
17845ffd83dbSDimitry Andric       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
17855ffd83dbSDimitry Andric                   V);
17865ffd83dbSDimitry Andric       return;
17875ffd83dbSDimitry Andric     }
17880b57cec5SDimitry Andric   }
17890b57cec5SDimitry Andric }
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
17920b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
17930b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
17940b57cec5SDimitry Andric                                     const Value *V) {
17950b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
17960b57cec5SDimitry Andric     return;
17970b57cec5SDimitry Andric 
1798fe6060f1SDimitry Andric   verifyAttributeTypes(Attrs, V);
1799fe6060f1SDimitry Andric 
1800fe6060f1SDimitry Andric   for (Attribute Attr : Attrs)
180181ad6265SDimitry Andric     Check(Attr.isStringAttribute() ||
1802fe6060f1SDimitry Andric               Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
180381ad6265SDimitry Andric           "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
1804fe6060f1SDimitry Andric           V);
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
180781ad6265SDimitry Andric     Check(Attrs.getNumAttributes() == 1,
18080b57cec5SDimitry Andric           "Attribute 'immarg' is incompatible with other attributes", V);
18090b57cec5SDimitry Andric   }
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
18120b57cec5SDimitry Andric   // sret.
18130b57cec5SDimitry Andric   unsigned AttrCount = 0;
18140b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
18150b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
18165ffd83dbSDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
18170b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
18180b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
18190b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1820e8d8bef9SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
182181ad6265SDimitry Andric   Check(AttrCount <= 1,
18225ffd83dbSDimitry Andric         "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1823e8d8bef9SDimitry Andric         "'byref', and 'sret' are incompatible!",
18240b57cec5SDimitry Andric         V);
18250b57cec5SDimitry Andric 
182681ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
18270b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
18280b57cec5SDimitry Andric         "Attributes "
18290b57cec5SDimitry Andric         "'inalloca and readonly' are incompatible!",
18300b57cec5SDimitry Andric         V);
18310b57cec5SDimitry Andric 
183281ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
18330b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::Returned)),
18340b57cec5SDimitry Andric         "Attributes "
18350b57cec5SDimitry Andric         "'sret and returned' are incompatible!",
18360b57cec5SDimitry Andric         V);
18370b57cec5SDimitry Andric 
183881ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
18390b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::SExt)),
18400b57cec5SDimitry Andric         "Attributes "
18410b57cec5SDimitry Andric         "'zeroext and signext' are incompatible!",
18420b57cec5SDimitry Andric         V);
18430b57cec5SDimitry Andric 
184481ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
18450b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
18460b57cec5SDimitry Andric         "Attributes "
18470b57cec5SDimitry Andric         "'readnone and readonly' are incompatible!",
18480b57cec5SDimitry Andric         V);
18490b57cec5SDimitry Andric 
185081ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
18510b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
18520b57cec5SDimitry Andric         "Attributes "
18530b57cec5SDimitry Andric         "'readnone and writeonly' are incompatible!",
18540b57cec5SDimitry Andric         V);
18550b57cec5SDimitry Andric 
185681ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
18570b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
18580b57cec5SDimitry Andric         "Attributes "
18590b57cec5SDimitry Andric         "'readonly and writeonly' are incompatible!",
18600b57cec5SDimitry Andric         V);
18610b57cec5SDimitry Andric 
186281ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
18630b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::AlwaysInline)),
18640b57cec5SDimitry Andric         "Attributes "
18650b57cec5SDimitry Andric         "'noinline and alwaysinline' are incompatible!",
18660b57cec5SDimitry Andric         V);
18670b57cec5SDimitry Andric 
186804eeddc0SDimitry Andric   AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1869fe6060f1SDimitry Andric   for (Attribute Attr : Attrs) {
1870fe6060f1SDimitry Andric     if (!Attr.isStringAttribute() &&
1871fe6060f1SDimitry Andric         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1872fe6060f1SDimitry Andric       CheckFailed("Attribute '" + Attr.getAsString() +
1873fe6060f1SDimitry Andric                   "' applied to incompatible type!", V);
1874fe6060f1SDimitry Andric       return;
1875fe6060f1SDimitry Andric     }
1876fe6060f1SDimitry Andric   }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1879fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByVal)) {
188081ad6265SDimitry Andric       if (Attrs.hasAttribute(Attribute::Alignment)) {
188181ad6265SDimitry Andric         Align AttrAlign = Attrs.getAlignment().valueOrOne();
188281ad6265SDimitry Andric         Align MaxAlign(ParamMaxAlignment);
188381ad6265SDimitry Andric         Check(AttrAlign <= MaxAlign,
188481ad6265SDimitry Andric               "Attribute 'align' exceed the max size 2^14", V);
188581ad6265SDimitry Andric       }
18860b57cec5SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
188781ad6265SDimitry Andric       Check(Attrs.getByValType()->isSized(&Visited),
1888fe6060f1SDimitry Andric             "Attribute 'byval' does not support unsized types!", V);
18890b57cec5SDimitry Andric     }
1890fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByRef)) {
1891fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
189281ad6265SDimitry Andric       Check(Attrs.getByRefType()->isSized(&Visited),
1893fe6060f1SDimitry Andric             "Attribute 'byref' does not support unsized types!", V);
1894fe6060f1SDimitry Andric     }
1895fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::InAlloca)) {
1896fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
189781ad6265SDimitry Andric       Check(Attrs.getInAllocaType()->isSized(&Visited),
1898fe6060f1SDimitry Andric             "Attribute 'inalloca' does not support unsized types!", V);
1899fe6060f1SDimitry Andric     }
1900fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::Preallocated)) {
1901fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
190281ad6265SDimitry Andric       Check(Attrs.getPreallocatedType()->isSized(&Visited),
1903fe6060f1SDimitry Andric             "Attribute 'preallocated' does not support unsized types!", V);
1904fe6060f1SDimitry Andric     }
1905fe6060f1SDimitry Andric     if (!PTy->isOpaque()) {
190604eeddc0SDimitry Andric       if (!isa<PointerType>(PTy->getNonOpaquePointerElementType()))
190781ad6265SDimitry Andric         Check(!Attrs.hasAttribute(Attribute::SwiftError),
19080b57cec5SDimitry Andric               "Attribute 'swifterror' only applies to parameters "
19090b57cec5SDimitry Andric               "with pointer to pointer type!",
19100b57cec5SDimitry Andric               V);
1911e8d8bef9SDimitry Andric       if (Attrs.hasAttribute(Attribute::ByRef)) {
191281ad6265SDimitry Andric         Check(Attrs.getByRefType() == PTy->getNonOpaquePointerElementType(),
1913e8d8bef9SDimitry Andric               "Attribute 'byref' type does not match parameter!", V);
1914e8d8bef9SDimitry Andric       }
1915e8d8bef9SDimitry Andric 
1916e8d8bef9SDimitry Andric       if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) {
191781ad6265SDimitry Andric         Check(Attrs.getByValType() == PTy->getNonOpaquePointerElementType(),
1918e8d8bef9SDimitry Andric               "Attribute 'byval' type does not match parameter!", V);
1919e8d8bef9SDimitry Andric       }
1920e8d8bef9SDimitry Andric 
1921e8d8bef9SDimitry Andric       if (Attrs.hasAttribute(Attribute::Preallocated)) {
192281ad6265SDimitry Andric         Check(Attrs.getPreallocatedType() ==
192304eeddc0SDimitry Andric                   PTy->getNonOpaquePointerElementType(),
1924e8d8bef9SDimitry Andric               "Attribute 'preallocated' type does not match parameter!", V);
1925e8d8bef9SDimitry Andric       }
1926fe6060f1SDimitry Andric 
1927fe6060f1SDimitry Andric       if (Attrs.hasAttribute(Attribute::InAlloca)) {
192881ad6265SDimitry Andric         Check(Attrs.getInAllocaType() == PTy->getNonOpaquePointerElementType(),
1929fe6060f1SDimitry Andric               "Attribute 'inalloca' type does not match parameter!", V);
1930fe6060f1SDimitry Andric       }
1931fe6060f1SDimitry Andric 
1932fe6060f1SDimitry Andric       if (Attrs.hasAttribute(Attribute::ElementType)) {
193381ad6265SDimitry Andric         Check(Attrs.getElementType() == PTy->getNonOpaquePointerElementType(),
1934fe6060f1SDimitry Andric               "Attribute 'elementtype' type does not match parameter!", V);
1935fe6060f1SDimitry Andric       }
1936fe6060f1SDimitry Andric     }
1937fe6060f1SDimitry Andric   }
1938fe6060f1SDimitry Andric }
1939fe6060f1SDimitry Andric 
1940fe6060f1SDimitry Andric void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1941fe6060f1SDimitry Andric                                             const Value *V) {
1942349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attr)) {
1943349cc55cSDimitry Andric     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1944fe6060f1SDimitry Andric     unsigned N;
1945fe6060f1SDimitry Andric     if (S.getAsInteger(10, N))
1946fe6060f1SDimitry Andric       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
19470b57cec5SDimitry Andric   }
19480b57cec5SDimitry Andric }
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric // Check parameter attributes against a function type.
19510b57cec5SDimitry Andric // The value V is printed in error messages.
19520b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
195304eeddc0SDimitry Andric                                    const Value *V, bool IsIntrinsic,
195404eeddc0SDimitry Andric                                    bool IsInlineAsm) {
19550b57cec5SDimitry Andric   if (Attrs.isEmpty())
19560b57cec5SDimitry Andric     return;
19570b57cec5SDimitry Andric 
1958fe6060f1SDimitry Andric   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
195981ad6265SDimitry Andric     Check(Attrs.hasParentContext(Context),
1960fe6060f1SDimitry Andric           "Attribute list does not match Module context!", &Attrs, V);
1961fe6060f1SDimitry Andric     for (const auto &AttrSet : Attrs) {
196281ad6265SDimitry Andric       Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
1963fe6060f1SDimitry Andric             "Attribute set does not match Module context!", &AttrSet, V);
1964fe6060f1SDimitry Andric       for (const auto &A : AttrSet) {
196581ad6265SDimitry Andric         Check(A.hasParentContext(Context),
1966fe6060f1SDimitry Andric               "Attribute does not match Module context!", &A, V);
1967fe6060f1SDimitry Andric       }
1968fe6060f1SDimitry Andric     }
1969fe6060f1SDimitry Andric   }
1970fe6060f1SDimitry Andric 
19710b57cec5SDimitry Andric   bool SawNest = false;
19720b57cec5SDimitry Andric   bool SawReturned = false;
19730b57cec5SDimitry Andric   bool SawSRet = false;
19740b57cec5SDimitry Andric   bool SawSwiftSelf = false;
1975fe6060f1SDimitry Andric   bool SawSwiftAsync = false;
19760b57cec5SDimitry Andric   bool SawSwiftError = false;
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric   // Verify return value attributes.
1979349cc55cSDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttrs();
1980fe6060f1SDimitry Andric   for (Attribute RetAttr : RetAttrs)
198181ad6265SDimitry Andric     Check(RetAttr.isStringAttribute() ||
1982fe6060f1SDimitry Andric               Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
1983fe6060f1SDimitry Andric           "Attribute '" + RetAttr.getAsString() +
1984fe6060f1SDimitry Andric               "' does not apply to function return values",
19850b57cec5SDimitry Andric           V);
1986fe6060f1SDimitry Andric 
19870b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric   // Verify parameter attributes.
19900b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
19910b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
1992349cc55cSDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric     if (!IsIntrinsic) {
199581ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
19960b57cec5SDimitry Andric             "immarg attribute only applies to intrinsics", V);
199704eeddc0SDimitry Andric       if (!IsInlineAsm)
199881ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
199904eeddc0SDimitry Andric               "Attribute 'elementtype' can only be applied to intrinsics"
200081ad6265SDimitry Andric               " and inline asm.",
200181ad6265SDimitry Andric               V);
20020b57cec5SDimitry Andric     }
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
200781ad6265SDimitry Andric       Check(!SawNest, "More than one parameter has attribute nest!", V);
20080b57cec5SDimitry Andric       SawNest = true;
20090b57cec5SDimitry Andric     }
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
201281ad6265SDimitry Andric       Check(!SawReturned, "More than one parameter has attribute returned!", V);
201381ad6265SDimitry Andric       Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
20140b57cec5SDimitry Andric             "Incompatible argument and return types for 'returned' attribute",
20150b57cec5SDimitry Andric             V);
20160b57cec5SDimitry Andric       SawReturned = true;
20170b57cec5SDimitry Andric     }
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
202081ad6265SDimitry Andric       Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
202181ad6265SDimitry Andric       Check(i == 0 || i == 1,
20220b57cec5SDimitry Andric             "Attribute 'sret' is not on first or second parameter!", V);
20230b57cec5SDimitry Andric       SawSRet = true;
20240b57cec5SDimitry Andric     }
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
202781ad6265SDimitry Andric       Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
20280b57cec5SDimitry Andric       SawSwiftSelf = true;
20290b57cec5SDimitry Andric     }
20300b57cec5SDimitry Andric 
2031fe6060f1SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
203281ad6265SDimitry Andric       Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2033fe6060f1SDimitry Andric       SawSwiftAsync = true;
2034fe6060f1SDimitry Andric     }
2035fe6060f1SDimitry Andric 
20360b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
203781ad6265SDimitry Andric       Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
20380b57cec5SDimitry Andric       SawSwiftError = true;
20390b57cec5SDimitry Andric     }
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
204281ad6265SDimitry Andric       Check(i == FT->getNumParams() - 1,
20430b57cec5SDimitry Andric             "inalloca isn't on the last parameter!", V);
20440b57cec5SDimitry Andric     }
20450b57cec5SDimitry Andric   }
20460b57cec5SDimitry Andric 
2047349cc55cSDimitry Andric   if (!Attrs.hasFnAttrs())
20480b57cec5SDimitry Andric     return;
20490b57cec5SDimitry Andric 
2050349cc55cSDimitry Andric   verifyAttributeTypes(Attrs.getFnAttrs(), V);
2051349cc55cSDimitry Andric   for (Attribute FnAttr : Attrs.getFnAttrs())
205281ad6265SDimitry Andric     Check(FnAttr.isStringAttribute() ||
2053fe6060f1SDimitry Andric               Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2054fe6060f1SDimitry Andric           "Attribute '" + FnAttr.getAsString() +
2055fe6060f1SDimitry Andric               "' does not apply to functions!",
2056fe6060f1SDimitry Andric           V);
20570b57cec5SDimitry Andric 
205881ad6265SDimitry Andric   Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2059349cc55cSDimitry Andric           Attrs.hasFnAttr(Attribute::AlwaysInline)),
20600b57cec5SDimitry Andric         "Attributes 'noinline and alwaysinline' are incompatible!", V);
20610b57cec5SDimitry Andric 
2062349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
206381ad6265SDimitry Andric     Check(Attrs.hasFnAttr(Attribute::NoInline),
20640b57cec5SDimitry Andric           "Attribute 'optnone' requires 'noinline'!", V);
20650b57cec5SDimitry Andric 
206681ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
20670b57cec5SDimitry Andric           "Attributes 'optsize and optnone' are incompatible!", V);
20680b57cec5SDimitry Andric 
206981ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
20700b57cec5SDimitry Andric           "Attributes 'minsize and optnone' are incompatible!", V);
20710b57cec5SDimitry Andric   }
20720b57cec5SDimitry Andric 
2073*bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2074*bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2075*bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_sm_enabled and "
2076*bdd1243dSDimitry Andric            "aarch64_pstate_sm_compatible' are incompatible!",
2077*bdd1243dSDimitry Andric            V);
2078*bdd1243dSDimitry Andric   }
2079*bdd1243dSDimitry Andric 
2080*bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_za_new")) {
2081*bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_za_preserved"),
2082*bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2083*bdd1243dSDimitry Andric            "are incompatible!",
2084*bdd1243dSDimitry Andric            V);
2085*bdd1243dSDimitry Andric 
2086*bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_za_shared"),
2087*bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2088*bdd1243dSDimitry Andric            "are incompatible!",
2089*bdd1243dSDimitry Andric            V);
2090*bdd1243dSDimitry Andric   }
2091*bdd1243dSDimitry Andric 
2092349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
20930b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
209481ad6265SDimitry Andric     Check(GV->hasGlobalUnnamedAddr(),
20950b57cec5SDimitry Andric           "Attribute 'jumptable' requires 'unnamed_addr'", V);
20960b57cec5SDimitry Andric   }
20970b57cec5SDimitry Andric 
2098*bdd1243dSDimitry Andric   if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
20990b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
21000b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
21010b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
21020b57cec5SDimitry Andric         return false;
21030b57cec5SDimitry Andric       }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
21060b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
21070b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
21080b57cec5SDimitry Andric                     V);
21090b57cec5SDimitry Andric         return false;
21100b57cec5SDimitry Andric       }
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric       return true;
21130b57cec5SDimitry Andric     };
21140b57cec5SDimitry Andric 
2115*bdd1243dSDimitry Andric     if (!CheckParam("element size", Args->first))
21160b57cec5SDimitry Andric       return;
21170b57cec5SDimitry Andric 
2118*bdd1243dSDimitry Andric     if (Args->second && !CheckParam("number of elements", *Args->second))
21190b57cec5SDimitry Andric       return;
21200b57cec5SDimitry Andric   }
2121480093f4SDimitry Andric 
212281ad6265SDimitry Andric   if (Attrs.hasFnAttr(Attribute::AllocKind)) {
212381ad6265SDimitry Andric     AllocFnKind K = Attrs.getAllocKind();
212481ad6265SDimitry Andric     AllocFnKind Type =
212581ad6265SDimitry Andric         K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
212681ad6265SDimitry Andric     if (!is_contained(
212781ad6265SDimitry Andric             {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
212881ad6265SDimitry Andric             Type))
212981ad6265SDimitry Andric       CheckFailed(
213081ad6265SDimitry Andric           "'allockind()' requires exactly one of alloc, realloc, and free");
213181ad6265SDimitry Andric     if ((Type == AllocFnKind::Free) &&
213281ad6265SDimitry Andric         ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
213381ad6265SDimitry Andric                AllocFnKind::Aligned)) != AllocFnKind::Unknown))
213481ad6265SDimitry Andric       CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
213581ad6265SDimitry Andric                   "or aligned modifiers.");
213681ad6265SDimitry Andric     AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
213781ad6265SDimitry Andric     if ((K & ZeroedUninit) == ZeroedUninit)
213881ad6265SDimitry Andric       CheckFailed("'allockind()' can't be both zeroed and uninitialized");
213981ad6265SDimitry Andric   }
214081ad6265SDimitry Andric 
2141349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
21420eae32dcSDimitry Andric     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
21430eae32dcSDimitry Andric     if (VScaleMin == 0)
21440eae32dcSDimitry Andric       CheckFailed("'vscale_range' minimum must be greater than 0", V);
2145fe6060f1SDimitry Andric 
2146*bdd1243dSDimitry Andric     std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
21470eae32dcSDimitry Andric     if (VScaleMax && VScaleMin > VScaleMax)
2148fe6060f1SDimitry Andric       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2149fe6060f1SDimitry Andric   }
2150fe6060f1SDimitry Andric 
2151349cc55cSDimitry Andric   if (Attrs.hasFnAttr("frame-pointer")) {
2152349cc55cSDimitry Andric     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2153480093f4SDimitry Andric     if (FP != "all" && FP != "non-leaf" && FP != "none")
2154480093f4SDimitry Andric       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2155480093f4SDimitry Andric   }
2156480093f4SDimitry Andric 
2157fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2158fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2159fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
21600b57cec5SDimitry Andric }
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
21630b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
21640b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
21650b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
21660b57cec5SDimitry Andric       MDNode *MD = Pair.second;
216781ad6265SDimitry Andric       Check(MD->getNumOperands() >= 2,
21680b57cec5SDimitry Andric             "!prof annotations should have no less than 2 operands", MD);
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric       // Check first operand.
217181ad6265SDimitry Andric       Check(MD->getOperand(0) != nullptr, "first operand should not be null",
21720b57cec5SDimitry Andric             MD);
217381ad6265SDimitry Andric       Check(isa<MDString>(MD->getOperand(0)),
21740b57cec5SDimitry Andric             "expected string with name of the !prof annotation", MD);
21750b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
21760b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
217781ad6265SDimitry Andric       Check(ProfName.equals("function_entry_count") ||
21780b57cec5SDimitry Andric                 ProfName.equals("synthetic_function_entry_count"),
21790b57cec5SDimitry Andric             "first operand should be 'function_entry_count'"
21800b57cec5SDimitry Andric             " or 'synthetic_function_entry_count'",
21810b57cec5SDimitry Andric             MD);
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric       // Check second operand.
218481ad6265SDimitry Andric       Check(MD->getOperand(1) != nullptr, "second operand should not be null",
21850b57cec5SDimitry Andric             MD);
218681ad6265SDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
21870b57cec5SDimitry Andric             "expected integer argument to function_entry_count", MD);
2188*bdd1243dSDimitry Andric     } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2189*bdd1243dSDimitry Andric       MDNode *MD = Pair.second;
2190*bdd1243dSDimitry Andric       Check(MD->getNumOperands() == 1,
2191*bdd1243dSDimitry Andric             "!kcfi_type must have exactly one operand", MD);
2192*bdd1243dSDimitry Andric       Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2193*bdd1243dSDimitry Andric             MD);
2194*bdd1243dSDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
2195*bdd1243dSDimitry Andric             "expected a constant operand for !kcfi_type", MD);
2196*bdd1243dSDimitry Andric       Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2197*bdd1243dSDimitry Andric       Check(isa<ConstantInt>(C),
2198*bdd1243dSDimitry Andric             "expected a constant integer operand for !kcfi_type", MD);
2199*bdd1243dSDimitry Andric       IntegerType *Type = cast<ConstantInt>(C)->getType();
2200*bdd1243dSDimitry Andric       Check(Type->getBitWidth() == 32,
2201*bdd1243dSDimitry Andric             "expected a 32-bit integer constant operand for !kcfi_type", MD);
22020b57cec5SDimitry Andric     }
22030b57cec5SDimitry Andric   }
22040b57cec5SDimitry Andric }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
22070b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
22080b57cec5SDimitry Andric     return;
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
22110b57cec5SDimitry Andric   Stack.push_back(EntryC);
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric   while (!Stack.empty()) {
22140b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric     // Check this constant expression.
22170b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
22180b57cec5SDimitry Andric       visitConstantExpr(CE);
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
22210b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
22220b57cec5SDimitry Andric       // that the global value is in the correct module
222381ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!",
22240b57cec5SDimitry Andric             EntryC, &M, GV, GV->getParent());
22250b57cec5SDimitry Andric       continue;
22260b57cec5SDimitry Andric     }
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric     // Visit all sub-expressions.
22290b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
22300b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
22310b57cec5SDimitry Andric       if (!OpC)
22320b57cec5SDimitry Andric         continue;
22330b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
22340b57cec5SDimitry Andric         continue;
22350b57cec5SDimitry Andric       Stack.push_back(OpC);
22360b57cec5SDimitry Andric     }
22370b57cec5SDimitry Andric   }
22380b57cec5SDimitry Andric }
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
22410b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
224281ad6265SDimitry Andric     Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
22430b57cec5SDimitry Andric                                 CE->getType()),
22440b57cec5SDimitry Andric           "Invalid bitcast", CE);
22450b57cec5SDimitry Andric }
22460b57cec5SDimitry Andric 
22470b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
22480b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
22490b57cec5SDimitry Andric   // function and return value.
22500b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
22510b57cec5SDimitry Andric }
22520b57cec5SDimitry Andric 
225304eeddc0SDimitry Andric void Verifier::verifyInlineAsmCall(const CallBase &Call) {
225404eeddc0SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
225504eeddc0SDimitry Andric   unsigned ArgNo = 0;
2256fcaf7f86SDimitry Andric   unsigned LabelNo = 0;
225704eeddc0SDimitry Andric   for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2258fcaf7f86SDimitry Andric     if (CI.Type == InlineAsm::isLabel) {
2259fcaf7f86SDimitry Andric       ++LabelNo;
2260fcaf7f86SDimitry Andric       continue;
2261fcaf7f86SDimitry Andric     }
2262fcaf7f86SDimitry Andric 
226304eeddc0SDimitry Andric     // Only deal with constraints that correspond to call arguments.
226404eeddc0SDimitry Andric     if (!CI.hasArg())
226504eeddc0SDimitry Andric       continue;
226604eeddc0SDimitry Andric 
226704eeddc0SDimitry Andric     if (CI.isIndirect) {
226804eeddc0SDimitry Andric       const Value *Arg = Call.getArgOperand(ArgNo);
226981ad6265SDimitry Andric       Check(Arg->getType()->isPointerTy(),
227081ad6265SDimitry Andric             "Operand for indirect constraint must have pointer type", &Call);
227104eeddc0SDimitry Andric 
227281ad6265SDimitry Andric       Check(Call.getParamElementType(ArgNo),
227304eeddc0SDimitry Andric             "Operand for indirect constraint must have elementtype attribute",
227404eeddc0SDimitry Andric             &Call);
227504eeddc0SDimitry Andric     } else {
227681ad6265SDimitry Andric       Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
227704eeddc0SDimitry Andric             "Elementtype attribute can only be applied for indirect "
227881ad6265SDimitry Andric             "constraints",
227981ad6265SDimitry Andric             &Call);
228004eeddc0SDimitry Andric     }
228104eeddc0SDimitry Andric 
228204eeddc0SDimitry Andric     ArgNo++;
228304eeddc0SDimitry Andric   }
2284fcaf7f86SDimitry Andric 
2285fcaf7f86SDimitry Andric   if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2286fcaf7f86SDimitry Andric     Check(LabelNo == CallBr->getNumIndirectDests(),
2287fcaf7f86SDimitry Andric           "Number of label constraints does not match number of callbr dests",
2288fcaf7f86SDimitry Andric           &Call);
2289fcaf7f86SDimitry Andric   } else {
2290fcaf7f86SDimitry Andric     Check(LabelNo == 0, "Label constraints can only be used with callbr",
2291fcaf7f86SDimitry Andric           &Call);
2292fcaf7f86SDimitry Andric   }
229304eeddc0SDimitry Andric }
229404eeddc0SDimitry Andric 
22950b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
22960b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
22970b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
22980b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
22990b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
23000b57cec5SDimitry Andric 
230181ad6265SDimitry Andric   Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
23020b57cec5SDimitry Andric             !Call.onlyAccessesArgMemory(),
23030b57cec5SDimitry Andric         "gc.statepoint must read and write all memory to preserve "
23040b57cec5SDimitry Andric         "reordering restrictions required by safepoint semantics",
23050b57cec5SDimitry Andric         Call);
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric   const int64_t NumPatchBytes =
23080b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
23090b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
231081ad6265SDimitry Andric   Check(NumPatchBytes >= 0,
23110b57cec5SDimitry Andric         "gc.statepoint number of patchable bytes must be "
23120b57cec5SDimitry Andric         "positive",
23130b57cec5SDimitry Andric         Call);
23140b57cec5SDimitry Andric 
231581ad6265SDimitry Andric   Type *TargetElemType = Call.getParamElementType(2);
231681ad6265SDimitry Andric   Check(TargetElemType,
231781ad6265SDimitry Andric         "gc.statepoint callee argument must have elementtype attribute", Call);
231881ad6265SDimitry Andric   FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
231981ad6265SDimitry Andric   Check(TargetFuncType,
232081ad6265SDimitry Andric         "gc.statepoint callee elementtype must be function type", Call);
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
232381ad6265SDimitry Andric   Check(NumCallArgs >= 0,
23240b57cec5SDimitry Andric         "gc.statepoint number of arguments to underlying call "
23250b57cec5SDimitry Andric         "must be positive",
23260b57cec5SDimitry Andric         Call);
23270b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
23280b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
232981ad6265SDimitry Andric     Check(NumCallArgs >= NumParams,
23300b57cec5SDimitry Andric           "gc.statepoint mismatch in number of vararg call args", Call);
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric     // TODO: Remove this limitation
233381ad6265SDimitry Andric     Check(TargetFuncType->getReturnType()->isVoidTy(),
23340b57cec5SDimitry Andric           "gc.statepoint doesn't support wrapping non-void "
23350b57cec5SDimitry Andric           "vararg functions yet",
23360b57cec5SDimitry Andric           Call);
23370b57cec5SDimitry Andric   } else
233881ad6265SDimitry Andric     Check(NumCallArgs == NumParams,
23390b57cec5SDimitry Andric           "gc.statepoint mismatch in number of call args", Call);
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   const uint64_t Flags
23420b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
234381ad6265SDimitry Andric   Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
23440b57cec5SDimitry Andric         "unknown flag used in gc.statepoint flags argument", Call);
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
23470b57cec5SDimitry Andric   // the type of the wrapped callee.
23480b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
23490b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
23500b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
23510b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
235281ad6265SDimitry Andric     Check(ArgType == ParamType,
23530b57cec5SDimitry Andric           "gc.statepoint call argument does not match wrapped "
23540b57cec5SDimitry Andric           "function type",
23550b57cec5SDimitry Andric           Call);
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
2358349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
235981ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
236081ad6265SDimitry Andric             "Attribute 'sret' cannot be used for vararg call arguments!", Call);
23610b57cec5SDimitry Andric     }
23620b57cec5SDimitry Andric   }
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
236781ad6265SDimitry Andric   Check(isa<ConstantInt>(NumTransitionArgsV),
23680b57cec5SDimitry Andric         "gc.statepoint number of transition arguments "
23690b57cec5SDimitry Andric         "must be constant integer",
23700b57cec5SDimitry Andric         Call);
23710b57cec5SDimitry Andric   const int NumTransitionArgs =
23720b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
237381ad6265SDimitry Andric   Check(NumTransitionArgs == 0,
2374e8d8bef9SDimitry Andric         "gc.statepoint w/inline transition bundle is deprecated", Call);
2375e8d8bef9SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
23765ffd83dbSDimitry Andric 
23770b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
237881ad6265SDimitry Andric   Check(isa<ConstantInt>(NumDeoptArgsV),
23790b57cec5SDimitry Andric         "gc.statepoint number of deoptimization arguments "
23800b57cec5SDimitry Andric         "must be constant integer",
23810b57cec5SDimitry Andric         Call);
23820b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
238381ad6265SDimitry Andric   Check(NumDeoptArgs == 0,
2384e8d8bef9SDimitry Andric         "gc.statepoint w/inline deopt operands is deprecated", Call);
23855ffd83dbSDimitry Andric 
2386e8d8bef9SDimitry Andric   const int ExpectedNumArgs = 7 + NumCallArgs;
238781ad6265SDimitry Andric   Check(ExpectedNumArgs == (int)Call.arg_size(),
2388e8d8bef9SDimitry Andric         "gc.statepoint too many arguments", Call);
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
23910b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
23920b57cec5SDimitry Andric   // of the same statepoint sequence
23930b57cec5SDimitry Andric   for (const User *U : Call.users()) {
23940b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
239581ad6265SDimitry Andric     Check(UserCall, "illegal use of statepoint token", Call, U);
23960b57cec5SDimitry Andric     if (!UserCall)
23970b57cec5SDimitry Andric       continue;
239881ad6265SDimitry Andric     Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
23990b57cec5SDimitry Andric           "gc.result or gc.relocate are the only value uses "
24000b57cec5SDimitry Andric           "of a gc.statepoint",
24010b57cec5SDimitry Andric           Call, U);
24020b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
240381ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
24040b57cec5SDimitry Andric             "gc.result connected to wrong gc.statepoint", Call, UserCall);
24050b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
240681ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
24070b57cec5SDimitry Andric             "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
24080b57cec5SDimitry Andric     }
24090b57cec5SDimitry Andric   }
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
24120b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
24130b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
24140b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
24150b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
24160b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
24170b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
24180b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
24190b57cec5SDimitry Andric }
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
24220b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
24230b57cec5SDimitry Andric     Function *F = Counts.first;
24240b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
24250b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
242681ad6265SDimitry Andric     Check(MaxRecoveredIndex <= EscapedObjectCount,
24270b57cec5SDimitry Andric           "all indices passed to llvm.localrecover must be less than the "
24280b57cec5SDimitry Andric           "number of arguments passed to llvm.localescape in the parent "
24290b57cec5SDimitry Andric           "function",
24300b57cec5SDimitry Andric           F);
24310b57cec5SDimitry Andric   }
24320b57cec5SDimitry Andric }
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
24350b57cec5SDimitry Andric   BasicBlock *UnwindDest;
24360b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
24370b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
24380b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
24390b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
24400b57cec5SDimitry Andric   else
24410b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
24420b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
24430b57cec5SDimitry Andric }
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
24460b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
24470b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
24480b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
24490b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
24500b57cec5SDimitry Andric     if (Visited.count(PredPad))
24510b57cec5SDimitry Andric       continue;
24520b57cec5SDimitry Andric     Active.insert(PredPad);
24530b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
24540b57cec5SDimitry Andric     do {
24550b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
24560b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
24570b57cec5SDimitry Andric         // Found a cycle; report error
24580b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
24590b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
24600b57cec5SDimitry Andric         do {
24610b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
24620b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
24630b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
24640b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
24650b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
24660b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
246781ad6265SDimitry Andric         Check(false, "EH pads can't handle each other's exceptions",
24680b57cec5SDimitry Andric               ArrayRef<Instruction *>(CycleNodes));
24690b57cec5SDimitry Andric       }
24700b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
24710b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
24720b57cec5SDimitry Andric         break;
24730b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
24740b57cec5SDimitry Andric       PredPad = SuccPad;
24750b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
24760b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
24770b57cec5SDimitry Andric         break;
24780b57cec5SDimitry Andric       Terminator = TermI->second;
24790b57cec5SDimitry Andric       Active.insert(PredPad);
24800b57cec5SDimitry Andric     } while (true);
24810b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
24820b57cec5SDimitry Andric     // nodes' successors.
24830b57cec5SDimitry Andric     Active.clear();
24840b57cec5SDimitry Andric   }
24850b57cec5SDimitry Andric }
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
24880b57cec5SDimitry Andric //
24890b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
24900b57cec5SDimitry Andric   visitGlobalValue(F);
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric   // Check function arguments.
24930b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
24940b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
24950b57cec5SDimitry Andric 
249681ad6265SDimitry Andric   Check(&Context == &F.getContext(),
24970b57cec5SDimitry Andric         "Function context does not match Module context!", &F);
24980b57cec5SDimitry Andric 
249981ad6265SDimitry Andric   Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
250081ad6265SDimitry Andric   Check(FT->getNumParams() == NumArgs,
25010b57cec5SDimitry Andric         "# formal arguments must match # of arguments for function type!", &F,
25020b57cec5SDimitry Andric         FT);
250381ad6265SDimitry Andric   Check(F.getReturnType()->isFirstClassType() ||
25040b57cec5SDimitry Andric             F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
25050b57cec5SDimitry Andric         "Functions cannot return aggregate values!", &F);
25060b57cec5SDimitry Andric 
250781ad6265SDimitry Andric   Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
25080b57cec5SDimitry Andric         "Invalid struct return type!", &F);
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
25110b57cec5SDimitry Andric 
251281ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, FT->getNumParams()),
25130b57cec5SDimitry Andric         "Attribute after last parameter!", &F);
25140b57cec5SDimitry Andric 
2515fe6060f1SDimitry Andric   bool IsIntrinsic = F.isIntrinsic();
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   // Check function attributes.
251804eeddc0SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
25210b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
25220b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
252381ad6265SDimitry Andric   Check(!Attrs.hasFnAttr(Attribute::Builtin),
25240b57cec5SDimitry Andric         "Attribute 'builtin' can only be applied to a callsite.", &F);
25250b57cec5SDimitry Andric 
252681ad6265SDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2527fe6060f1SDimitry Andric         "Attribute 'elementtype' can only be applied to a callsite.", &F);
2528fe6060f1SDimitry Andric 
25290b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
25300b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
25310b57cec5SDimitry Andric   // restrictions can be lifted.
25320b57cec5SDimitry Andric   switch (F.getCallingConv()) {
25330b57cec5SDimitry Andric   default:
25340b57cec5SDimitry Andric   case CallingConv::C:
25350b57cec5SDimitry Andric     break;
2536e8d8bef9SDimitry Andric   case CallingConv::X86_INTR: {
253781ad6265SDimitry Andric     Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2538e8d8bef9SDimitry Andric           "Calling convention parameter requires byval", &F);
2539e8d8bef9SDimitry Andric     break;
2540e8d8bef9SDimitry Andric   }
25410b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
25420b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
254381ad6265SDimitry Andric     Check(F.getReturnType()->isVoidTy(),
25440b57cec5SDimitry Andric           "Calling convention requires void return type", &F);
2545*bdd1243dSDimitry Andric     [[fallthrough]];
25460b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
25470b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
25480b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
25490b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
25500b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
255181ad6265SDimitry Andric     Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
2552e8d8bef9SDimitry Andric     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2553e8d8bef9SDimitry Andric       const unsigned StackAS = DL.getAllocaAddrSpace();
2554e8d8bef9SDimitry Andric       unsigned i = 0;
2555e8d8bef9SDimitry Andric       for (const Argument &Arg : F.args()) {
255681ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
2557e8d8bef9SDimitry Andric               "Calling convention disallows byval", &F);
255881ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2559e8d8bef9SDimitry Andric               "Calling convention disallows preallocated", &F);
256081ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2561e8d8bef9SDimitry Andric               "Calling convention disallows inalloca", &F);
2562e8d8bef9SDimitry Andric 
2563349cc55cSDimitry Andric         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2564e8d8bef9SDimitry Andric           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2565e8d8bef9SDimitry Andric           // value here.
256681ad6265SDimitry Andric           Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2567e8d8bef9SDimitry Andric                 "Calling convention disallows stack byref", &F);
2568e8d8bef9SDimitry Andric         }
2569e8d8bef9SDimitry Andric 
2570e8d8bef9SDimitry Andric         ++i;
2571e8d8bef9SDimitry Andric       }
2572e8d8bef9SDimitry Andric     }
2573e8d8bef9SDimitry Andric 
2574*bdd1243dSDimitry Andric     [[fallthrough]];
25750b57cec5SDimitry Andric   case CallingConv::Fast:
25760b57cec5SDimitry Andric   case CallingConv::Cold:
25770b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
25780b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
25790b57cec5SDimitry Andric   case CallingConv::PTX_Device:
258081ad6265SDimitry Andric     Check(!F.isVarArg(),
258181ad6265SDimitry Andric           "Calling convention does not support varargs or "
25820b57cec5SDimitry Andric           "perfect forwarding!",
25830b57cec5SDimitry Andric           &F);
25840b57cec5SDimitry Andric     break;
25850b57cec5SDimitry Andric   }
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
25880b57cec5SDimitry Andric   unsigned i = 0;
25890b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
259081ad6265SDimitry Andric     Check(Arg.getType() == FT->getParamType(i),
25910b57cec5SDimitry Andric           "Argument value does not match function argument type!", &Arg,
25920b57cec5SDimitry Andric           FT->getParamType(i));
259381ad6265SDimitry Andric     Check(Arg.getType()->isFirstClassType(),
25940b57cec5SDimitry Andric           "Function arguments must have first-class types!", &Arg);
2595fe6060f1SDimitry Andric     if (!IsIntrinsic) {
259681ad6265SDimitry Andric       Check(!Arg.getType()->isMetadataTy(),
25970b57cec5SDimitry Andric             "Function takes metadata but isn't an intrinsic", &Arg, &F);
259881ad6265SDimitry Andric       Check(!Arg.getType()->isTokenTy(),
25990b57cec5SDimitry Andric             "Function takes token but isn't an intrinsic", &Arg, &F);
260081ad6265SDimitry Andric       Check(!Arg.getType()->isX86_AMXTy(),
2601fe6060f1SDimitry Andric             "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
26020b57cec5SDimitry Andric     }
26030b57cec5SDimitry Andric 
26040b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
2605349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
26060b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
26070b57cec5SDimitry Andric     }
26080b57cec5SDimitry Andric     ++i;
26090b57cec5SDimitry Andric   }
26100b57cec5SDimitry Andric 
2611fe6060f1SDimitry Andric   if (!IsIntrinsic) {
261281ad6265SDimitry Andric     Check(!F.getReturnType()->isTokenTy(),
2613fe6060f1SDimitry Andric           "Function returns a token but isn't an intrinsic", &F);
261481ad6265SDimitry Andric     Check(!F.getReturnType()->isX86_AMXTy(),
2615fe6060f1SDimitry Andric           "Function returns a x86_amx but isn't an intrinsic", &F);
2616fe6060f1SDimitry Andric   }
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric   // Get the function metadata attachments.
26190b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
26200b57cec5SDimitry Andric   F.getAllMetadata(MDs);
26210b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
26220b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric   // Check validity of the personality function
26250b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
26260b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
26270b57cec5SDimitry Andric     if (Per)
262881ad6265SDimitry Andric       Check(Per->getParent() == F.getParent(),
262981ad6265SDimitry Andric             "Referencing personality function in another module!", &F,
263081ad6265SDimitry Andric             F.getParent(), Per, Per->getParent());
26310b57cec5SDimitry Andric   }
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric   if (F.isMaterializable()) {
26340b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
263581ad6265SDimitry Andric     Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
26360b57cec5SDimitry Andric           MDs.empty() ? nullptr : MDs.front().second);
26370b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
26380b57cec5SDimitry Andric     for (const auto &I : MDs) {
26390b57cec5SDimitry Andric       // This is used for call site debug information.
264081ad6265SDimitry Andric       CheckDI(I.first != LLVMContext::MD_dbg ||
26410b57cec5SDimitry Andric                   !cast<DISubprogram>(I.second)->isDistinct(),
26420b57cec5SDimitry Andric               "function declaration may only have a unique !dbg attachment",
26430b57cec5SDimitry Andric               &F);
264481ad6265SDimitry Andric       Check(I.first != LLVMContext::MD_prof,
26450b57cec5SDimitry Andric             "function declaration may not have a !prof attachment", &F);
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric       // Verify the metadata itself.
26485ffd83dbSDimitry Andric       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
26490b57cec5SDimitry Andric     }
265081ad6265SDimitry Andric     Check(!F.hasPersonalityFn(),
26510b57cec5SDimitry Andric           "Function declaration shouldn't have a personality routine", &F);
26520b57cec5SDimitry Andric   } else {
26530b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
26540b57cec5SDimitry Andric     // is not legal to define intrinsics.
265581ad6265SDimitry Andric     Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric     // Check the entry node
26580b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
265981ad6265SDimitry Andric     Check(pred_empty(Entry),
26600b57cec5SDimitry Andric           "Entry block to function must not have predecessors!", Entry);
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
26630b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
266481ad6265SDimitry Andric       Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
26650b57cec5SDimitry Andric             "blockaddress may not be used with the entry block!", Entry);
26660b57cec5SDimitry Andric     }
26670b57cec5SDimitry Andric 
2668*bdd1243dSDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2669*bdd1243dSDimitry Andric              NumKCFIAttachments = 0;
26700b57cec5SDimitry Andric     // Visit metadata attachments.
26710b57cec5SDimitry Andric     for (const auto &I : MDs) {
26720b57cec5SDimitry Andric       // Verify that the attachment is legal.
26735ffd83dbSDimitry Andric       auto AllowLocs = AreDebugLocsAllowed::No;
26740b57cec5SDimitry Andric       switch (I.first) {
26750b57cec5SDimitry Andric       default:
26760b57cec5SDimitry Andric         break;
26770b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
26780b57cec5SDimitry Andric         ++NumDebugAttachments;
267981ad6265SDimitry Andric         CheckDI(NumDebugAttachments == 1,
26800b57cec5SDimitry Andric                 "function must have a single !dbg attachment", &F, I.second);
268181ad6265SDimitry Andric         CheckDI(isa<DISubprogram>(I.second),
26820b57cec5SDimitry Andric                 "function !dbg attachment must be a subprogram", &F, I.second);
268381ad6265SDimitry Andric         CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
2684e8d8bef9SDimitry Andric                 "function definition may only have a distinct !dbg attachment",
2685e8d8bef9SDimitry Andric                 &F);
2686e8d8bef9SDimitry Andric 
26870b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
26880b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
268981ad6265SDimitry Andric         CheckDI(!AttachedTo || AttachedTo == &F,
26900b57cec5SDimitry Andric                 "DISubprogram attached to more than one function", SP, &F);
26910b57cec5SDimitry Andric         AttachedTo = &F;
26925ffd83dbSDimitry Andric         AllowLocs = AreDebugLocsAllowed::Yes;
26930b57cec5SDimitry Andric         break;
26940b57cec5SDimitry Andric       }
26950b57cec5SDimitry Andric       case LLVMContext::MD_prof:
26960b57cec5SDimitry Andric         ++NumProfAttachments;
269781ad6265SDimitry Andric         Check(NumProfAttachments == 1,
26980b57cec5SDimitry Andric               "function must have a single !prof attachment", &F, I.second);
26990b57cec5SDimitry Andric         break;
2700*bdd1243dSDimitry Andric       case LLVMContext::MD_kcfi_type:
2701*bdd1243dSDimitry Andric         ++NumKCFIAttachments;
2702*bdd1243dSDimitry Andric         Check(NumKCFIAttachments == 1,
2703*bdd1243dSDimitry Andric               "function must have a single !kcfi_type attachment", &F,
2704*bdd1243dSDimitry Andric               I.second);
2705*bdd1243dSDimitry Andric         break;
27060b57cec5SDimitry Andric       }
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric       // Verify the metadata itself.
27095ffd83dbSDimitry Andric       visitMDNode(*I.second, AllowLocs);
27100b57cec5SDimitry Andric     }
27110b57cec5SDimitry Andric   }
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
27140b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
27150b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
27160b57cec5SDimitry Andric   // uses.
2717fe6060f1SDimitry Andric   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
27180b57cec5SDimitry Andric     const User *U;
2719349cc55cSDimitry Andric     if (F.hasAddressTaken(&U, false, true, false,
2720349cc55cSDimitry Andric                           /*IgnoreARCAttachedCall=*/true))
272181ad6265SDimitry Andric       Check(false, "Invalid user of intrinsic instruction!", U);
27220b57cec5SDimitry Andric   }
27230b57cec5SDimitry Andric 
2724fe6060f1SDimitry Andric   // Check intrinsics' signatures.
2725fe6060f1SDimitry Andric   switch (F.getIntrinsicID()) {
2726fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_base: {
2727fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
272881ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
272981ad6265SDimitry Andric     Check(isa<PointerType>(F.getReturnType()),
2730fe6060f1SDimitry Andric           "gc.get.pointer.base must return a pointer", F);
273181ad6265SDimitry Andric     Check(FT->getParamType(0) == F.getReturnType(),
273281ad6265SDimitry Andric           "gc.get.pointer.base operand and result must be of the same type", F);
2733fe6060f1SDimitry Andric     break;
2734fe6060f1SDimitry Andric   }
2735fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_offset: {
2736fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
273781ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
273881ad6265SDimitry Andric     Check(isa<PointerType>(FT->getParamType(0)),
2739fe6060f1SDimitry Andric           "gc.get.pointer.offset operand must be a pointer", F);
274081ad6265SDimitry Andric     Check(F.getReturnType()->isIntegerTy(),
2741fe6060f1SDimitry Andric           "gc.get.pointer.offset must return integer", F);
2742fe6060f1SDimitry Andric     break;
2743fe6060f1SDimitry Andric   }
2744fe6060f1SDimitry Andric   }
2745fe6060f1SDimitry Andric 
27460b57cec5SDimitry Andric   auto *N = F.getSubprogram();
27470b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
27480b57cec5SDimitry Andric   if (!HasDebugInfo)
27490b57cec5SDimitry Andric     return;
27500b57cec5SDimitry Andric 
27515ffd83dbSDimitry Andric   // Check that all !dbg attachments lead to back to N.
27520b57cec5SDimitry Andric   //
27530b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
27540b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
27550b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
27560b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
27570b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
27580b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
27590b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
27600b57cec5SDimitry Andric     if (!DL)
27610b57cec5SDimitry Andric       return;
27620b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
27630b57cec5SDimitry Andric       return;
27640b57cec5SDimitry Andric 
27650b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
276681ad6265SDimitry Andric     CheckDI(Parent && isa<DILocalScope>(Parent),
276781ad6265SDimitry Andric             "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
27685ffd83dbSDimitry Andric 
27690b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
277081ad6265SDimitry Andric     Check(Scope, "Failed to find DILocalScope", DL);
27715ffd83dbSDimitry Andric 
27725ffd83dbSDimitry Andric     if (!Seen.insert(Scope).second)
27730b57cec5SDimitry Andric       return;
27740b57cec5SDimitry Andric 
27755ffd83dbSDimitry Andric     DISubprogram *SP = Scope->getSubprogram();
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
27780b57cec5SDimitry Andric     // validation in that case
27790b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
27800b57cec5SDimitry Andric       return;
27810b57cec5SDimitry Andric 
278281ad6265SDimitry Andric     CheckDI(SP->describes(&F),
27830b57cec5SDimitry Andric             "!dbg attachment points at wrong subprogram for function", N, &F,
27840b57cec5SDimitry Andric             &I, DL, Scope, SP);
27850b57cec5SDimitry Andric   };
27860b57cec5SDimitry Andric   for (auto &BB : F)
27870b57cec5SDimitry Andric     for (auto &I : BB) {
27880b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
27890b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
27900b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
27910b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
27920b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
27930b57cec5SDimitry Andric       if (BrokenDebugInfo)
27940b57cec5SDimitry Andric         return;
27950b57cec5SDimitry Andric     }
27960b57cec5SDimitry Andric }
27970b57cec5SDimitry Andric 
27980b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
27990b57cec5SDimitry Andric //
28000b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
28010b57cec5SDimitry Andric   InstsInThisBlock.clear();
28020b57cec5SDimitry Andric 
28030b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
280481ad6265SDimitry Andric   Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
28050b57cec5SDimitry Andric 
28060b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
28070b57cec5SDimitry Andric   // it.
28080b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
2809e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
28100b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
28110b57cec5SDimitry Andric     llvm::sort(Preds);
28120b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
281381ad6265SDimitry Andric       Check(PN.getNumIncomingValues() == Preds.size(),
28140b57cec5SDimitry Andric             "PHINode should have one entry for each predecessor of its "
28150b57cec5SDimitry Andric             "parent basic block!",
28160b57cec5SDimitry Andric             &PN);
28170b57cec5SDimitry Andric 
28180b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
28190b57cec5SDimitry Andric       Values.clear();
28200b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
28210b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
28220b57cec5SDimitry Andric         Values.push_back(
28230b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
28240b57cec5SDimitry Andric       llvm::sort(Values);
28250b57cec5SDimitry Andric 
28260b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
28270b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
28280b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
28290b57cec5SDimitry Andric         // all identical.
28300b57cec5SDimitry Andric         //
283181ad6265SDimitry Andric         Check(i == 0 || Values[i].first != Values[i - 1].first ||
28320b57cec5SDimitry Andric                   Values[i].second == Values[i - 1].second,
28330b57cec5SDimitry Andric               "PHI node has multiple entries for the same basic block with "
28340b57cec5SDimitry Andric               "different incoming values!",
28350b57cec5SDimitry Andric               &PN, Values[i].first, Values[i].second, Values[i - 1].second);
28360b57cec5SDimitry Andric 
28370b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
28380b57cec5SDimitry Andric         // matched up.
283981ad6265SDimitry Andric         Check(Values[i].first == Preds[i],
28400b57cec5SDimitry Andric               "PHI node entries do not match predecessors!", &PN,
28410b57cec5SDimitry Andric               Values[i].first, Preds[i]);
28420b57cec5SDimitry Andric       }
28430b57cec5SDimitry Andric     }
28440b57cec5SDimitry Andric   }
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
28470b57cec5SDimitry Andric   for (auto &I : BB)
28480b57cec5SDimitry Andric   {
284981ad6265SDimitry Andric     Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
28500b57cec5SDimitry Andric   }
28510b57cec5SDimitry Andric }
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
28540b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
285581ad6265SDimitry Andric   Check(&I == I.getParent()->getTerminator(),
28560b57cec5SDimitry Andric         "Terminator found in the middle of a basic block!", I.getParent());
28570b57cec5SDimitry Andric   visitInstruction(I);
28580b57cec5SDimitry Andric }
28590b57cec5SDimitry Andric 
28600b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
28610b57cec5SDimitry Andric   if (BI.isConditional()) {
286281ad6265SDimitry Andric     Check(BI.getCondition()->getType()->isIntegerTy(1),
28630b57cec5SDimitry Andric           "Branch condition is not 'i1' type!", &BI, BI.getCondition());
28640b57cec5SDimitry Andric   }
28650b57cec5SDimitry Andric   visitTerminator(BI);
28660b57cec5SDimitry Andric }
28670b57cec5SDimitry Andric 
28680b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
28690b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
28700b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
28710b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
287281ad6265SDimitry Andric     Check(N == 0,
28730b57cec5SDimitry Andric           "Found return instr that returns non-void in Function of void "
28740b57cec5SDimitry Andric           "return type!",
28750b57cec5SDimitry Andric           &RI, F->getReturnType());
28760b57cec5SDimitry Andric   else
287781ad6265SDimitry Andric     Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
28780b57cec5SDimitry Andric           "Function return type does not match operand "
28790b57cec5SDimitry Andric           "type of return inst!",
28800b57cec5SDimitry Andric           &RI, F->getReturnType());
28810b57cec5SDimitry Andric 
28820b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
28830b57cec5SDimitry Andric   // terminators...
28840b57cec5SDimitry Andric   visitTerminator(RI);
28850b57cec5SDimitry Andric }
28860b57cec5SDimitry Andric 
28870b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
288881ad6265SDimitry Andric   Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
28890b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
28900b57cec5SDimitry Andric   // have the same type as the switched-on value.
28910b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
28920b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
28930b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
2894*bdd1243dSDimitry Andric     Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
2895*bdd1243dSDimitry Andric           "Case value is not a constant integer.", &SI);
289681ad6265SDimitry Andric     Check(Case.getCaseValue()->getType() == SwitchTy,
28970b57cec5SDimitry Andric           "Switch constants must all be same type as switch value!", &SI);
289881ad6265SDimitry Andric     Check(Constants.insert(Case.getCaseValue()).second,
28990b57cec5SDimitry Andric           "Duplicate integer as switch case", &SI, Case.getCaseValue());
29000b57cec5SDimitry Andric   }
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric   visitTerminator(SI);
29030b57cec5SDimitry Andric }
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
290681ad6265SDimitry Andric   Check(BI.getAddress()->getType()->isPointerTy(),
29070b57cec5SDimitry Andric         "Indirectbr operand must have pointer type!", &BI);
29080b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
290981ad6265SDimitry Andric     Check(BI.getDestination(i)->getType()->isLabelTy(),
29100b57cec5SDimitry Andric           "Indirectbr destinations must all have pointer type!", &BI);
29110b57cec5SDimitry Andric 
29120b57cec5SDimitry Andric   visitTerminator(BI);
29130b57cec5SDimitry Andric }
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
291681ad6265SDimitry Andric   Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
2917fe6060f1SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
291881ad6265SDimitry Andric   Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
29190b57cec5SDimitry Andric 
292004eeddc0SDimitry Andric   verifyInlineAsmCall(CBI);
29210b57cec5SDimitry Andric   visitTerminator(CBI);
29220b57cec5SDimitry Andric }
29230b57cec5SDimitry Andric 
29240b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
292581ad6265SDimitry Andric   Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
29260b57cec5SDimitry Andric                                         SI.getOperand(2)),
29270b57cec5SDimitry Andric         "Invalid operands for select instruction!", &SI);
29280b57cec5SDimitry Andric 
292981ad6265SDimitry Andric   Check(SI.getTrueValue()->getType() == SI.getType(),
29300b57cec5SDimitry Andric         "Select values must have same type as select instruction!", &SI);
29310b57cec5SDimitry Andric   visitInstruction(SI);
29320b57cec5SDimitry Andric }
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
29350b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
29360b57cec5SDimitry Andric ///
29370b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
293881ad6265SDimitry Andric   Check(false, "User-defined operators should not live outside of a pass!", &I);
29390b57cec5SDimitry Andric }
29400b57cec5SDimitry Andric 
29410b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
29420b57cec5SDimitry Andric   // Get the source and destination types
29430b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29440b57cec5SDimitry Andric   Type *DestTy = I.getType();
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
29470b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
29480b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
29490b57cec5SDimitry Andric 
295081ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
295181ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
295281ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
29530b57cec5SDimitry Andric         "trunc source and destination must both be a vector or neither", &I);
295481ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
29550b57cec5SDimitry Andric 
29560b57cec5SDimitry Andric   visitInstruction(I);
29570b57cec5SDimitry Andric }
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
29600b57cec5SDimitry Andric   // Get the source and destination types
29610b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29620b57cec5SDimitry Andric   Type *DestTy = I.getType();
29630b57cec5SDimitry Andric 
29640b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
296581ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
296681ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
296781ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
29680b57cec5SDimitry Andric         "zext source and destination must both be a vector or neither", &I);
29690b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
29700b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
29710b57cec5SDimitry Andric 
297281ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   visitInstruction(I);
29750b57cec5SDimitry Andric }
29760b57cec5SDimitry Andric 
29770b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
29780b57cec5SDimitry Andric   // Get the source and destination types
29790b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29800b57cec5SDimitry Andric   Type *DestTy = I.getType();
29810b57cec5SDimitry Andric 
29820b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
29830b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
29840b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
29850b57cec5SDimitry Andric 
298681ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
298781ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
298881ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
29890b57cec5SDimitry Andric         "sext source and destination must both be a vector or neither", &I);
299081ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
29910b57cec5SDimitry Andric 
29920b57cec5SDimitry Andric   visitInstruction(I);
29930b57cec5SDimitry Andric }
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
29960b57cec5SDimitry Andric   // Get the source and destination types
29970b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
29980b57cec5SDimitry Andric   Type *DestTy = I.getType();
29990b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
30000b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30010b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
30020b57cec5SDimitry Andric 
300381ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
300481ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
300581ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
30060b57cec5SDimitry Andric         "fptrunc source and destination must both be a vector or neither", &I);
300781ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
30080b57cec5SDimitry Andric 
30090b57cec5SDimitry Andric   visitInstruction(I);
30100b57cec5SDimitry Andric }
30110b57cec5SDimitry Andric 
30120b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
30130b57cec5SDimitry Andric   // Get the source and destination types
30140b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30150b57cec5SDimitry Andric   Type *DestTy = I.getType();
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
30180b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30190b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
30200b57cec5SDimitry Andric 
302181ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
302281ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
302381ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
30240b57cec5SDimitry Andric         "fpext source and destination must both be a vector or neither", &I);
302581ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric   visitInstruction(I);
30280b57cec5SDimitry Andric }
30290b57cec5SDimitry Andric 
30300b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
30310b57cec5SDimitry Andric   // Get the source and destination types
30320b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30330b57cec5SDimitry Andric   Type *DestTy = I.getType();
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
30360b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
30370b57cec5SDimitry Andric 
303881ad6265SDimitry Andric   Check(SrcVec == DstVec,
30390b57cec5SDimitry Andric         "UIToFP source and dest must both be vector or scalar", &I);
304081ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
30410b57cec5SDimitry Andric         "UIToFP source must be integer or integer vector", &I);
304281ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
30430b57cec5SDimitry Andric         &I);
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   if (SrcVec && DstVec)
304681ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
30475ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
30480b57cec5SDimitry Andric           "UIToFP source and dest vector length mismatch", &I);
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric   visitInstruction(I);
30510b57cec5SDimitry Andric }
30520b57cec5SDimitry Andric 
30530b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
30540b57cec5SDimitry Andric   // Get the source and destination types
30550b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30560b57cec5SDimitry Andric   Type *DestTy = I.getType();
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
30590b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
30600b57cec5SDimitry Andric 
306181ad6265SDimitry Andric   Check(SrcVec == DstVec,
30620b57cec5SDimitry Andric         "SIToFP source and dest must both be vector or scalar", &I);
306381ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
30640b57cec5SDimitry Andric         "SIToFP source must be integer or integer vector", &I);
306581ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
30660b57cec5SDimitry Andric         &I);
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   if (SrcVec && DstVec)
306981ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
30705ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
30710b57cec5SDimitry Andric           "SIToFP source and dest vector length mismatch", &I);
30720b57cec5SDimitry Andric 
30730b57cec5SDimitry Andric   visitInstruction(I);
30740b57cec5SDimitry Andric }
30750b57cec5SDimitry Andric 
30760b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
30770b57cec5SDimitry Andric   // Get the source and destination types
30780b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30790b57cec5SDimitry Andric   Type *DestTy = I.getType();
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
30820b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
30830b57cec5SDimitry Andric 
308481ad6265SDimitry Andric   Check(SrcVec == DstVec,
30850b57cec5SDimitry Andric         "FPToUI source and dest must both be vector or scalar", &I);
308681ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
308781ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
30880b57cec5SDimitry Andric         "FPToUI result must be integer or integer vector", &I);
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric   if (SrcVec && DstVec)
309181ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
30925ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
30930b57cec5SDimitry Andric           "FPToUI source and dest vector length mismatch", &I);
30940b57cec5SDimitry Andric 
30950b57cec5SDimitry Andric   visitInstruction(I);
30960b57cec5SDimitry Andric }
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &I) {
30990b57cec5SDimitry Andric   // Get the source and destination types
31000b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31010b57cec5SDimitry Andric   Type *DestTy = I.getType();
31020b57cec5SDimitry Andric 
31030b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31040b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31050b57cec5SDimitry Andric 
310681ad6265SDimitry Andric   Check(SrcVec == DstVec,
31070b57cec5SDimitry Andric         "FPToSI source and dest must both be vector or scalar", &I);
310881ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
310981ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
31100b57cec5SDimitry Andric         "FPToSI result must be integer or integer vector", &I);
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric   if (SrcVec && DstVec)
311381ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
31145ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
31150b57cec5SDimitry Andric           "FPToSI source and dest vector length mismatch", &I);
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   visitInstruction(I);
31180b57cec5SDimitry Andric }
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
31210b57cec5SDimitry Andric   // Get the source and destination types
31220b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31230b57cec5SDimitry Andric   Type *DestTy = I.getType();
31240b57cec5SDimitry Andric 
312581ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
31260b57cec5SDimitry Andric 
312781ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
312881ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
31290b57cec5SDimitry Andric         &I);
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
31325ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
31335ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
313481ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
31350b57cec5SDimitry Andric           "PtrToInt Vector width mismatch", &I);
31360b57cec5SDimitry Andric   }
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric   visitInstruction(I);
31390b57cec5SDimitry Andric }
31400b57cec5SDimitry Andric 
31410b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
31420b57cec5SDimitry Andric   // Get the source and destination types
31430b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31440b57cec5SDimitry Andric   Type *DestTy = I.getType();
31450b57cec5SDimitry Andric 
314681ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
314781ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
31480b57cec5SDimitry Andric 
314981ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
31500b57cec5SDimitry Andric         &I);
31510b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
31525ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
31535ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
315481ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
31550b57cec5SDimitry Andric           "IntToPtr Vector width mismatch", &I);
31560b57cec5SDimitry Andric   }
31570b57cec5SDimitry Andric   visitInstruction(I);
31580b57cec5SDimitry Andric }
31590b57cec5SDimitry Andric 
31600b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
316181ad6265SDimitry Andric   Check(
31620b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
31630b57cec5SDimitry Andric       "Invalid bitcast", &I);
31640b57cec5SDimitry Andric   visitInstruction(I);
31650b57cec5SDimitry Andric }
31660b57cec5SDimitry Andric 
31670b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
31680b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31690b57cec5SDimitry Andric   Type *DestTy = I.getType();
31700b57cec5SDimitry Andric 
317181ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
31720b57cec5SDimitry Andric         &I);
317381ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
31740b57cec5SDimitry Andric         &I);
317581ad6265SDimitry Andric   Check(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
31760b57cec5SDimitry Andric         "AddrSpaceCast must be between different address spaces", &I);
31775ffd83dbSDimitry Andric   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
317881ad6265SDimitry Andric     Check(SrcVTy->getElementCount() ==
3179e8d8bef9SDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
31800b57cec5SDimitry Andric           "AddrSpaceCast vector pointer number of elements mismatch", &I);
31810b57cec5SDimitry Andric   visitInstruction(I);
31820b57cec5SDimitry Andric }
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
31850b57cec5SDimitry Andric ///
31860b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
31870b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
31880b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
31890b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
31900b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
319181ad6265SDimitry Andric   Check(&PN == &PN.getParent()->front() ||
31920b57cec5SDimitry Andric             isa<PHINode>(--BasicBlock::iterator(&PN)),
31930b57cec5SDimitry Andric         "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
319681ad6265SDimitry Andric   Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
31990b57cec5SDimitry Andric   // result, and that the incoming blocks are really basic blocks.
32000b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
320181ad6265SDimitry Andric     Check(PN.getType() == IncValue->getType(),
32020b57cec5SDimitry Andric           "PHI node operands are not the same type as the result!", &PN);
32030b57cec5SDimitry Andric   }
32040b57cec5SDimitry Andric 
32050b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric   visitInstruction(PN);
32080b57cec5SDimitry Andric }
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
321181ad6265SDimitry Andric   Check(Call.getCalledOperand()->getType()->isPointerTy(),
32120b57cec5SDimitry Andric         "Called function must be a pointer!", Call);
32135ffd83dbSDimitry Andric   PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType());
32140b57cec5SDimitry Andric 
321581ad6265SDimitry Andric   Check(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()),
32160b57cec5SDimitry Andric         "Called function is not the same type as the call!", Call);
32170b57cec5SDimitry Andric 
32180b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
32190b57cec5SDimitry Andric 
32200b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
32210b57cec5SDimitry Andric   if (FTy->isVarArg())
322281ad6265SDimitry Andric     Check(Call.arg_size() >= FTy->getNumParams(),
322381ad6265SDimitry Andric           "Called function requires more parameters than were provided!", Call);
32240b57cec5SDimitry Andric   else
322581ad6265SDimitry Andric     Check(Call.arg_size() == FTy->getNumParams(),
32260b57cec5SDimitry Andric           "Incorrect number of arguments passed to called function!", Call);
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
32290b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
323081ad6265SDimitry Andric     Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
32310b57cec5SDimitry Andric           "Call parameter type does not match function signature!",
32320b57cec5SDimitry Andric           Call.getArgOperand(i), FTy->getParamType(i), Call);
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
32350b57cec5SDimitry Andric 
323681ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, Call.arg_size()),
32370b57cec5SDimitry Andric         "Attribute after last parameter!", Call);
32380b57cec5SDimitry Andric 
3239*bdd1243dSDimitry Andric   Function *Callee =
3240*bdd1243dSDimitry Andric       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3241*bdd1243dSDimitry Andric   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3242*bdd1243dSDimitry Andric   if (IsIntrinsic)
3243*bdd1243dSDimitry Andric     Check(Callee->getValueType() == FTy,
3244*bdd1243dSDimitry Andric           "Intrinsic called with incompatible signature", Call);
3245*bdd1243dSDimitry Andric 
324681ad6265SDimitry Andric   auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
324781ad6265SDimitry Andric     if (!Ty->isSized())
324881ad6265SDimitry Andric       return;
324981ad6265SDimitry Andric     Align ABIAlign = DL.getABITypeAlign(Ty);
325081ad6265SDimitry Andric     Align MaxAlign(ParamMaxAlignment);
325181ad6265SDimitry Andric     Check(ABIAlign <= MaxAlign,
325281ad6265SDimitry Andric           "Incorrect alignment of " + Message + " to called function!", Call);
325381ad6265SDimitry Andric   };
325481ad6265SDimitry Andric 
3255*bdd1243dSDimitry Andric   if (!IsIntrinsic) {
325681ad6265SDimitry Andric     VerifyTypeAlign(FTy->getReturnType(), "return type");
325781ad6265SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
325881ad6265SDimitry Andric       Type *Ty = FTy->getParamType(i);
325981ad6265SDimitry Andric       VerifyTypeAlign(Ty, "argument passed");
326081ad6265SDimitry Andric     }
3261*bdd1243dSDimitry Andric   }
32620b57cec5SDimitry Andric 
3263349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
32640b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
32650b57cec5SDimitry Andric     // declaration is also speculatable.
326681ad6265SDimitry Andric     Check(Callee && Callee->isSpeculatable(),
32670b57cec5SDimitry Andric           "speculatable attribute may not apply to call sites", Call);
32680b57cec5SDimitry Andric   }
32690b57cec5SDimitry Andric 
3270349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
327181ad6265SDimitry Andric     Check(Call.getCalledFunction()->getIntrinsicID() ==
32725ffd83dbSDimitry Andric               Intrinsic::call_preallocated_arg,
32735ffd83dbSDimitry Andric           "preallocated as a call site attribute can only be on "
32745ffd83dbSDimitry Andric           "llvm.call.preallocated.arg");
32755ffd83dbSDimitry Andric   }
32765ffd83dbSDimitry Andric 
32770b57cec5SDimitry Andric   // Verify call attributes.
327804eeddc0SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
32790b57cec5SDimitry Andric 
32800b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
32810b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
32820b57cec5SDimitry Andric   // inalloca.
32830b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
32840b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
32850b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
328681ad6265SDimitry Andric       Check(AI->isUsedWithInAlloca(),
32870b57cec5SDimitry Andric             "inalloca argument for call has mismatched alloca", AI, Call);
32880b57cec5SDimitry Andric   }
32890b57cec5SDimitry Andric 
32900b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
32910b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
32920b57cec5SDimitry Andric   // well.
32930b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
32940b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
32950b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
32960b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
329781ad6265SDimitry Andric         Check(AI->isSwiftError(),
32980b57cec5SDimitry Andric               "swifterror argument for call has mismatched alloca", AI, Call);
32990b57cec5SDimitry Andric         continue;
33000b57cec5SDimitry Andric       }
33010b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
330281ad6265SDimitry Andric       Check(ArgI, "swifterror argument should come from an alloca or parameter",
33030b57cec5SDimitry Andric             SwiftErrorArg, Call);
330481ad6265SDimitry Andric       Check(ArgI->hasSwiftErrorAttr(),
33050b57cec5SDimitry Andric             "swifterror argument for call has mismatched parameter", ArgI,
33060b57cec5SDimitry Andric             Call);
33070b57cec5SDimitry Andric     }
33080b57cec5SDimitry Andric 
3309349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
33100b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
33110b57cec5SDimitry Andric       // also has the matching immarg.
331281ad6265SDimitry Andric       Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
331381ad6265SDimitry Andric             "immarg may not apply only to call sites", Call.getArgOperand(i),
331481ad6265SDimitry Andric             Call);
33150b57cec5SDimitry Andric     }
33160b57cec5SDimitry Andric 
33170b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
33180b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
331981ad6265SDimitry Andric       Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
33200b57cec5SDimitry Andric             "immarg operand has non-immediate parameter", ArgVal, Call);
33210b57cec5SDimitry Andric     }
33225ffd83dbSDimitry Andric 
33235ffd83dbSDimitry Andric     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
33245ffd83dbSDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
33255ffd83dbSDimitry Andric       bool hasOB =
33265ffd83dbSDimitry Andric           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
33275ffd83dbSDimitry Andric       bool isMustTail = Call.isMustTailCall();
332881ad6265SDimitry Andric       Check(hasOB != isMustTail,
33295ffd83dbSDimitry Andric             "preallocated operand either requires a preallocated bundle or "
33305ffd83dbSDimitry Andric             "the call to be musttail (but not both)",
33315ffd83dbSDimitry Andric             ArgVal, Call);
33325ffd83dbSDimitry Andric     }
33330b57cec5SDimitry Andric   }
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric   if (FTy->isVarArg()) {
33360b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
33370b57cec5SDimitry Andric     bool SawNest = false;
33380b57cec5SDimitry Andric     bool SawReturned = false;
33390b57cec5SDimitry Andric 
33400b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3341349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
33420b57cec5SDimitry Andric         SawNest = true;
3343349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
33440b57cec5SDimitry Andric         SawReturned = true;
33450b57cec5SDimitry Andric     }
33460b57cec5SDimitry Andric 
33470b57cec5SDimitry Andric     // Check attributes on the varargs part.
33480b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
33490b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
3350349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
33510b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
33520b57cec5SDimitry Andric 
33530b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
335481ad6265SDimitry Andric         Check(!SawNest, "More than one parameter has attribute nest!", Call);
33550b57cec5SDimitry Andric         SawNest = true;
33560b57cec5SDimitry Andric       }
33570b57cec5SDimitry Andric 
33580b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
335981ad6265SDimitry Andric         Check(!SawReturned, "More than one parameter has attribute returned!",
33600b57cec5SDimitry Andric               Call);
336181ad6265SDimitry Andric         Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
33620b57cec5SDimitry Andric               "Incompatible argument and return types for 'returned' "
33630b57cec5SDimitry Andric               "attribute",
33640b57cec5SDimitry Andric               Call);
33650b57cec5SDimitry Andric         SawReturned = true;
33660b57cec5SDimitry Andric       }
33670b57cec5SDimitry Andric 
33680b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
33690b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
33700b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
33710b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
33720b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
337381ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
33740b57cec5SDimitry Andric               "Attribute 'sret' cannot be used for vararg call arguments!",
33750b57cec5SDimitry Andric               Call);
33760b57cec5SDimitry Andric 
33770b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
337881ad6265SDimitry Andric         Check(Idx == Call.arg_size() - 1,
33790b57cec5SDimitry Andric               "inalloca isn't on the last argument!", Call);
33800b57cec5SDimitry Andric     }
33810b57cec5SDimitry Andric   }
33820b57cec5SDimitry Andric 
33830b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
33840b57cec5SDimitry Andric   if (!IsIntrinsic) {
33850b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
338681ad6265SDimitry Andric       Check(!ParamTy->isMetadataTy(),
33870b57cec5SDimitry Andric             "Function has metadata parameter but isn't an intrinsic", Call);
338881ad6265SDimitry Andric       Check(!ParamTy->isTokenTy(),
33890b57cec5SDimitry Andric             "Function has token parameter but isn't an intrinsic", Call);
33900b57cec5SDimitry Andric     }
33910b57cec5SDimitry Andric   }
33920b57cec5SDimitry Andric 
33930b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
3394fe6060f1SDimitry Andric   if (!Call.getCalledFunction()) {
339581ad6265SDimitry Andric     Check(!FTy->getReturnType()->isTokenTy(),
33960b57cec5SDimitry Andric           "Return type cannot be token for indirect call!");
339781ad6265SDimitry Andric     Check(!FTy->getReturnType()->isX86_AMXTy(),
3398fe6060f1SDimitry Andric           "Return type cannot be x86_amx for indirect call!");
3399fe6060f1SDimitry Andric   }
34000b57cec5SDimitry Andric 
34010b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
34020b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
34030b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
34040b57cec5SDimitry Andric 
3405480093f4SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet", at
340681ad6265SDimitry Andric   // most one "gc-transition", at most one "cfguardtarget", at most one
340781ad6265SDimitry Andric   // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
34080b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
34095ffd83dbSDimitry Andric        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3410fe6060f1SDimitry Andric        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3411*bdd1243dSDimitry Andric        FoundPtrauthBundle = false, FoundKCFIBundle = false,
3412fe6060f1SDimitry Andric        FoundAttachedCallBundle = false;
34130b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
34140b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
34150b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
34160b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
341781ad6265SDimitry Andric       Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
34180b57cec5SDimitry Andric       FoundDeoptBundle = true;
34190b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
342081ad6265SDimitry Andric       Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
34210b57cec5SDimitry Andric             Call);
34220b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
34230b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
342481ad6265SDimitry Andric       Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
34250b57cec5SDimitry Andric       FoundFuncletBundle = true;
342681ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
34270b57cec5SDimitry Andric             "Expected exactly one funclet bundle operand", Call);
342881ad6265SDimitry Andric       Check(isa<FuncletPadInst>(BU.Inputs.front()),
34290b57cec5SDimitry Andric             "Funclet bundle operands should correspond to a FuncletPadInst",
34300b57cec5SDimitry Andric             Call);
3431480093f4SDimitry Andric     } else if (Tag == LLVMContext::OB_cfguardtarget) {
343281ad6265SDimitry Andric       Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
343381ad6265SDimitry Andric             Call);
3434480093f4SDimitry Andric       FoundCFGuardTargetBundle = true;
343581ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
3436480093f4SDimitry Andric             "Expected exactly one cfguardtarget bundle operand", Call);
343781ad6265SDimitry Andric     } else if (Tag == LLVMContext::OB_ptrauth) {
343881ad6265SDimitry Andric       Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
343981ad6265SDimitry Andric       FoundPtrauthBundle = true;
344081ad6265SDimitry Andric       Check(BU.Inputs.size() == 2,
344181ad6265SDimitry Andric             "Expected exactly two ptrauth bundle operands", Call);
344281ad6265SDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
344381ad6265SDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
344481ad6265SDimitry Andric             "Ptrauth bundle key operand must be an i32 constant", Call);
344581ad6265SDimitry Andric       Check(BU.Inputs[1]->getType()->isIntegerTy(64),
344681ad6265SDimitry Andric             "Ptrauth bundle discriminator operand must be an i64", Call);
3447*bdd1243dSDimitry Andric     } else if (Tag == LLVMContext::OB_kcfi) {
3448*bdd1243dSDimitry Andric       Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
3449*bdd1243dSDimitry Andric       FoundKCFIBundle = true;
3450*bdd1243dSDimitry Andric       Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
3451*bdd1243dSDimitry Andric             Call);
3452*bdd1243dSDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
3453*bdd1243dSDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
3454*bdd1243dSDimitry Andric             "Kcfi bundle operand must be an i32 constant", Call);
34555ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_preallocated) {
345681ad6265SDimitry Andric       Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
34575ffd83dbSDimitry Andric             Call);
34585ffd83dbSDimitry Andric       FoundPreallocatedBundle = true;
345981ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
34605ffd83dbSDimitry Andric             "Expected exactly one preallocated bundle operand", Call);
34615ffd83dbSDimitry Andric       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
346281ad6265SDimitry Andric       Check(Input &&
34635ffd83dbSDimitry Andric                 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
34645ffd83dbSDimitry Andric             "\"preallocated\" argument must be a token from "
34655ffd83dbSDimitry Andric             "llvm.call.preallocated.setup",
34665ffd83dbSDimitry Andric             Call);
34675ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_gc_live) {
346881ad6265SDimitry Andric       Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
34695ffd83dbSDimitry Andric       FoundGCLiveBundle = true;
3470fe6060f1SDimitry Andric     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
347181ad6265SDimitry Andric       Check(!FoundAttachedCallBundle,
3472fe6060f1SDimitry Andric             "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3473fe6060f1SDimitry Andric       FoundAttachedCallBundle = true;
3474349cc55cSDimitry Andric       verifyAttachedCallBundle(Call, BU);
34750b57cec5SDimitry Andric     }
34760b57cec5SDimitry Andric   }
34770b57cec5SDimitry Andric 
347881ad6265SDimitry Andric   // Verify that callee and callsite agree on whether to use pointer auth.
347981ad6265SDimitry Andric   Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
348081ad6265SDimitry Andric         "Direct call cannot have a ptrauth bundle", Call);
348181ad6265SDimitry Andric 
34820b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
34830b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
3484*bdd1243dSDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info
3485*bdd1243dSDimitry Andric   // (Interposable functions are not inlinable, neither are functions without
3486*bdd1243dSDimitry Andric   //  definitions.)
34870b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3488*bdd1243dSDimitry Andric       !Call.getCalledFunction()->isInterposable() &&
3489*bdd1243dSDimitry Andric       !Call.getCalledFunction()->isDeclaration() &&
34900b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
349181ad6265SDimitry Andric     CheckDI(Call.getDebugLoc(),
34920b57cec5SDimitry Andric             "inlinable function call in a function with "
34930b57cec5SDimitry Andric             "debug info must have a !dbg location",
34940b57cec5SDimitry Andric             Call);
34950b57cec5SDimitry Andric 
349604eeddc0SDimitry Andric   if (Call.isInlineAsm())
349704eeddc0SDimitry Andric     verifyInlineAsmCall(Call);
349804eeddc0SDimitry Andric 
34990b57cec5SDimitry Andric   visitInstruction(Call);
35000b57cec5SDimitry Andric }
35010b57cec5SDimitry Andric 
35020eae32dcSDimitry Andric void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3503fe6060f1SDimitry Andric                                          StringRef Context) {
350481ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InAlloca),
3505fe6060f1SDimitry Andric         Twine("inalloca attribute not allowed in ") + Context);
350681ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InReg),
3507fe6060f1SDimitry Andric         Twine("inreg attribute not allowed in ") + Context);
350881ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::SwiftError),
3509fe6060f1SDimitry Andric         Twine("swifterror attribute not allowed in ") + Context);
351081ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::Preallocated),
3511fe6060f1SDimitry Andric         Twine("preallocated attribute not allowed in ") + Context);
351281ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::ByRef),
3513fe6060f1SDimitry Andric         Twine("byref attribute not allowed in ") + Context);
3514fe6060f1SDimitry Andric }
3515fe6060f1SDimitry Andric 
35160b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
35170b57cec5SDimitry Andric /// types with different pointee types and the same address space.
35180b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
35190b57cec5SDimitry Andric   if (L == R)
35200b57cec5SDimitry Andric     return true;
35210b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
35220b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
35230b57cec5SDimitry Andric   if (!PL || !PR)
35240b57cec5SDimitry Andric     return false;
35250b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
35260b57cec5SDimitry Andric }
35270b57cec5SDimitry Andric 
352804eeddc0SDimitry Andric static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
35290b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
35300b57cec5SDimitry Andric       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3531fe6060f1SDimitry Andric       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3532fe6060f1SDimitry Andric       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3533fe6060f1SDimitry Andric       Attribute::ByRef};
353404eeddc0SDimitry Andric   AttrBuilder Copy(C);
35350b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
3536349cc55cSDimitry Andric     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3537fe6060f1SDimitry Andric     if (Attr.isValid())
3538fe6060f1SDimitry Andric       Copy.addAttribute(Attr);
35390b57cec5SDimitry Andric   }
3540e8d8bef9SDimitry Andric 
3541e8d8bef9SDimitry Andric   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3542349cc55cSDimitry Andric   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3543349cc55cSDimitry Andric       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3544349cc55cSDimitry Andric        Attrs.hasParamAttr(I, Attribute::ByRef)))
35450b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
35460b57cec5SDimitry Andric   return Copy;
35470b57cec5SDimitry Andric }
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
355081ad6265SDimitry Andric   Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
35510b57cec5SDimitry Andric 
35520b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
35530b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
35540b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
355581ad6265SDimitry Andric   Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
35560b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched varargs", &CI);
355781ad6265SDimitry Andric   Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
35580b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched return types", &CI);
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
356181ad6265SDimitry Andric   Check(F->getCallingConv() == CI.getCallingConv(),
35620b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched calling conv", &CI);
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
35650b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
35660b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
35670b57cec5SDimitry Andric   //   produced by the call or void.
35680b57cec5SDimitry Andric   Value *RetVal = &CI;
35690b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
35700b57cec5SDimitry Andric 
35710b57cec5SDimitry Andric   // Handle the optional bitcast.
35720b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
357381ad6265SDimitry Andric     Check(BI->getOperand(0) == RetVal,
35740b57cec5SDimitry Andric           "bitcast following musttail call must use the call", BI);
35750b57cec5SDimitry Andric     RetVal = BI;
35760b57cec5SDimitry Andric     Next = BI->getNextNode();
35770b57cec5SDimitry Andric   }
35780b57cec5SDimitry Andric 
35790b57cec5SDimitry Andric   // Check the return.
35800b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
358181ad6265SDimitry Andric   Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
358281ad6265SDimitry Andric   Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3583fe6060f1SDimitry Andric             isa<UndefValue>(Ret->getReturnValue()),
35840b57cec5SDimitry Andric         "musttail call result must be returned", Ret);
3585fe6060f1SDimitry Andric 
3586fe6060f1SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
3587fe6060f1SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
3588fe6060f1SDimitry Andric   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3589fe6060f1SDimitry Andric       CI.getCallingConv() == CallingConv::Tail) {
3590fe6060f1SDimitry Andric     StringRef CCName =
3591fe6060f1SDimitry Andric         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3592fe6060f1SDimitry Andric 
3593fe6060f1SDimitry Andric     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3594fe6060f1SDimitry Andric     //   are allowed in swifttailcc call
3595349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
359604eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3597fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3598fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3599fe6060f1SDimitry Andric     }
3600349cc55cSDimitry Andric     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
360104eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3602fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3603fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3604fe6060f1SDimitry Andric     }
3605fe6060f1SDimitry Andric     // - Varargs functions are not allowed
360681ad6265SDimitry Andric     Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3607fe6060f1SDimitry Andric                                      " tail call for varargs function");
3608fe6060f1SDimitry Andric     return;
3609fe6060f1SDimitry Andric   }
3610fe6060f1SDimitry Andric 
3611fe6060f1SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
3612fe6060f1SDimitry Andric   //   parameters or return types may differ in pointee type, but not
3613fe6060f1SDimitry Andric   //   address space.
3614fe6060f1SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
361581ad6265SDimitry Andric     Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
361681ad6265SDimitry Andric           "cannot guarantee tail call due to mismatched parameter counts", &CI);
3617349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
361881ad6265SDimitry Andric       Check(
3619fe6060f1SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3620fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
3621fe6060f1SDimitry Andric     }
3622fe6060f1SDimitry Andric   }
3623fe6060f1SDimitry Andric 
3624fe6060f1SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3625fe6060f1SDimitry Andric   //   returned, preallocated, and inalloca, must match.
3626349cc55cSDimitry Andric   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
362704eeddc0SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
362804eeddc0SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
362981ad6265SDimitry Andric     Check(CallerABIAttrs == CalleeABIAttrs,
3630fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched ABI impacting "
3631fe6060f1SDimitry Andric           "function attributes",
3632fe6060f1SDimitry Andric           &CI, CI.getOperand(I));
3633fe6060f1SDimitry Andric   }
36340b57cec5SDimitry Andric }
36350b57cec5SDimitry Andric 
36360b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
36370b57cec5SDimitry Andric   visitCallBase(CI);
36380b57cec5SDimitry Andric 
36390b57cec5SDimitry Andric   if (CI.isMustTailCall())
36400b57cec5SDimitry Andric     verifyMustTailCall(CI);
36410b57cec5SDimitry Andric }
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
36440b57cec5SDimitry Andric   visitCallBase(II);
36450b57cec5SDimitry Andric 
36460b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
36470b57cec5SDimitry Andric   // exception handling instruction.
364881ad6265SDimitry Andric   Check(
36490b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
36500b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
36510b57cec5SDimitry Andric       &II);
36520b57cec5SDimitry Andric 
36530b57cec5SDimitry Andric   visitTerminator(II);
36540b57cec5SDimitry Andric }
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
36570b57cec5SDimitry Andric ///
36580b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
365981ad6265SDimitry Andric   Check(U.getType() == U.getOperand(0)->getType(),
36600b57cec5SDimitry Andric         "Unary operators must have same type for"
36610b57cec5SDimitry Andric         "operands and result!",
36620b57cec5SDimitry Andric         &U);
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric   switch (U.getOpcode()) {
36650b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
36660b57cec5SDimitry Andric   // floating-point operands.
36670b57cec5SDimitry Andric   case Instruction::FNeg:
366881ad6265SDimitry Andric     Check(U.getType()->isFPOrFPVectorTy(),
36690b57cec5SDimitry Andric           "FNeg operator only works with float types!", &U);
36700b57cec5SDimitry Andric     break;
36710b57cec5SDimitry Andric   default:
36720b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
36730b57cec5SDimitry Andric   }
36740b57cec5SDimitry Andric 
36750b57cec5SDimitry Andric   visitInstruction(U);
36760b57cec5SDimitry Andric }
36770b57cec5SDimitry Andric 
36780b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
36790b57cec5SDimitry Andric /// of the same type!
36800b57cec5SDimitry Andric ///
36810b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
368281ad6265SDimitry Andric   Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
36830b57cec5SDimitry Andric         "Both operands to a binary operator are not of the same type!", &B);
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric   switch (B.getOpcode()) {
36860b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
36870b57cec5SDimitry Andric   // integral operands.
36880b57cec5SDimitry Andric   case Instruction::Add:
36890b57cec5SDimitry Andric   case Instruction::Sub:
36900b57cec5SDimitry Andric   case Instruction::Mul:
36910b57cec5SDimitry Andric   case Instruction::SDiv:
36920b57cec5SDimitry Andric   case Instruction::UDiv:
36930b57cec5SDimitry Andric   case Instruction::SRem:
36940b57cec5SDimitry Andric   case Instruction::URem:
369581ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
36960b57cec5SDimitry Andric           "Integer arithmetic operators only work with integral types!", &B);
369781ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
36980b57cec5SDimitry Andric           "Integer arithmetic operators must have same type "
36990b57cec5SDimitry Andric           "for operands and result!",
37000b57cec5SDimitry Andric           &B);
37010b57cec5SDimitry Andric     break;
37020b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
37030b57cec5SDimitry Andric   // floating-point operands.
37040b57cec5SDimitry Andric   case Instruction::FAdd:
37050b57cec5SDimitry Andric   case Instruction::FSub:
37060b57cec5SDimitry Andric   case Instruction::FMul:
37070b57cec5SDimitry Andric   case Instruction::FDiv:
37080b57cec5SDimitry Andric   case Instruction::FRem:
370981ad6265SDimitry Andric     Check(B.getType()->isFPOrFPVectorTy(),
37100b57cec5SDimitry Andric           "Floating-point arithmetic operators only work with "
37110b57cec5SDimitry Andric           "floating-point types!",
37120b57cec5SDimitry Andric           &B);
371381ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
37140b57cec5SDimitry Andric           "Floating-point arithmetic operators must have same type "
37150b57cec5SDimitry Andric           "for operands and result!",
37160b57cec5SDimitry Andric           &B);
37170b57cec5SDimitry Andric     break;
37180b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
37190b57cec5SDimitry Andric   case Instruction::And:
37200b57cec5SDimitry Andric   case Instruction::Or:
37210b57cec5SDimitry Andric   case Instruction::Xor:
372281ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
37230b57cec5SDimitry Andric           "Logical operators only work with integral types!", &B);
372481ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
372581ad6265SDimitry Andric           "Logical operators must have same type for operands and result!", &B);
37260b57cec5SDimitry Andric     break;
37270b57cec5SDimitry Andric   case Instruction::Shl:
37280b57cec5SDimitry Andric   case Instruction::LShr:
37290b57cec5SDimitry Andric   case Instruction::AShr:
373081ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
37310b57cec5SDimitry Andric           "Shifts only work with integral types!", &B);
373281ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
37330b57cec5SDimitry Andric           "Shift return type must be same as operands!", &B);
37340b57cec5SDimitry Andric     break;
37350b57cec5SDimitry Andric   default:
37360b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
37370b57cec5SDimitry Andric   }
37380b57cec5SDimitry Andric 
37390b57cec5SDimitry Andric   visitInstruction(B);
37400b57cec5SDimitry Andric }
37410b57cec5SDimitry Andric 
37420b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
37430b57cec5SDimitry Andric   // Check that the operands are the same type
37440b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
37450b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
374681ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
37470b57cec5SDimitry Andric         "Both operands to ICmp instruction are not of the same type!", &IC);
37480b57cec5SDimitry Andric   // Check that the operands are the right type
374981ad6265SDimitry Andric   Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
37500b57cec5SDimitry Andric         "Invalid operand types for ICmp instruction", &IC);
37510b57cec5SDimitry Andric   // Check that the predicate is valid.
375281ad6265SDimitry Andric   Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric   visitInstruction(IC);
37550b57cec5SDimitry Andric }
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
37580b57cec5SDimitry Andric   // Check that the operands are the same type
37590b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
37600b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
376181ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
37620b57cec5SDimitry Andric         "Both operands to FCmp instruction are not of the same type!", &FC);
37630b57cec5SDimitry Andric   // Check that the operands are the right type
376481ad6265SDimitry Andric   Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
376581ad6265SDimitry Andric         &FC);
37660b57cec5SDimitry Andric   // Check that the predicate is valid.
376781ad6265SDimitry Andric   Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
37680b57cec5SDimitry Andric 
37690b57cec5SDimitry Andric   visitInstruction(FC);
37700b57cec5SDimitry Andric }
37710b57cec5SDimitry Andric 
37720b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
377381ad6265SDimitry Andric   Check(ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
37740b57cec5SDimitry Andric         "Invalid extractelement operands!", &EI);
37750b57cec5SDimitry Andric   visitInstruction(EI);
37760b57cec5SDimitry Andric }
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
377981ad6265SDimitry Andric   Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
37800b57cec5SDimitry Andric                                            IE.getOperand(2)),
37810b57cec5SDimitry Andric         "Invalid insertelement operands!", &IE);
37820b57cec5SDimitry Andric   visitInstruction(IE);
37830b57cec5SDimitry Andric }
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
378681ad6265SDimitry Andric   Check(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
37875ffd83dbSDimitry Andric                                            SV.getShuffleMask()),
37880b57cec5SDimitry Andric         "Invalid shufflevector operands!", &SV);
37890b57cec5SDimitry Andric   visitInstruction(SV);
37900b57cec5SDimitry Andric }
37910b57cec5SDimitry Andric 
37920b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
37930b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
37940b57cec5SDimitry Andric 
379581ad6265SDimitry Andric   Check(isa<PointerType>(TargetTy),
37960b57cec5SDimitry Andric         "GEP base pointer is not a vector or a vector of pointers", &GEP);
379781ad6265SDimitry Andric   Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
37980b57cec5SDimitry Andric 
3799e8d8bef9SDimitry Andric   SmallVector<Value *, 16> Idxs(GEP.indices());
380081ad6265SDimitry Andric   Check(
380181ad6265SDimitry Andric       all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
38020b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
38030b57cec5SDimitry Andric   Type *ElTy =
38040b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
380581ad6265SDimitry Andric   Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
38060b57cec5SDimitry Andric 
380781ad6265SDimitry Andric   Check(GEP.getType()->isPtrOrPtrVectorTy() &&
38080b57cec5SDimitry Andric             GEP.getResultElementType() == ElTy,
38090b57cec5SDimitry Andric         "GEP is not of right type for indices!", &GEP, ElTy);
38100b57cec5SDimitry Andric 
38115ffd83dbSDimitry Andric   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
38120b57cec5SDimitry Andric     // Additional checks for vector GEPs.
38135ffd83dbSDimitry Andric     ElementCount GEPWidth = GEPVTy->getElementCount();
38140b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
381581ad6265SDimitry Andric       Check(
38165ffd83dbSDimitry Andric           GEPWidth ==
38175ffd83dbSDimitry Andric               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
38180b57cec5SDimitry Andric           "Vector GEP result width doesn't match operand's", &GEP);
38190b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
38200b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
38215ffd83dbSDimitry Andric       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
38225ffd83dbSDimitry Andric         ElementCount IndexWidth = IndexVTy->getElementCount();
382381ad6265SDimitry Andric         Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
38240b57cec5SDimitry Andric       }
382581ad6265SDimitry Andric       Check(IndexTy->isIntOrIntVectorTy(),
38260b57cec5SDimitry Andric             "All GEP indices should be of integer type");
38270b57cec5SDimitry Andric     }
38280b57cec5SDimitry Andric   }
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
383181ad6265SDimitry Andric     Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
38320b57cec5SDimitry Andric           "GEP address space doesn't match type", &GEP);
38330b57cec5SDimitry Andric   }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric   visitInstruction(GEP);
38360b57cec5SDimitry Andric }
38370b57cec5SDimitry Andric 
38380b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
38390b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
38400b57cec5SDimitry Andric }
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
38430b57cec5SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
38440b57cec5SDimitry Andric          "precondition violation");
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
384781ad6265SDimitry Andric   Check(NumOperands % 2 == 0, "Unfinished range!", Range);
38480b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
384981ad6265SDimitry Andric   Check(NumRanges >= 1, "It should have at least one range!", Range);
38500b57cec5SDimitry Andric 
38510b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
38520b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
38530b57cec5SDimitry Andric     ConstantInt *Low =
38540b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
385581ad6265SDimitry Andric     Check(Low, "The lower limit must be an integer!", Low);
38560b57cec5SDimitry Andric     ConstantInt *High =
38570b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
385881ad6265SDimitry Andric     Check(High, "The upper limit must be an integer!", High);
385981ad6265SDimitry Andric     Check(High->getType() == Low->getType() && High->getType() == Ty,
38600b57cec5SDimitry Andric           "Range types must match instruction type!", &I);
38610b57cec5SDimitry Andric 
38620b57cec5SDimitry Andric     APInt HighV = High->getValue();
38630b57cec5SDimitry Andric     APInt LowV = Low->getValue();
38640b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
386581ad6265SDimitry Andric     Check(!CurRange.isEmptySet() && !CurRange.isFullSet(),
38660b57cec5SDimitry Andric           "Range must not be empty!", Range);
38670b57cec5SDimitry Andric     if (i != 0) {
386881ad6265SDimitry Andric       Check(CurRange.intersectWith(LastRange).isEmptySet(),
38690b57cec5SDimitry Andric             "Intervals are overlapping", Range);
387081ad6265SDimitry Andric       Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
38710b57cec5SDimitry Andric             Range);
387281ad6265SDimitry Andric       Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
38730b57cec5SDimitry Andric             Range);
38740b57cec5SDimitry Andric     }
38750b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
38760b57cec5SDimitry Andric   }
38770b57cec5SDimitry Andric   if (NumRanges > 2) {
38780b57cec5SDimitry Andric     APInt FirstLow =
38790b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
38800b57cec5SDimitry Andric     APInt FirstHigh =
38810b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
38820b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
388381ad6265SDimitry Andric     Check(FirstRange.intersectWith(LastRange).isEmptySet(),
38840b57cec5SDimitry Andric           "Intervals are overlapping", Range);
388581ad6265SDimitry Andric     Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
38860b57cec5SDimitry Andric           Range);
38870b57cec5SDimitry Andric   }
38880b57cec5SDimitry Andric }
38890b57cec5SDimitry Andric 
38900b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
38910b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
389281ad6265SDimitry Andric   Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
389381ad6265SDimitry Andric   Check(!(Size & (Size - 1)),
38940b57cec5SDimitry Andric         "atomic memory access' operand must have a power-of-two size", Ty, I);
38950b57cec5SDimitry Andric }
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
38980b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
389981ad6265SDimitry Andric   Check(PTy, "Load operand must be a pointer.", &LI);
39000b57cec5SDimitry Andric   Type *ElTy = LI.getType();
39010eae32dcSDimitry Andric   if (MaybeAlign A = LI.getAlign()) {
390281ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
39030b57cec5SDimitry Andric           "huge alignment values are unsupported", &LI);
39040eae32dcSDimitry Andric   }
390581ad6265SDimitry Andric   Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
39060b57cec5SDimitry Andric   if (LI.isAtomic()) {
390781ad6265SDimitry Andric     Check(LI.getOrdering() != AtomicOrdering::Release &&
39080b57cec5SDimitry Andric               LI.getOrdering() != AtomicOrdering::AcquireRelease,
39090b57cec5SDimitry Andric           "Load cannot have Release ordering", &LI);
391081ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
39110b57cec5SDimitry Andric           "atomic load operand must have integer, pointer, or floating point "
39120b57cec5SDimitry Andric           "type!",
39130b57cec5SDimitry Andric           ElTy, &LI);
39140b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
39150b57cec5SDimitry Andric   } else {
391681ad6265SDimitry Andric     Check(LI.getSyncScopeID() == SyncScope::System,
39170b57cec5SDimitry Andric           "Non-atomic load cannot have SynchronizationScope specified", &LI);
39180b57cec5SDimitry Andric   }
39190b57cec5SDimitry Andric 
39200b57cec5SDimitry Andric   visitInstruction(LI);
39210b57cec5SDimitry Andric }
39220b57cec5SDimitry Andric 
39230b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
39240b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
392581ad6265SDimitry Andric   Check(PTy, "Store operand must be a pointer.", &SI);
3926fe6060f1SDimitry Andric   Type *ElTy = SI.getOperand(0)->getType();
392781ad6265SDimitry Andric   Check(PTy->isOpaqueOrPointeeTypeMatches(ElTy),
39280b57cec5SDimitry Andric         "Stored value type does not match pointer operand type!", &SI, ElTy);
39290eae32dcSDimitry Andric   if (MaybeAlign A = SI.getAlign()) {
393081ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
39310b57cec5SDimitry Andric           "huge alignment values are unsupported", &SI);
39320eae32dcSDimitry Andric   }
393381ad6265SDimitry Andric   Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
39340b57cec5SDimitry Andric   if (SI.isAtomic()) {
393581ad6265SDimitry Andric     Check(SI.getOrdering() != AtomicOrdering::Acquire &&
39360b57cec5SDimitry Andric               SI.getOrdering() != AtomicOrdering::AcquireRelease,
39370b57cec5SDimitry Andric           "Store cannot have Acquire ordering", &SI);
393881ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
39390b57cec5SDimitry Andric           "atomic store operand must have integer, pointer, or floating point "
39400b57cec5SDimitry Andric           "type!",
39410b57cec5SDimitry Andric           ElTy, &SI);
39420b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
39430b57cec5SDimitry Andric   } else {
394481ad6265SDimitry Andric     Check(SI.getSyncScopeID() == SyncScope::System,
39450b57cec5SDimitry Andric           "Non-atomic store cannot have SynchronizationScope specified", &SI);
39460b57cec5SDimitry Andric   }
39470b57cec5SDimitry Andric   visitInstruction(SI);
39480b57cec5SDimitry Andric }
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
39510b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
39520b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
3953fe6060f1SDimitry Andric   for (const auto &I : llvm::enumerate(Call.args())) {
3954fe6060f1SDimitry Andric     if (I.value() == SwiftErrorVal) {
395581ad6265SDimitry Andric       Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
39560b57cec5SDimitry Andric             "swifterror value when used in a callsite should be marked "
39570b57cec5SDimitry Andric             "with swifterror attribute",
39580b57cec5SDimitry Andric             SwiftErrorVal, Call);
39590b57cec5SDimitry Andric     }
39600b57cec5SDimitry Andric   }
39610b57cec5SDimitry Andric }
39620b57cec5SDimitry Andric 
39630b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
39640b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
39650b57cec5SDimitry Andric   // a swifterror argument.
39660b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
396781ad6265SDimitry Andric     Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
39680b57cec5SDimitry Andric               isa<InvokeInst>(U),
39690b57cec5SDimitry Andric           "swifterror value can only be loaded and stored from, or "
39700b57cec5SDimitry Andric           "as a swifterror argument!",
39710b57cec5SDimitry Andric           SwiftErrorVal, U);
39720b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
39730b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
397481ad6265SDimitry Andric       Check(StoreI->getOperand(1) == SwiftErrorVal,
39750b57cec5SDimitry Andric             "swifterror value should be the second operand when used "
397681ad6265SDimitry Andric             "by stores",
397781ad6265SDimitry Andric             SwiftErrorVal, U);
39780b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
39790b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
39800b57cec5SDimitry Andric   }
39810b57cec5SDimitry Andric }
39820b57cec5SDimitry Andric 
39830b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
39840b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
398581ad6265SDimitry Andric   Check(AI.getAllocatedType()->isSized(&Visited),
39860b57cec5SDimitry Andric         "Cannot allocate unsized type", &AI);
398781ad6265SDimitry Andric   Check(AI.getArraySize()->getType()->isIntegerTy(),
39880b57cec5SDimitry Andric         "Alloca array size must have integer type", &AI);
39890eae32dcSDimitry Andric   if (MaybeAlign A = AI.getAlign()) {
399081ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
39910b57cec5SDimitry Andric           "huge alignment values are unsupported", &AI);
39920eae32dcSDimitry Andric   }
39930b57cec5SDimitry Andric 
39940b57cec5SDimitry Andric   if (AI.isSwiftError()) {
399581ad6265SDimitry Andric     Check(AI.getAllocatedType()->isPointerTy(),
399681ad6265SDimitry Andric           "swifterror alloca must have pointer type", &AI);
399781ad6265SDimitry Andric     Check(!AI.isArrayAllocation(),
399881ad6265SDimitry Andric           "swifterror alloca must not be array allocation", &AI);
39990b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
40000b57cec5SDimitry Andric   }
40010b57cec5SDimitry Andric 
40020b57cec5SDimitry Andric   visitInstruction(AI);
40030b57cec5SDimitry Andric }
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4006fe6060f1SDimitry Andric   Type *ElTy = CXI.getOperand(1)->getType();
400781ad6265SDimitry Andric   Check(ElTy->isIntOrPtrTy(),
40080b57cec5SDimitry Andric         "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
40090b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
40100b57cec5SDimitry Andric   visitInstruction(CXI);
40110b57cec5SDimitry Andric }
40120b57cec5SDimitry Andric 
40130b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
401481ad6265SDimitry Andric   Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
40150b57cec5SDimitry Andric         "atomicrmw instructions cannot be unordered.", &RMWI);
40160b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
4017fe6060f1SDimitry Andric   Type *ElTy = RMWI.getOperand(1)->getType();
40180b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
401981ad6265SDimitry Andric     Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
402081ad6265SDimitry Andric               ElTy->isPointerTy(),
402181ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
40220b57cec5SDimitry Andric               " operand must have integer or floating point type!",
40230b57cec5SDimitry Andric           &RMWI, ElTy);
40240b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
402581ad6265SDimitry Andric     Check(ElTy->isFloatingPointTy(),
402681ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
40270b57cec5SDimitry Andric               " operand must have floating point type!",
40280b57cec5SDimitry Andric           &RMWI, ElTy);
40290b57cec5SDimitry Andric   } else {
403081ad6265SDimitry Andric     Check(ElTy->isIntegerTy(),
403181ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
40320b57cec5SDimitry Andric               " operand must have integer type!",
40330b57cec5SDimitry Andric           &RMWI, ElTy);
40340b57cec5SDimitry Andric   }
40350b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
403681ad6265SDimitry Andric   Check(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
40370b57cec5SDimitry Andric         "Invalid binary operation!", &RMWI);
40380b57cec5SDimitry Andric   visitInstruction(RMWI);
40390b57cec5SDimitry Andric }
40400b57cec5SDimitry Andric 
40410b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
40420b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
404381ad6265SDimitry Andric   Check(Ordering == AtomicOrdering::Acquire ||
40440b57cec5SDimitry Andric             Ordering == AtomicOrdering::Release ||
40450b57cec5SDimitry Andric             Ordering == AtomicOrdering::AcquireRelease ||
40460b57cec5SDimitry Andric             Ordering == AtomicOrdering::SequentiallyConsistent,
40470b57cec5SDimitry Andric         "fence instructions may only have acquire, release, acq_rel, or "
40480b57cec5SDimitry Andric         "seq_cst ordering.",
40490b57cec5SDimitry Andric         &FI);
40500b57cec5SDimitry Andric   visitInstruction(FI);
40510b57cec5SDimitry Andric }
40520b57cec5SDimitry Andric 
40530b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
405481ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
40550b57cec5SDimitry Andric                                          EVI.getIndices()) == EVI.getType(),
40560b57cec5SDimitry Andric         "Invalid ExtractValueInst operands!", &EVI);
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric   visitInstruction(EVI);
40590b57cec5SDimitry Andric }
40600b57cec5SDimitry Andric 
40610b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
406281ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
40630b57cec5SDimitry Andric                                          IVI.getIndices()) ==
40640b57cec5SDimitry Andric             IVI.getOperand(1)->getType(),
40650b57cec5SDimitry Andric         "Invalid InsertValueInst operands!", &IVI);
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   visitInstruction(IVI);
40680b57cec5SDimitry Andric }
40690b57cec5SDimitry Andric 
40700b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
40710b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
40720b57cec5SDimitry Andric     return FPI->getParentPad();
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
40750b57cec5SDimitry Andric }
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
40780b57cec5SDimitry Andric   assert(I.isEHPad());
40790b57cec5SDimitry Andric 
40800b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
40810b57cec5SDimitry Andric   Function *F = BB->getParent();
40820b57cec5SDimitry Andric 
408381ad6265SDimitry Andric   Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
40840b57cec5SDimitry Andric 
40850b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
40860b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
40870b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
40880b57cec5SDimitry Andric     // invoke.
40890b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
40900b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
409181ad6265SDimitry Andric       Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
40920b57cec5SDimitry Andric             "Block containing LandingPadInst must be jumped to "
40930b57cec5SDimitry Andric             "only by the unwind edge of an invoke.",
40940b57cec5SDimitry Andric             LPI);
40950b57cec5SDimitry Andric     }
40960b57cec5SDimitry Andric     return;
40970b57cec5SDimitry Andric   }
40980b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
40990b57cec5SDimitry Andric     if (!pred_empty(BB))
410081ad6265SDimitry Andric       Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
41010b57cec5SDimitry Andric             "Block containg CatchPadInst must be jumped to "
41020b57cec5SDimitry Andric             "only by its catchswitch.",
41030b57cec5SDimitry Andric             CPI);
410481ad6265SDimitry Andric     Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
41050b57cec5SDimitry Andric           "Catchswitch cannot unwind to one of its catchpads",
41060b57cec5SDimitry Andric           CPI->getCatchSwitch(), CPI);
41070b57cec5SDimitry Andric     return;
41080b57cec5SDimitry Andric   }
41090b57cec5SDimitry Andric 
41100b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
41110b57cec5SDimitry Andric   // pad relationship.
41120b57cec5SDimitry Andric   Instruction *ToPad = &I;
41130b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
41140b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
41150b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
41160b57cec5SDimitry Andric     Value *FromPad;
41170b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
411881ad6265SDimitry Andric       Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
41190b57cec5SDimitry Andric             "EH pad must be jumped to via an unwind edge", ToPad, II);
41200b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
41210b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
41220b57cec5SDimitry Andric       else
41230b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
41240b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
41250b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
412681ad6265SDimitry Andric       Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
41270b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
41280b57cec5SDimitry Andric       FromPad = CSI;
41290b57cec5SDimitry Andric     } else {
413081ad6265SDimitry Andric       Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
41310b57cec5SDimitry Andric     }
41320b57cec5SDimitry Andric 
41330b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
41340b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
41350b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
413681ad6265SDimitry Andric       Check(FromPad != ToPad,
41370b57cec5SDimitry Andric             "EH pad cannot handle exceptions raised within it", FromPad, TI);
41380b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
41390b57cec5SDimitry Andric         // This is a legal unwind edge.
41400b57cec5SDimitry Andric         break;
41410b57cec5SDimitry Andric       }
414281ad6265SDimitry Andric       Check(!isa<ConstantTokenNone>(FromPad),
41430b57cec5SDimitry Andric             "A single unwind edge may only enter one EH pad", TI);
414481ad6265SDimitry Andric       Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
414581ad6265SDimitry Andric             FromPad);
414604eeddc0SDimitry Andric 
414704eeddc0SDimitry Andric       // This will be diagnosed on the corresponding instruction already. We
414804eeddc0SDimitry Andric       // need the extra check here to make sure getParentPad() works.
414981ad6265SDimitry Andric       Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
415004eeddc0SDimitry Andric             "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
41510b57cec5SDimitry Andric     }
41520b57cec5SDimitry Andric   }
41530b57cec5SDimitry Andric }
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
41560b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
41570b57cec5SDimitry Andric   // isn't a cleanup.
415881ad6265SDimitry Andric   Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
41590b57cec5SDimitry Andric         "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
41620b57cec5SDimitry Andric 
41630b57cec5SDimitry Andric   if (!LandingPadResultTy)
41640b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
41650b57cec5SDimitry Andric   else
416681ad6265SDimitry Andric     Check(LandingPadResultTy == LPI.getType(),
41670b57cec5SDimitry Andric           "The landingpad instruction should have a consistent result type "
41680b57cec5SDimitry Andric           "inside a function.",
41690b57cec5SDimitry Andric           &LPI);
41700b57cec5SDimitry Andric 
41710b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
417281ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
41730b57cec5SDimitry Andric         "LandingPadInst needs to be in a function with a personality.", &LPI);
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
41760b57cec5SDimitry Andric   // block.
417781ad6265SDimitry Andric   Check(LPI.getParent()->getLandingPadInst() == &LPI,
417881ad6265SDimitry Andric         "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
41790b57cec5SDimitry Andric 
41800b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
41810b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
41820b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
418381ad6265SDimitry Andric       Check(isa<PointerType>(Clause->getType()),
41840b57cec5SDimitry Andric             "Catch operand does not have pointer type!", &LPI);
41850b57cec5SDimitry Andric     } else {
418681ad6265SDimitry Andric       Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
418781ad6265SDimitry Andric       Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
41880b57cec5SDimitry Andric             "Filter operand is not an array of constants!", &LPI);
41890b57cec5SDimitry Andric     }
41900b57cec5SDimitry Andric   }
41910b57cec5SDimitry Andric 
41920b57cec5SDimitry Andric   visitInstruction(LPI);
41930b57cec5SDimitry Andric }
41940b57cec5SDimitry Andric 
41950b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
419681ad6265SDimitry Andric   Check(RI.getFunction()->hasPersonalityFn(),
41970b57cec5SDimitry Andric         "ResumeInst needs to be in a function with a personality.", &RI);
41980b57cec5SDimitry Andric 
41990b57cec5SDimitry Andric   if (!LandingPadResultTy)
42000b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
42010b57cec5SDimitry Andric   else
420281ad6265SDimitry Andric     Check(LandingPadResultTy == RI.getValue()->getType(),
42030b57cec5SDimitry Andric           "The resume instruction should have a consistent result type "
42040b57cec5SDimitry Andric           "inside a function.",
42050b57cec5SDimitry Andric           &RI);
42060b57cec5SDimitry Andric 
42070b57cec5SDimitry Andric   visitTerminator(RI);
42080b57cec5SDimitry Andric }
42090b57cec5SDimitry Andric 
42100b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
42110b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric   Function *F = BB->getParent();
421481ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
42150b57cec5SDimitry Andric         "CatchPadInst needs to be in a function with a personality.", &CPI);
42160b57cec5SDimitry Andric 
421781ad6265SDimitry Andric   Check(isa<CatchSwitchInst>(CPI.getParentPad()),
42180b57cec5SDimitry Andric         "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
42190b57cec5SDimitry Andric         CPI.getParentPad());
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
42220b57cec5SDimitry Andric   // block.
422381ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
42240b57cec5SDimitry Andric         "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
42250b57cec5SDimitry Andric 
42260b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
42270b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
42280b57cec5SDimitry Andric }
42290b57cec5SDimitry Andric 
42300b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
423181ad6265SDimitry Andric   Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
42320b57cec5SDimitry Andric         "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
42330b57cec5SDimitry Andric         CatchReturn.getOperand(0));
42340b57cec5SDimitry Andric 
42350b57cec5SDimitry Andric   visitTerminator(CatchReturn);
42360b57cec5SDimitry Andric }
42370b57cec5SDimitry Andric 
42380b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
42390b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
42400b57cec5SDimitry Andric 
42410b57cec5SDimitry Andric   Function *F = BB->getParent();
424281ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
42430b57cec5SDimitry Andric         "CleanupPadInst needs to be in a function with a personality.", &CPI);
42440b57cec5SDimitry Andric 
42450b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
42460b57cec5SDimitry Andric   // block.
424781ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
424881ad6265SDimitry Andric         "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
42490b57cec5SDimitry Andric 
42500b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
425181ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
42520b57cec5SDimitry Andric         "CleanupPadInst has an invalid parent.", &CPI);
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
42550b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
42560b57cec5SDimitry Andric }
42570b57cec5SDimitry Andric 
42580b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
42590b57cec5SDimitry Andric   User *FirstUser = nullptr;
42600b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
42610b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
42620b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric   while (!Worklist.empty()) {
42650b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
426681ad6265SDimitry Andric     Check(Seen.insert(CurrentPad).second,
42670b57cec5SDimitry Andric           "FuncletPadInst must not be nested within itself", CurrentPad);
42680b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
42690b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
42700b57cec5SDimitry Andric       BasicBlock *UnwindDest;
42710b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
42720b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
42730b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
42740b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
42750b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
42760b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
42770b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
42780b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
42790b57cec5SDimitry Andric           continue;
42800b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
42810b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
42820b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
42830b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
42840b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
42850b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
42860b57cec5SDimitry Andric         // such calls to be annotated nounwind.
42870b57cec5SDimitry Andric         continue;
42880b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
42890b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
42900b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
42910b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
42920b57cec5SDimitry Andric         Worklist.push_back(CPI);
42930b57cec5SDimitry Andric         continue;
42940b57cec5SDimitry Andric       } else {
429581ad6265SDimitry Andric         Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
42960b57cec5SDimitry Andric         continue;
42970b57cec5SDimitry Andric       }
42980b57cec5SDimitry Andric 
42990b57cec5SDimitry Andric       Value *UnwindPad;
43000b57cec5SDimitry Andric       bool ExitsFPI;
43010b57cec5SDimitry Andric       if (UnwindDest) {
43020b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
43030b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
43040b57cec5SDimitry Andric           continue;
43050b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
43060b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
43070b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
43080b57cec5SDimitry Andric           continue;
43090b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
43100b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
43110b57cec5SDimitry Andric         // of them are exited so we can stop searching their
43120b57cec5SDimitry Andric         // children.
43130b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
43140b57cec5SDimitry Andric         ExitsFPI = false;
43150b57cec5SDimitry Andric         do {
43160b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
43170b57cec5SDimitry Andric             ExitsFPI = true;
43180b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
43190b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
43200b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
43210b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
43220b57cec5SDimitry Andric             break;
43230b57cec5SDimitry Andric           }
43240b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
43250b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
43260b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
43270b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
43280b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
43290b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
43300b57cec5SDimitry Andric             break;
43310b57cec5SDimitry Andric           }
43320b57cec5SDimitry Andric           ExitedPad = ExitedParent;
43330b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
43340b57cec5SDimitry Andric       } else {
43350b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
43360b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
43370b57cec5SDimitry Andric         ExitsFPI = true;
43380b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
43390b57cec5SDimitry Andric       }
43400b57cec5SDimitry Andric 
43410b57cec5SDimitry Andric       if (ExitsFPI) {
43420b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
43430b57cec5SDimitry Andric         // such edges.
43440b57cec5SDimitry Andric         if (FirstUser) {
434581ad6265SDimitry Andric           Check(UnwindPad == FirstUnwindPad,
434681ad6265SDimitry Andric                 "Unwind edges out of a funclet "
43470b57cec5SDimitry Andric                 "pad must have the same unwind "
43480b57cec5SDimitry Andric                 "dest",
43490b57cec5SDimitry Andric                 &FPI, U, FirstUser);
43500b57cec5SDimitry Andric         } else {
43510b57cec5SDimitry Andric           FirstUser = U;
43520b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
43530b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
43540b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
43550b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
43560b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
43570b57cec5SDimitry Andric         }
43580b57cec5SDimitry Andric       }
43590b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
43600b57cec5SDimitry Andric       // soon as we know where they unwind to.
43610b57cec5SDimitry Andric       if (CurrentPad != &FPI)
43620b57cec5SDimitry Andric         break;
43630b57cec5SDimitry Andric     }
43640b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
43650b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
43660b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
43670b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
43680b57cec5SDimitry Andric         // all direct uses of FPI.
43690b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
43700b57cec5SDimitry Andric         continue;
43710b57cec5SDimitry Andric       }
43720b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
43730b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
43740b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
43750b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
43760b57cec5SDimitry Andric       // UnresolvedAncestorPad.
43770b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
43780b57cec5SDimitry Andric       while (!Worklist.empty()) {
43790b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
43800b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
43810b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
43820b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
43830b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
43840b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
43850b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
43860b57cec5SDimitry Andric             break;
43870b57cec5SDimitry Andric           }
43880b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
43890b57cec5SDimitry Andric         }
43900b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
43910b57cec5SDimitry Andric         // then the uncle is not yet resolved.
43920b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
43930b57cec5SDimitry Andric           break;
43940b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
43950b57cec5SDimitry Andric         Worklist.pop_back();
43960b57cec5SDimitry Andric       }
43970b57cec5SDimitry Andric     }
43980b57cec5SDimitry Andric   }
43990b57cec5SDimitry Andric 
44000b57cec5SDimitry Andric   if (FirstUnwindPad) {
44010b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
44020b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
44030b57cec5SDimitry Andric       Value *SwitchUnwindPad;
44040b57cec5SDimitry Andric       if (SwitchUnwindDest)
44050b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
44060b57cec5SDimitry Andric       else
44070b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
440881ad6265SDimitry Andric       Check(SwitchUnwindPad == FirstUnwindPad,
44090b57cec5SDimitry Andric             "Unwind edges out of a catch must have the same unwind dest as "
44100b57cec5SDimitry Andric             "the parent catchswitch",
44110b57cec5SDimitry Andric             &FPI, FirstUser, CatchSwitch);
44120b57cec5SDimitry Andric     }
44130b57cec5SDimitry Andric   }
44140b57cec5SDimitry Andric 
44150b57cec5SDimitry Andric   visitInstruction(FPI);
44160b57cec5SDimitry Andric }
44170b57cec5SDimitry Andric 
44180b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
44190b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
44200b57cec5SDimitry Andric 
44210b57cec5SDimitry Andric   Function *F = BB->getParent();
442281ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
44230b57cec5SDimitry Andric         "CatchSwitchInst needs to be in a function with a personality.",
44240b57cec5SDimitry Andric         &CatchSwitch);
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
44270b57cec5SDimitry Andric   // block.
442881ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CatchSwitch,
44290b57cec5SDimitry Andric         "CatchSwitchInst not the first non-PHI instruction in the block.",
44300b57cec5SDimitry Andric         &CatchSwitch);
44310b57cec5SDimitry Andric 
44320b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
443381ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
44340b57cec5SDimitry Andric         "CatchSwitchInst has an invalid parent.", ParentPad);
44350b57cec5SDimitry Andric 
44360b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
44370b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
443881ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
44390b57cec5SDimitry Andric           "CatchSwitchInst must unwind to an EH block which is not a "
44400b57cec5SDimitry Andric           "landingpad.",
44410b57cec5SDimitry Andric           &CatchSwitch);
44420b57cec5SDimitry Andric 
44430b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
44440b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
44450b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
44460b57cec5SDimitry Andric   }
44470b57cec5SDimitry Andric 
444881ad6265SDimitry Andric   Check(CatchSwitch.getNumHandlers() != 0,
44490b57cec5SDimitry Andric         "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
445281ad6265SDimitry Andric     Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
44530b57cec5SDimitry Andric           "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
44540b57cec5SDimitry Andric   }
44550b57cec5SDimitry Andric 
44560b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
44570b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
44580b57cec5SDimitry Andric }
44590b57cec5SDimitry Andric 
44600b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
446181ad6265SDimitry Andric   Check(isa<CleanupPadInst>(CRI.getOperand(0)),
44620b57cec5SDimitry Andric         "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
44630b57cec5SDimitry Andric         CRI.getOperand(0));
44640b57cec5SDimitry Andric 
44650b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
44660b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
446781ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
44680b57cec5SDimitry Andric           "CleanupReturnInst must unwind to an EH block which is not a "
44690b57cec5SDimitry Andric           "landingpad.",
44700b57cec5SDimitry Andric           &CRI);
44710b57cec5SDimitry Andric   }
44720b57cec5SDimitry Andric 
44730b57cec5SDimitry Andric   visitTerminator(CRI);
44740b57cec5SDimitry Andric }
44750b57cec5SDimitry Andric 
44760b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
44770b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
44780b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
44790b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
44800b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
44810b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
44820b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
44830b57cec5SDimitry Andric       return;
44840b57cec5SDimitry Andric   }
44850b57cec5SDimitry Andric 
44860b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
44870b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
44880b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
44890b57cec5SDimitry Andric   //
44900b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
44910b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
44920b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
44930b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
44940b57cec5SDimitry Andric     return;
44950b57cec5SDimitry Andric 
44960b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
449781ad6265SDimitry Andric   Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
44980b57cec5SDimitry Andric }
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
450181ad6265SDimitry Andric   Check(I.getType()->isPointerTy(),
450281ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
450381ad6265SDimitry Andric         "apply only to pointer types",
450481ad6265SDimitry Andric         &I);
450581ad6265SDimitry Andric   Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
45060b57cec5SDimitry Andric         "dereferenceable, dereferenceable_or_null apply only to load"
450781ad6265SDimitry Andric         " and inttoptr instructions, use attributes for calls or invokes",
450881ad6265SDimitry Andric         &I);
450981ad6265SDimitry Andric   Check(MD->getNumOperands() == 1,
451081ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
451181ad6265SDimitry Andric         "take one operand!",
451281ad6265SDimitry Andric         &I);
45130b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
451481ad6265SDimitry Andric   Check(CI && CI->getType()->isIntegerTy(64),
451581ad6265SDimitry Andric         "dereferenceable, "
451681ad6265SDimitry Andric         "dereferenceable_or_null metadata value must be an i64!",
451781ad6265SDimitry Andric         &I);
45180b57cec5SDimitry Andric }
45190b57cec5SDimitry Andric 
45208bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
452181ad6265SDimitry Andric   Check(MD->getNumOperands() >= 2,
45228bcb0991SDimitry Andric         "!prof annotations should have no less than 2 operands", MD);
45238bcb0991SDimitry Andric 
45248bcb0991SDimitry Andric   // Check first operand.
452581ad6265SDimitry Andric   Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
452681ad6265SDimitry Andric   Check(isa<MDString>(MD->getOperand(0)),
45278bcb0991SDimitry Andric         "expected string with name of the !prof annotation", MD);
45288bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
45298bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
45308bcb0991SDimitry Andric 
45318bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
45328bcb0991SDimitry Andric   if (ProfName.equals("branch_weights")) {
45335ffd83dbSDimitry Andric     if (isa<InvokeInst>(&I)) {
453481ad6265SDimitry Andric       Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
45355ffd83dbSDimitry Andric             "Wrong number of InvokeInst branch_weights operands", MD);
45365ffd83dbSDimitry Andric     } else {
45378bcb0991SDimitry Andric       unsigned ExpectedNumOperands = 0;
45388bcb0991SDimitry Andric       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
45398bcb0991SDimitry Andric         ExpectedNumOperands = BI->getNumSuccessors();
45408bcb0991SDimitry Andric       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
45418bcb0991SDimitry Andric         ExpectedNumOperands = SI->getNumSuccessors();
45425ffd83dbSDimitry Andric       else if (isa<CallInst>(&I))
45438bcb0991SDimitry Andric         ExpectedNumOperands = 1;
45448bcb0991SDimitry Andric       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
45458bcb0991SDimitry Andric         ExpectedNumOperands = IBI->getNumDestinations();
45468bcb0991SDimitry Andric       else if (isa<SelectInst>(&I))
45478bcb0991SDimitry Andric         ExpectedNumOperands = 2;
4548*bdd1243dSDimitry Andric       else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
4549*bdd1243dSDimitry Andric         ExpectedNumOperands = CI->getNumSuccessors();
45508bcb0991SDimitry Andric       else
45518bcb0991SDimitry Andric         CheckFailed("!prof branch_weights are not allowed for this instruction",
45528bcb0991SDimitry Andric                     MD);
45538bcb0991SDimitry Andric 
455481ad6265SDimitry Andric       Check(MD->getNumOperands() == 1 + ExpectedNumOperands,
45558bcb0991SDimitry Andric             "Wrong number of operands", MD);
45565ffd83dbSDimitry Andric     }
45578bcb0991SDimitry Andric     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
45588bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
455981ad6265SDimitry Andric       Check(MDO, "second operand should not be null", MD);
456081ad6265SDimitry Andric       Check(mdconst::dyn_extract<ConstantInt>(MDO),
45618bcb0991SDimitry Andric             "!prof brunch_weights operand is not a const int");
45628bcb0991SDimitry Andric     }
45638bcb0991SDimitry Andric   }
45648bcb0991SDimitry Andric }
45658bcb0991SDimitry Andric 
4566*bdd1243dSDimitry Andric void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
4567*bdd1243dSDimitry Andric   assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
4568*bdd1243dSDimitry Andric   bool ExpectedInstTy =
4569*bdd1243dSDimitry Andric       isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
4570*bdd1243dSDimitry Andric   CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
4571*bdd1243dSDimitry Andric           I, MD);
4572*bdd1243dSDimitry Andric   // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4573*bdd1243dSDimitry Andric   // only be found as DbgAssignIntrinsic operands.
4574*bdd1243dSDimitry Andric   if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
4575*bdd1243dSDimitry Andric     for (auto *User : AsValue->users()) {
4576*bdd1243dSDimitry Andric       CheckDI(isa<DbgAssignIntrinsic>(User),
4577*bdd1243dSDimitry Andric               "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4578*bdd1243dSDimitry Andric               MD, User);
4579*bdd1243dSDimitry Andric       // All of the dbg.assign intrinsics should be in the same function as I.
4580*bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
4581*bdd1243dSDimitry Andric         CheckDI(DAI->getFunction() == I.getFunction(),
4582*bdd1243dSDimitry Andric                 "dbg.assign not in same function as inst", DAI, &I);
4583*bdd1243dSDimitry Andric     }
4584*bdd1243dSDimitry Andric   }
4585*bdd1243dSDimitry Andric }
4586*bdd1243dSDimitry Andric 
4587fcaf7f86SDimitry Andric void Verifier::visitCallStackMetadata(MDNode *MD) {
4588fcaf7f86SDimitry Andric   // Call stack metadata should consist of a list of at least 1 constant int
4589fcaf7f86SDimitry Andric   // (representing a hash of the location).
4590fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4591fcaf7f86SDimitry Andric         "call stack metadata should have at least 1 operand", MD);
4592fcaf7f86SDimitry Andric 
4593fcaf7f86SDimitry Andric   for (const auto &Op : MD->operands())
4594fcaf7f86SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
4595fcaf7f86SDimitry Andric           "call stack metadata operand should be constant integer", Op);
4596fcaf7f86SDimitry Andric }
4597fcaf7f86SDimitry Andric 
4598fcaf7f86SDimitry Andric void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
4599fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
4600fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4601fcaf7f86SDimitry Andric         "!memprof annotations should have at least 1 metadata operand "
4602fcaf7f86SDimitry Andric         "(MemInfoBlock)",
4603fcaf7f86SDimitry Andric         MD);
4604fcaf7f86SDimitry Andric 
4605fcaf7f86SDimitry Andric   // Check each MIB
4606fcaf7f86SDimitry Andric   for (auto &MIBOp : MD->operands()) {
4607fcaf7f86SDimitry Andric     MDNode *MIB = dyn_cast<MDNode>(MIBOp);
4608fcaf7f86SDimitry Andric     // The first operand of an MIB should be the call stack metadata.
4609fcaf7f86SDimitry Andric     // There rest of the operands should be MDString tags, and there should be
4610fcaf7f86SDimitry Andric     // at least one.
4611fcaf7f86SDimitry Andric     Check(MIB->getNumOperands() >= 2,
4612fcaf7f86SDimitry Andric           "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
4613fcaf7f86SDimitry Andric 
4614fcaf7f86SDimitry Andric     // Check call stack metadata (first operand).
4615fcaf7f86SDimitry Andric     Check(MIB->getOperand(0) != nullptr,
4616fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should not be null", MIB);
4617fcaf7f86SDimitry Andric     Check(isa<MDNode>(MIB->getOperand(0)),
4618fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should be an MDNode", MIB);
4619fcaf7f86SDimitry Andric     MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
4620fcaf7f86SDimitry Andric     visitCallStackMetadata(StackMD);
4621fcaf7f86SDimitry Andric 
4622fcaf7f86SDimitry Andric     // Check that remaining operands are MDString.
4623*bdd1243dSDimitry Andric     Check(llvm::all_of(llvm::drop_begin(MIB->operands()),
4624fcaf7f86SDimitry Andric                        [](const MDOperand &Op) { return isa<MDString>(Op); }),
4625fcaf7f86SDimitry Andric           "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB);
4626fcaf7f86SDimitry Andric   }
4627fcaf7f86SDimitry Andric }
4628fcaf7f86SDimitry Andric 
4629fcaf7f86SDimitry Andric void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
4630fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
4631fcaf7f86SDimitry Andric   // Verify the partial callstack annotated from memprof profiles. This callsite
4632fcaf7f86SDimitry Andric   // is a part of a profiled allocation callstack.
4633fcaf7f86SDimitry Andric   visitCallStackMetadata(MD);
4634fcaf7f86SDimitry Andric }
4635fcaf7f86SDimitry Andric 
4636e8d8bef9SDimitry Andric void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
463781ad6265SDimitry Andric   Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
463881ad6265SDimitry Andric   Check(Annotation->getNumOperands() >= 1,
4639e8d8bef9SDimitry Andric         "annotation must have at least one operand");
4640e8d8bef9SDimitry Andric   for (const MDOperand &Op : Annotation->operands())
464181ad6265SDimitry Andric     Check(isa<MDString>(Op.get()), "operands must be strings");
4642e8d8bef9SDimitry Andric }
4643e8d8bef9SDimitry Andric 
4644349cc55cSDimitry Andric void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4645349cc55cSDimitry Andric   unsigned NumOps = MD->getNumOperands();
464681ad6265SDimitry Andric   Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4647349cc55cSDimitry Andric         MD);
464881ad6265SDimitry Andric   Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4649349cc55cSDimitry Andric         "first scope operand must be self-referential or string", MD);
4650349cc55cSDimitry Andric   if (NumOps == 3)
465181ad6265SDimitry Andric     Check(isa<MDString>(MD->getOperand(2)),
4652349cc55cSDimitry Andric           "third scope operand must be string (if used)", MD);
4653349cc55cSDimitry Andric 
4654349cc55cSDimitry Andric   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
465581ad6265SDimitry Andric   Check(Domain != nullptr, "second scope operand must be MDNode", MD);
4656349cc55cSDimitry Andric 
4657349cc55cSDimitry Andric   unsigned NumDomainOps = Domain->getNumOperands();
465881ad6265SDimitry Andric   Check(NumDomainOps >= 1 && NumDomainOps <= 2,
4659349cc55cSDimitry Andric         "domain must have one or two operands", Domain);
466081ad6265SDimitry Andric   Check(Domain->getOperand(0).get() == Domain ||
4661349cc55cSDimitry Andric             isa<MDString>(Domain->getOperand(0)),
4662349cc55cSDimitry Andric         "first domain operand must be self-referential or string", Domain);
4663349cc55cSDimitry Andric   if (NumDomainOps == 2)
466481ad6265SDimitry Andric     Check(isa<MDString>(Domain->getOperand(1)),
4665349cc55cSDimitry Andric           "second domain operand must be string (if used)", Domain);
4666349cc55cSDimitry Andric }
4667349cc55cSDimitry Andric 
4668349cc55cSDimitry Andric void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4669349cc55cSDimitry Andric   for (const MDOperand &Op : MD->operands()) {
4670349cc55cSDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
467181ad6265SDimitry Andric     Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4672349cc55cSDimitry Andric     visitAliasScopeMetadata(OpMD);
4673349cc55cSDimitry Andric   }
4674349cc55cSDimitry Andric }
4675349cc55cSDimitry Andric 
467681ad6265SDimitry Andric void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
467781ad6265SDimitry Andric   auto IsValidAccessScope = [](const MDNode *MD) {
467881ad6265SDimitry Andric     return MD->getNumOperands() == 0 && MD->isDistinct();
467981ad6265SDimitry Andric   };
468081ad6265SDimitry Andric 
468181ad6265SDimitry Andric   // It must be either an access scope itself...
468281ad6265SDimitry Andric   if (IsValidAccessScope(MD))
468381ad6265SDimitry Andric     return;
468481ad6265SDimitry Andric 
468581ad6265SDimitry Andric   // ...or a list of access scopes.
468681ad6265SDimitry Andric   for (const MDOperand &Op : MD->operands()) {
468781ad6265SDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
468881ad6265SDimitry Andric     Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
468981ad6265SDimitry Andric     Check(IsValidAccessScope(OpMD),
469081ad6265SDimitry Andric           "Access scope list contains invalid access scope", MD);
469181ad6265SDimitry Andric   }
469281ad6265SDimitry Andric }
469381ad6265SDimitry Andric 
46940b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
46950b57cec5SDimitry Andric ///
46960b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
46970b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
469881ad6265SDimitry Andric   Check(BB, "Instruction not embedded in basic block!", &I);
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
47010b57cec5SDimitry Andric     for (User *U : I.users()) {
470281ad6265SDimitry Andric       Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
47030b57cec5SDimitry Andric             "Only PHI nodes may reference their own value!", &I);
47040b57cec5SDimitry Andric     }
47050b57cec5SDimitry Andric   }
47060b57cec5SDimitry Andric 
47070b57cec5SDimitry Andric   // Check that void typed values don't have names
470881ad6265SDimitry Andric   Check(!I.getType()->isVoidTy() || !I.hasName(),
47090b57cec5SDimitry Andric         "Instruction has a name, but provides a void value!", &I);
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
47120b57cec5SDimitry Andric   // value type.
471381ad6265SDimitry Andric   Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
47140b57cec5SDimitry Andric         "Instruction returns a non-scalar type!", &I);
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
47170b57cec5SDimitry Andric   // checked against the callee type.
471881ad6265SDimitry Andric   Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
47190b57cec5SDimitry Andric         "Invalid use of metadata!", &I);
47200b57cec5SDimitry Andric 
47210b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
47220b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
47230b57cec5SDimitry Andric   // instruction, it is an error!
47240b57cec5SDimitry Andric   for (Use &U : I.uses()) {
47250b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
472681ad6265SDimitry Andric       Check(Used->getParent() != nullptr,
47270b57cec5SDimitry Andric             "Instruction referencing"
47280b57cec5SDimitry Andric             " instruction not embedded in a basic block!",
47290b57cec5SDimitry Andric             &I, Used);
47300b57cec5SDimitry Andric     else {
47310b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
47320b57cec5SDimitry Andric       return;
47330b57cec5SDimitry Andric     }
47340b57cec5SDimitry Andric   }
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
47370b57cec5SDimitry Andric   // call.
47380b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
474181ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
47440b57cec5SDimitry Andric     // instructions.
47450b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
474681ad6265SDimitry Andric       Check(false, "Instruction operands must be first-class values!", &I);
47470b57cec5SDimitry Andric     }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4750349cc55cSDimitry Andric       // This code checks whether the function is used as the operand of a
4751349cc55cSDimitry Andric       // clang_arc_attachedcall operand bundle.
4752349cc55cSDimitry Andric       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4753349cc55cSDimitry Andric                                       int Idx) {
4754349cc55cSDimitry Andric         return CBI && CBI->isOperandBundleOfType(
4755349cc55cSDimitry Andric                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4756349cc55cSDimitry Andric       };
4757349cc55cSDimitry Andric 
47580b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
4759349cc55cSDimitry Andric       // taken. Ignore cases where the address of the intrinsic function is used
4760349cc55cSDimitry Andric       // as the argument of operand bundle "clang.arc.attachedcall" as those
4761349cc55cSDimitry Andric       // cases are handled in verifyAttachedCallBundle.
476281ad6265SDimitry Andric       Check((!F->isIntrinsic() ||
4763349cc55cSDimitry Andric              (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4764349cc55cSDimitry Andric              IsAttachedCallOperand(F, CBI, i)),
47650b57cec5SDimitry Andric             "Cannot take the address of an intrinsic!", &I);
476681ad6265SDimitry Andric       Check(!F->isIntrinsic() || isa<CallInst>(I) ||
47670b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::donothing ||
4768fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4769fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_end ||
4770fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4771fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
47720b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_resume ||
47730b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_destroy ||
477481ad6265SDimitry Andric                 F->getIntrinsicID() ==
477581ad6265SDimitry Andric                     Intrinsic::experimental_patchpoint_void ||
47760b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
47770b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4778349cc55cSDimitry Andric                 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4779349cc55cSDimitry Andric                 IsAttachedCallOperand(F, CBI, i),
47800b57cec5SDimitry Andric             "Cannot invoke an intrinsic other than donothing, patchpoint, "
4781349cc55cSDimitry Andric             "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
47820b57cec5SDimitry Andric             &I);
478381ad6265SDimitry Andric       Check(F->getParent() == &M, "Referencing function in another module!", &I,
478481ad6265SDimitry Andric             &M, F, F->getParent());
47850b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
478681ad6265SDimitry Andric       Check(OpBB->getParent() == BB->getParent(),
47870b57cec5SDimitry Andric             "Referring to a basic block in another function!", &I);
47880b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
478981ad6265SDimitry Andric       Check(OpArg->getParent() == BB->getParent(),
47900b57cec5SDimitry Andric             "Referring to an argument in another function!", &I);
47910b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
479281ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!", &I,
47930b57cec5SDimitry Andric             &M, GV, GV->getParent());
47940b57cec5SDimitry Andric     } else if (isa<Instruction>(I.getOperand(i))) {
47950b57cec5SDimitry Andric       verifyDominatesUse(I, i);
47960b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
479781ad6265SDimitry Andric       Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
47980b57cec5SDimitry Andric             "Cannot take the address of an inline asm!", &I);
47990b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4800fe6060f1SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy()) {
48010b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
4802fe6060f1SDimitry Andric         // illegal bitcast.
48030b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
48040b57cec5SDimitry Andric       }
48050b57cec5SDimitry Andric     }
48060b57cec5SDimitry Andric   }
48070b57cec5SDimitry Andric 
48080b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
480981ad6265SDimitry Andric     Check(I.getType()->isFPOrFPVectorTy(),
48100b57cec5SDimitry Andric           "fpmath requires a floating point result!", &I);
481181ad6265SDimitry Andric     Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
48120b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
48130b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
48140b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
481581ad6265SDimitry Andric       Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
48160b57cec5SDimitry Andric             "fpmath accuracy must have float type", &I);
481781ad6265SDimitry Andric       Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
48180b57cec5SDimitry Andric             "fpmath accuracy not a positive number!", &I);
48190b57cec5SDimitry Andric     } else {
482081ad6265SDimitry Andric       Check(false, "invalid fpmath accuracy!", &I);
48210b57cec5SDimitry Andric     }
48220b57cec5SDimitry Andric   }
48230b57cec5SDimitry Andric 
48240b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
482581ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
48260b57cec5SDimitry Andric           "Ranges are only for loads, calls and invokes!", &I);
48270b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
48280b57cec5SDimitry Andric   }
48290b57cec5SDimitry Andric 
4830349cc55cSDimitry Andric   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
483181ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<StoreInst>(I),
4832349cc55cSDimitry Andric           "invariant.group metadata is only for loads and stores", &I);
4833349cc55cSDimitry Andric   }
4834349cc55cSDimitry Andric 
4835*bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
483681ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
48370b57cec5SDimitry Andric           &I);
483881ad6265SDimitry Andric     Check(isa<LoadInst>(I),
48390b57cec5SDimitry Andric           "nonnull applies only to load instructions, use attributes"
48400b57cec5SDimitry Andric           " for calls or invokes",
48410b57cec5SDimitry Andric           &I);
4842*bdd1243dSDimitry Andric     Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
48430b57cec5SDimitry Andric   }
48440b57cec5SDimitry Andric 
48450b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
48460b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
48470b57cec5SDimitry Andric 
48480b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
48490b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
48500b57cec5SDimitry Andric 
48510b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
48520b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
48530b57cec5SDimitry Andric 
4854349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
4855349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
4856349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
4857349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
4858349cc55cSDimitry Andric 
485981ad6265SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
486081ad6265SDimitry Andric     visitAccessGroupMetadata(MD);
486181ad6265SDimitry Andric 
48620b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
486381ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "align applies only to pointer types",
48640b57cec5SDimitry Andric           &I);
486581ad6265SDimitry Andric     Check(isa<LoadInst>(I),
486681ad6265SDimitry Andric           "align applies only to load instructions, "
486781ad6265SDimitry Andric           "use attributes for calls or invokes",
486881ad6265SDimitry Andric           &I);
486981ad6265SDimitry Andric     Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
48700b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
487181ad6265SDimitry Andric     Check(CI && CI->getType()->isIntegerTy(64),
48720b57cec5SDimitry Andric           "align metadata value must be an i64!", &I);
48730b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
487481ad6265SDimitry Andric     Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
487581ad6265SDimitry Andric           &I);
487681ad6265SDimitry Andric     Check(Align <= Value::MaximumAlignment,
48770b57cec5SDimitry Andric           "alignment is larger that implementation defined limit", &I);
48780b57cec5SDimitry Andric   }
48790b57cec5SDimitry Andric 
48808bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
48818bcb0991SDimitry Andric     visitProfMetadata(I, MD);
48828bcb0991SDimitry Andric 
4883fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
4884fcaf7f86SDimitry Andric     visitMemProfMetadata(I, MD);
4885fcaf7f86SDimitry Andric 
4886fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
4887fcaf7f86SDimitry Andric     visitCallsiteMetadata(I, MD);
4888fcaf7f86SDimitry Andric 
4889*bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
4890*bdd1243dSDimitry Andric     visitDIAssignIDMetadata(I, MD);
4891*bdd1243dSDimitry Andric 
4892e8d8bef9SDimitry Andric   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
4893e8d8bef9SDimitry Andric     visitAnnotationMetadata(Annotation);
4894e8d8bef9SDimitry Andric 
48950b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
489681ad6265SDimitry Andric     CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
48975ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::Yes);
48980b57cec5SDimitry Andric   }
48990b57cec5SDimitry Andric 
49008bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
49010b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
49028bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
49038bcb0991SDimitry Andric   }
49040b57cec5SDimitry Andric 
49055ffd83dbSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
49065ffd83dbSDimitry Andric   I.getAllMetadata(MDs);
49075ffd83dbSDimitry Andric   for (auto Attachment : MDs) {
49085ffd83dbSDimitry Andric     unsigned Kind = Attachment.first;
49095ffd83dbSDimitry Andric     auto AllowLocs =
49105ffd83dbSDimitry Andric         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
49115ffd83dbSDimitry Andric             ? AreDebugLocsAllowed::Yes
49125ffd83dbSDimitry Andric             : AreDebugLocsAllowed::No;
49135ffd83dbSDimitry Andric     visitMDNode(*Attachment.second, AllowLocs);
49145ffd83dbSDimitry Andric   }
49155ffd83dbSDimitry Andric 
49160b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
49170b57cec5SDimitry Andric }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
49200b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
49210b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
492281ad6265SDimitry Andric   Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
49230b57cec5SDimitry Andric         IF);
49240b57cec5SDimitry Andric 
49250b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
49260b57cec5SDimitry Andric   // describe.
49270b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
49280b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
49290b57cec5SDimitry Andric 
49300b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
49310b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
49320b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
49330b57cec5SDimitry Andric 
49340b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
49350b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
49360b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
49370b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
493881ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
49390b57cec5SDimitry Andric         "Intrinsic has incorrect return type!", IF);
494081ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
49410b57cec5SDimitry Andric         "Intrinsic has incorrect argument type!", IF);
49420b57cec5SDimitry Andric 
49430b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
49440b57cec5SDimitry Andric   if (IsVarArg)
494581ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
49460b57cec5SDimitry Andric           "Intrinsic was not defined with variable arguments!", IF);
49470b57cec5SDimitry Andric   else
494881ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
49490b57cec5SDimitry Andric           "Callsite was not defined with variable arguments!", IF);
49500b57cec5SDimitry Andric 
49510b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
495281ad6265SDimitry Andric   Check(TableRef.empty(), "Intrinsic has too few arguments!", IF);
49530b57cec5SDimitry Andric 
49540b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
49550b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
49560b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
49570b57cec5SDimitry Andric   // the name.
4958fe6060f1SDimitry Andric   const std::string ExpectedName =
4959fe6060f1SDimitry Andric       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
496081ad6265SDimitry Andric   Check(ExpectedName == IF->getName(),
49610b57cec5SDimitry Andric         "Intrinsic name not mangled correctly for type arguments! "
49620b57cec5SDimitry Andric         "Should be: " +
49630b57cec5SDimitry Andric             ExpectedName,
49640b57cec5SDimitry Andric         IF);
49650b57cec5SDimitry Andric 
49660b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
49670b57cec5SDimitry Andric   // or are local to *this* function.
4968fe6060f1SDimitry Andric   for (Value *V : Call.args()) {
49690b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
49700b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
4971fe6060f1SDimitry Andric     if (auto *Const = dyn_cast<Constant>(V))
497281ad6265SDimitry Andric       Check(!Const->getType()->isX86_AMXTy(),
4973fe6060f1SDimitry Andric             "const x86_amx is not allowed in argument!");
4974fe6060f1SDimitry Andric   }
49750b57cec5SDimitry Andric 
49760b57cec5SDimitry Andric   switch (ID) {
49770b57cec5SDimitry Andric   default:
49780b57cec5SDimitry Andric     break;
49795ffd83dbSDimitry Andric   case Intrinsic::assume: {
49805ffd83dbSDimitry Andric     for (auto &Elem : Call.bundle_op_infos()) {
4981*bdd1243dSDimitry Andric       unsigned ArgCount = Elem.End - Elem.Begin;
4982*bdd1243dSDimitry Andric       // Separate storage assumptions are special insofar as they're the only
4983*bdd1243dSDimitry Andric       // operand bundles allowed on assumes that aren't parameter attributes.
4984*bdd1243dSDimitry Andric       if (Elem.Tag->getKey() == "separate_storage") {
4985*bdd1243dSDimitry Andric         Check(ArgCount == 2,
4986*bdd1243dSDimitry Andric               "separate_storage assumptions should have 2 arguments", Call);
4987*bdd1243dSDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
4988*bdd1243dSDimitry Andric                   Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
4989*bdd1243dSDimitry Andric               "arguments to separate_storage assumptions should be pointers",
4990*bdd1243dSDimitry Andric               Call);
4991*bdd1243dSDimitry Andric         return;
4992*bdd1243dSDimitry Andric       }
499381ad6265SDimitry Andric       Check(Elem.Tag->getKey() == "ignore" ||
49945ffd83dbSDimitry Andric                 Attribute::isExistingAttribute(Elem.Tag->getKey()),
4995349cc55cSDimitry Andric             "tags must be valid attribute names", Call);
49965ffd83dbSDimitry Andric       Attribute::AttrKind Kind =
49975ffd83dbSDimitry Andric           Attribute::getAttrKindFromName(Elem.Tag->getKey());
4998e8d8bef9SDimitry Andric       if (Kind == Attribute::Alignment) {
499981ad6265SDimitry Andric         Check(ArgCount <= 3 && ArgCount >= 2,
5000349cc55cSDimitry Andric               "alignment assumptions should have 2 or 3 arguments", Call);
500181ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
5002349cc55cSDimitry Andric               "first argument should be a pointer", Call);
500381ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
5004349cc55cSDimitry Andric               "second argument should be an integer", Call);
5005e8d8bef9SDimitry Andric         if (ArgCount == 3)
500681ad6265SDimitry Andric           Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
5007349cc55cSDimitry Andric                 "third argument should be an integer if present", Call);
5008e8d8bef9SDimitry Andric         return;
5009e8d8bef9SDimitry Andric       }
501081ad6265SDimitry Andric       Check(ArgCount <= 2, "too many arguments", Call);
50115ffd83dbSDimitry Andric       if (Kind == Attribute::None)
50125ffd83dbSDimitry Andric         break;
5013fe6060f1SDimitry Andric       if (Attribute::isIntAttrKind(Kind)) {
501481ad6265SDimitry Andric         Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
501581ad6265SDimitry Andric         Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
5016349cc55cSDimitry Andric               "the second argument should be a constant integral value", Call);
5017fe6060f1SDimitry Andric       } else if (Attribute::canUseAsParamAttr(Kind)) {
501881ad6265SDimitry Andric         Check((ArgCount) == 1, "this attribute should have one argument", Call);
5019fe6060f1SDimitry Andric       } else if (Attribute::canUseAsFnAttr(Kind)) {
502081ad6265SDimitry Andric         Check((ArgCount) == 0, "this attribute has no argument", Call);
50215ffd83dbSDimitry Andric       }
50225ffd83dbSDimitry Andric     }
50235ffd83dbSDimitry Andric     break;
50245ffd83dbSDimitry Andric   }
50250b57cec5SDimitry Andric   case Intrinsic::coro_id: {
50260b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
50270b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
50280b57cec5SDimitry Andric       break;
50290b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
503081ad6265SDimitry Andric     Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
5031fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to an initialized "
50320b57cec5SDimitry Andric           "constant");
50330b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
503481ad6265SDimitry Andric     Check(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
5035fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to either a struct or "
50360b57cec5SDimitry Andric           "an array");
50370b57cec5SDimitry Andric     break;
50380b57cec5SDimitry Andric   }
5039*bdd1243dSDimitry Andric   case Intrinsic::is_fpclass: {
5040*bdd1243dSDimitry Andric     const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
5041*bdd1243dSDimitry Andric     Check((TestMask->getZExtValue() & ~fcAllFlags) == 0,
5042*bdd1243dSDimitry Andric           "unsupported bits for llvm.is.fpclass test mask");
5043*bdd1243dSDimitry Andric     break;
5044*bdd1243dSDimitry Andric   }
504581ad6265SDimitry Andric   case Intrinsic::fptrunc_round: {
504681ad6265SDimitry Andric     // Check the rounding mode
504781ad6265SDimitry Andric     Metadata *MD = nullptr;
504881ad6265SDimitry Andric     auto *MAV = dyn_cast<MetadataAsValue>(Call.getOperand(1));
504981ad6265SDimitry Andric     if (MAV)
505081ad6265SDimitry Andric       MD = MAV->getMetadata();
505181ad6265SDimitry Andric 
505281ad6265SDimitry Andric     Check(MD != nullptr, "missing rounding mode argument", Call);
505381ad6265SDimitry Andric 
505481ad6265SDimitry Andric     Check(isa<MDString>(MD),
505581ad6265SDimitry Andric           ("invalid value for llvm.fptrunc.round metadata operand"
505681ad6265SDimitry Andric            " (the operand should be a string)"),
505781ad6265SDimitry Andric           MD);
505881ad6265SDimitry Andric 
5059*bdd1243dSDimitry Andric     std::optional<RoundingMode> RoundMode =
506081ad6265SDimitry Andric         convertStrToRoundingMode(cast<MDString>(MD)->getString());
506181ad6265SDimitry Andric     Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
506281ad6265SDimitry Andric           "unsupported rounding mode argument", Call);
506381ad6265SDimitry Andric     break;
506481ad6265SDimitry Andric   }
506581ad6265SDimitry Andric #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
506681ad6265SDimitry Andric #include "llvm/IR/VPIntrinsics.def"
506781ad6265SDimitry Andric     visitVPIntrinsic(cast<VPIntrinsic>(Call));
506881ad6265SDimitry Andric     break;
50695ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
5070480093f4SDimitry Andric   case Intrinsic::INTRINSIC:
5071480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
50720b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
50730b57cec5SDimitry Andric     break;
50740b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
507581ad6265SDimitry Andric     Check(isa<MetadataAsValue>(Call.getArgOperand(0)),
50760b57cec5SDimitry Andric           "invalid llvm.dbg.declare intrinsic call 1", Call);
50770b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
50780b57cec5SDimitry Andric     break;
50790b57cec5SDimitry Andric   case Intrinsic::dbg_addr: // llvm.dbg.addr
50800b57cec5SDimitry Andric     visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call));
50810b57cec5SDimitry Andric     break;
50820b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
50830b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
50840b57cec5SDimitry Andric     break;
5085*bdd1243dSDimitry Andric   case Intrinsic::dbg_assign: // llvm.dbg.assign
5086*bdd1243dSDimitry Andric     visitDbgIntrinsic("assign", cast<DbgVariableIntrinsic>(Call));
5087*bdd1243dSDimitry Andric     break;
50880b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
50890b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
50900b57cec5SDimitry Andric     break;
50910b57cec5SDimitry Andric   case Intrinsic::memcpy:
50925ffd83dbSDimitry Andric   case Intrinsic::memcpy_inline:
50930b57cec5SDimitry Andric   case Intrinsic::memmove:
509481ad6265SDimitry Andric   case Intrinsic::memset:
509581ad6265SDimitry Andric   case Intrinsic::memset_inline: {
50960b57cec5SDimitry Andric     break;
50970b57cec5SDimitry Andric   }
50980b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
50990b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
51000b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
51010b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
51020b57cec5SDimitry Andric 
51030b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
51040b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
51050b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
510681ad6265SDimitry Andric     Check(ElementSizeVal.isPowerOf2(),
51070b57cec5SDimitry Andric           "element size of the element-wise atomic memory intrinsic "
51080b57cec5SDimitry Andric           "must be a power of 2",
51090b57cec5SDimitry Andric           Call);
51100b57cec5SDimitry Andric 
5111*bdd1243dSDimitry Andric     auto IsValidAlignment = [&](MaybeAlign Alignment) {
5112*bdd1243dSDimitry Andric       return Alignment && ElementSizeVal.ule(Alignment->value());
51130b57cec5SDimitry Andric     };
5114*bdd1243dSDimitry Andric     Check(IsValidAlignment(AMI->getDestAlign()),
51150b57cec5SDimitry Andric           "incorrect alignment of the destination argument", Call);
51160b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
5117*bdd1243dSDimitry Andric       Check(IsValidAlignment(AMT->getSourceAlign()),
51180b57cec5SDimitry Andric             "incorrect alignment of the source argument", Call);
51190b57cec5SDimitry Andric     }
51200b57cec5SDimitry Andric     break;
51210b57cec5SDimitry Andric   }
51225ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_setup: {
51235ffd83dbSDimitry Andric     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
512481ad6265SDimitry Andric     Check(NumArgs != nullptr,
51255ffd83dbSDimitry Andric           "llvm.call.preallocated.setup argument must be a constant");
51265ffd83dbSDimitry Andric     bool FoundCall = false;
51275ffd83dbSDimitry Andric     for (User *U : Call.users()) {
51285ffd83dbSDimitry Andric       auto *UseCall = dyn_cast<CallBase>(U);
512981ad6265SDimitry Andric       Check(UseCall != nullptr,
51305ffd83dbSDimitry Andric             "Uses of llvm.call.preallocated.setup must be calls");
51315ffd83dbSDimitry Andric       const Function *Fn = UseCall->getCalledFunction();
51325ffd83dbSDimitry Andric       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
51335ffd83dbSDimitry Andric         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
513481ad6265SDimitry Andric         Check(AllocArgIndex != nullptr,
51355ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be a constant");
51365ffd83dbSDimitry Andric         auto AllocArgIndexInt = AllocArgIndex->getValue();
513781ad6265SDimitry Andric         Check(AllocArgIndexInt.sge(0) &&
51385ffd83dbSDimitry Andric                   AllocArgIndexInt.slt(NumArgs->getValue()),
51395ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be between 0 and "
51405ffd83dbSDimitry Andric               "corresponding "
51415ffd83dbSDimitry Andric               "llvm.call.preallocated.setup's argument count");
51425ffd83dbSDimitry Andric       } else if (Fn && Fn->getIntrinsicID() ==
51435ffd83dbSDimitry Andric                            Intrinsic::call_preallocated_teardown) {
51445ffd83dbSDimitry Andric         // nothing to do
51455ffd83dbSDimitry Andric       } else {
514681ad6265SDimitry Andric         Check(!FoundCall, "Can have at most one call corresponding to a "
51475ffd83dbSDimitry Andric                           "llvm.call.preallocated.setup");
51485ffd83dbSDimitry Andric         FoundCall = true;
51495ffd83dbSDimitry Andric         size_t NumPreallocatedArgs = 0;
5150349cc55cSDimitry Andric         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
51515ffd83dbSDimitry Andric           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
51525ffd83dbSDimitry Andric             ++NumPreallocatedArgs;
51535ffd83dbSDimitry Andric           }
51545ffd83dbSDimitry Andric         }
515581ad6265SDimitry Andric         Check(NumPreallocatedArgs != 0,
51565ffd83dbSDimitry Andric               "cannot use preallocated intrinsics on a call without "
51575ffd83dbSDimitry Andric               "preallocated arguments");
515881ad6265SDimitry Andric         Check(NumArgs->equalsInt(NumPreallocatedArgs),
51595ffd83dbSDimitry Andric               "llvm.call.preallocated.setup arg size must be equal to number "
51605ffd83dbSDimitry Andric               "of preallocated arguments "
51615ffd83dbSDimitry Andric               "at call site",
51625ffd83dbSDimitry Andric               Call, *UseCall);
51635ffd83dbSDimitry Andric         // getOperandBundle() cannot be called if more than one of the operand
51645ffd83dbSDimitry Andric         // bundle exists. There is already a check elsewhere for this, so skip
51655ffd83dbSDimitry Andric         // here if we see more than one.
51665ffd83dbSDimitry Andric         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
51675ffd83dbSDimitry Andric             1) {
51685ffd83dbSDimitry Andric           return;
51695ffd83dbSDimitry Andric         }
51705ffd83dbSDimitry Andric         auto PreallocatedBundle =
51715ffd83dbSDimitry Andric             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
517281ad6265SDimitry Andric         Check(PreallocatedBundle,
51735ffd83dbSDimitry Andric               "Use of llvm.call.preallocated.setup outside intrinsics "
51745ffd83dbSDimitry Andric               "must be in \"preallocated\" operand bundle");
517581ad6265SDimitry Andric         Check(PreallocatedBundle->Inputs.front().get() == &Call,
51765ffd83dbSDimitry Andric               "preallocated bundle must have token from corresponding "
51775ffd83dbSDimitry Andric               "llvm.call.preallocated.setup");
51785ffd83dbSDimitry Andric       }
51795ffd83dbSDimitry Andric     }
51805ffd83dbSDimitry Andric     break;
51815ffd83dbSDimitry Andric   }
51825ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_arg: {
51835ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
518481ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
51855ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
51865ffd83dbSDimitry Andric           "llvm.call.preallocated.arg token argument must be a "
51875ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
518881ad6265SDimitry Andric     Check(Call.hasFnAttr(Attribute::Preallocated),
51895ffd83dbSDimitry Andric           "llvm.call.preallocated.arg must be called with a \"preallocated\" "
51905ffd83dbSDimitry Andric           "call site attribute");
51915ffd83dbSDimitry Andric     break;
51925ffd83dbSDimitry Andric   }
51935ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_teardown: {
51945ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
519581ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
51965ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
51975ffd83dbSDimitry Andric           "llvm.call.preallocated.teardown token argument must be a "
51985ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
51995ffd83dbSDimitry Andric     break;
52005ffd83dbSDimitry Andric   }
52010b57cec5SDimitry Andric   case Intrinsic::gcroot:
52020b57cec5SDimitry Andric   case Intrinsic::gcwrite:
52030b57cec5SDimitry Andric   case Intrinsic::gcread:
52040b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
52050b57cec5SDimitry Andric       AllocaInst *AI =
52060b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
520781ad6265SDimitry Andric       Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
520881ad6265SDimitry Andric       Check(isa<Constant>(Call.getArgOperand(1)),
52090b57cec5SDimitry Andric             "llvm.gcroot parameter #2 must be a constant.", Call);
52100b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
521181ad6265SDimitry Andric         Check(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
52120b57cec5SDimitry Andric               "llvm.gcroot parameter #1 must either be a pointer alloca, "
52130b57cec5SDimitry Andric               "or argument #2 must be a non-null constant.",
52140b57cec5SDimitry Andric               Call);
52150b57cec5SDimitry Andric       }
52160b57cec5SDimitry Andric     }
52170b57cec5SDimitry Andric 
521881ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
52190b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
52200b57cec5SDimitry Andric     break;
52210b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
522281ad6265SDimitry Andric     Check(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
52230b57cec5SDimitry Andric           "llvm.init_trampoline parameter #2 must resolve to a function.",
52240b57cec5SDimitry Andric           Call);
52250b57cec5SDimitry Andric     break;
52260b57cec5SDimitry Andric   case Intrinsic::prefetch:
5227*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5228*bdd1243dSDimitry Andric           "rw argument to llvm.prefetch must be 0-1", Call);
5229*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
5230*bdd1243dSDimitry Andric           "locality argument to llvm.prefetch must be 0-4", Call);
5231*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5232*bdd1243dSDimitry Andric           "cache type argument to llvm.prefetch must be 0-1", Call);
52330b57cec5SDimitry Andric     break;
52340b57cec5SDimitry Andric   case Intrinsic::stackprotector:
523581ad6265SDimitry Andric     Check(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
52360b57cec5SDimitry Andric           "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
52370b57cec5SDimitry Andric     break;
52380b57cec5SDimitry Andric   case Intrinsic::localescape: {
52390b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
5240*bdd1243dSDimitry Andric     Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
5241*bdd1243dSDimitry Andric           Call);
524281ad6265SDimitry Andric     Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
524381ad6265SDimitry Andric           Call);
52440b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
52450b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
52460b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
52470b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
524881ad6265SDimitry Andric       Check(AI && AI->isStaticAlloca(),
52490b57cec5SDimitry Andric             "llvm.localescape only accepts static allocas", Call);
52500b57cec5SDimitry Andric     }
5251349cc55cSDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
52520b57cec5SDimitry Andric     SawFrameEscape = true;
52530b57cec5SDimitry Andric     break;
52540b57cec5SDimitry Andric   }
52550b57cec5SDimitry Andric   case Intrinsic::localrecover: {
52560b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
52570b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
525881ad6265SDimitry Andric     Check(Fn && !Fn->isDeclaration(),
52590b57cec5SDimitry Andric           "llvm.localrecover first "
52600b57cec5SDimitry Andric           "argument must be function defined in this module",
52610b57cec5SDimitry Andric           Call);
52620b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
52630b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
52640b57cec5SDimitry Andric     Entry.second = unsigned(
52650b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
52660b57cec5SDimitry Andric     break;
52670b57cec5SDimitry Andric   }
52680b57cec5SDimitry Andric 
52690b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
52700b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
527181ad6265SDimitry Andric       Check(!CI->isInlineAsm(),
52720b57cec5SDimitry Andric             "gc.statepoint support for inline assembly unimplemented", CI);
527381ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
52740b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
52750b57cec5SDimitry Andric 
52760b57cec5SDimitry Andric     verifyStatepoint(Call);
52770b57cec5SDimitry Andric     break;
52780b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
527981ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
52800b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
5281*bdd1243dSDimitry Andric 
5282*bdd1243dSDimitry Andric     auto *Statepoint = Call.getArgOperand(0);
5283*bdd1243dSDimitry Andric     if (isa<UndefValue>(Statepoint))
5284*bdd1243dSDimitry Andric       break;
5285*bdd1243dSDimitry Andric 
52860b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
5287*bdd1243dSDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
52880b57cec5SDimitry Andric     const Function *StatepointFn =
52890b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
529081ad6265SDimitry Andric     Check(StatepointFn && StatepointFn->isDeclaration() &&
52910b57cec5SDimitry Andric               StatepointFn->getIntrinsicID() ==
52920b57cec5SDimitry Andric                   Intrinsic::experimental_gc_statepoint,
52930b57cec5SDimitry Andric           "gc.result operand #1 must be from a statepoint", Call,
52940b57cec5SDimitry Andric           Call.getArgOperand(0));
52950b57cec5SDimitry Andric 
529681ad6265SDimitry Andric     // Check that result type matches wrapped callee.
529781ad6265SDimitry Andric     auto *TargetFuncType =
529881ad6265SDimitry Andric         cast<FunctionType>(StatepointCall->getParamElementType(2));
529981ad6265SDimitry Andric     Check(Call.getType() == TargetFuncType->getReturnType(),
53000b57cec5SDimitry Andric           "gc.result result type does not match wrapped callee", Call);
53010b57cec5SDimitry Andric     break;
53020b57cec5SDimitry Andric   }
53030b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
530481ad6265SDimitry Andric     Check(Call.arg_size() == 3, "wrong number of arguments", Call);
53050b57cec5SDimitry Andric 
530681ad6265SDimitry Andric     Check(isa<PointerType>(Call.getType()->getScalarType()),
53070b57cec5SDimitry Andric           "gc.relocate must return a pointer or a vector of pointers", Call);
53080b57cec5SDimitry Andric 
53090b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
53120b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
53130b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
53140b57cec5SDimitry Andric 
53150b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
53160b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
53170b57cec5SDimitry Andric 
53180b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
53190b57cec5SDimitry Andric       // statepoint terminator
532081ad6265SDimitry Andric       Check(InvokeBB, "safepoints should have unique landingpads",
53210b57cec5SDimitry Andric             LandingPad->getParent());
532281ad6265SDimitry Andric       Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
53230b57cec5SDimitry Andric             InvokeBB);
532481ad6265SDimitry Andric       Check(isa<GCStatepointInst>(InvokeBB->getTerminator()),
53250b57cec5SDimitry Andric             "gc relocate should be linked to a statepoint", InvokeBB);
53260b57cec5SDimitry Andric     } else {
53270b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
53280b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
53290b57cec5SDimitry Andric       // relocates of a call statepoint.
5330fcaf7f86SDimitry Andric       auto *Token = Call.getArgOperand(0);
5331fcaf7f86SDimitry Andric       Check(isa<GCStatepointInst>(Token) || isa<UndefValue>(Token),
53320b57cec5SDimitry Andric             "gc relocate is incorrectly tied to the statepoint", Call, Token);
53330b57cec5SDimitry Andric     }
53340b57cec5SDimitry Andric 
53350b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
5336fcaf7f86SDimitry Andric     const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
53370b57cec5SDimitry Andric 
53380b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
53390b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
534081ad6265SDimitry Andric     Check(isa<ConstantInt>(Base),
53410b57cec5SDimitry Andric           "gc.relocate operand #2 must be integer offset", Call);
53420b57cec5SDimitry Andric 
53430b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
534481ad6265SDimitry Andric     Check(isa<ConstantInt>(Derived),
53450b57cec5SDimitry Andric           "gc.relocate operand #3 must be integer offset", Call);
53460b57cec5SDimitry Andric 
53475ffd83dbSDimitry Andric     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
53485ffd83dbSDimitry Andric     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
53495ffd83dbSDimitry Andric 
53500b57cec5SDimitry Andric     // Check the bounds
5351fcaf7f86SDimitry Andric     if (isa<UndefValue>(StatepointCall))
5352fcaf7f86SDimitry Andric       break;
5353fcaf7f86SDimitry Andric     if (auto Opt = cast<GCStatepointInst>(StatepointCall)
5354fcaf7f86SDimitry Andric                        .getOperandBundle(LLVMContext::OB_gc_live)) {
535581ad6265SDimitry Andric       Check(BaseIndex < Opt->Inputs.size(),
53560b57cec5SDimitry Andric             "gc.relocate: statepoint base index out of bounds", Call);
535781ad6265SDimitry Andric       Check(DerivedIndex < Opt->Inputs.size(),
53585ffd83dbSDimitry Andric             "gc.relocate: statepoint derived index out of bounds", Call);
53595ffd83dbSDimitry Andric     }
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
53620b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
53630b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
53640b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
53650b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5366*bdd1243dSDimitry Andric     auto *ResultType = Call.getType();
5367*bdd1243dSDimitry Andric     auto *DerivedType = Relocate.getDerivedPtr()->getType();
5368*bdd1243dSDimitry Andric     auto *BaseType = Relocate.getBasePtr()->getType();
53690b57cec5SDimitry Andric 
5370*bdd1243dSDimitry Andric     Check(BaseType->isPtrOrPtrVectorTy(),
5371*bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5372*bdd1243dSDimitry Andric     Check(DerivedType->isPtrOrPtrVectorTy(),
5373*bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5374*bdd1243dSDimitry Andric 
537581ad6265SDimitry Andric     Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
53760b57cec5SDimitry Andric           "gc.relocate: vector relocates to vector and pointer to pointer",
53770b57cec5SDimitry Andric           Call);
537881ad6265SDimitry Andric     Check(
53790b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
53800b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
53810b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
53820b57cec5SDimitry Andric         Call);
5383*bdd1243dSDimitry Andric 
5384*bdd1243dSDimitry Andric     auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
5385*bdd1243dSDimitry Andric     Check(GC, "gc.relocate: calling function must have GCStrategy",
5386*bdd1243dSDimitry Andric           Call.getFunction());
5387*bdd1243dSDimitry Andric     if (GC) {
5388*bdd1243dSDimitry Andric       auto isGCPtr = [&GC](Type *PTy) {
5389*bdd1243dSDimitry Andric         return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
5390*bdd1243dSDimitry Andric       };
5391*bdd1243dSDimitry Andric       Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
5392*bdd1243dSDimitry Andric       Check(isGCPtr(BaseType),
5393*bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5394*bdd1243dSDimitry Andric       Check(isGCPtr(DerivedType),
5395*bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5396*bdd1243dSDimitry Andric     }
53970b57cec5SDimitry Andric     break;
53980b57cec5SDimitry Andric   }
53990b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
54000b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
540181ad6265SDimitry Andric     Check(isa<CatchPadInst>(Call.getArgOperand(0)),
54020b57cec5SDimitry Andric           "eh.exceptionpointer argument must be a catchpad", Call);
54030b57cec5SDimitry Andric     break;
54040b57cec5SDimitry Andric   }
54055ffd83dbSDimitry Andric   case Intrinsic::get_active_lane_mask: {
540681ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(),
540781ad6265SDimitry Andric           "get_active_lane_mask: must return a "
540881ad6265SDimitry Andric           "vector",
540981ad6265SDimitry Andric           Call);
54105ffd83dbSDimitry Andric     auto *ElemTy = Call.getType()->getScalarType();
541181ad6265SDimitry Andric     Check(ElemTy->isIntegerTy(1),
541281ad6265SDimitry Andric           "get_active_lane_mask: element type is not "
541381ad6265SDimitry Andric           "i1",
541481ad6265SDimitry Andric           Call);
54155ffd83dbSDimitry Andric     break;
54165ffd83dbSDimitry Andric   }
54170b57cec5SDimitry Andric   case Intrinsic::masked_load: {
541881ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
54190b57cec5SDimitry Andric           Call);
54200b57cec5SDimitry Andric 
54210b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(0);
54220b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
54230b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
54240b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
542581ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
54260b57cec5SDimitry Andric           Call);
542781ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
54280b57cec5SDimitry Andric           "masked_load: alignment must be a power of 2", Call);
54290b57cec5SDimitry Andric 
5430fe6060f1SDimitry Andric     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
543181ad6265SDimitry Andric     Check(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()),
54320b57cec5SDimitry Andric           "masked_load: return must match pointer type", Call);
543381ad6265SDimitry Andric     Check(PassThru->getType() == Call.getType(),
5434fe6060f1SDimitry Andric           "masked_load: pass through and return type must match", Call);
543581ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5436fe6060f1SDimitry Andric               cast<VectorType>(Call.getType())->getElementCount(),
5437fe6060f1SDimitry Andric           "masked_load: vector mask must be same length as return", Call);
54380b57cec5SDimitry Andric     break;
54390b57cec5SDimitry Andric   }
54400b57cec5SDimitry Andric   case Intrinsic::masked_store: {
54410b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
54420b57cec5SDimitry Andric     Value *Ptr = Call.getArgOperand(1);
54430b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
54440b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
544581ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
54460b57cec5SDimitry Andric           Call);
544781ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
54480b57cec5SDimitry Andric           "masked_store: alignment must be a power of 2", Call);
54490b57cec5SDimitry Andric 
5450fe6060f1SDimitry Andric     PointerType *PtrTy = cast<PointerType>(Ptr->getType());
545181ad6265SDimitry Andric     Check(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()),
54520b57cec5SDimitry Andric           "masked_store: storee must match pointer type", Call);
545381ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5454fe6060f1SDimitry Andric               cast<VectorType>(Val->getType())->getElementCount(),
5455fe6060f1SDimitry Andric           "masked_store: vector mask must be same length as value", Call);
54560b57cec5SDimitry Andric     break;
54570b57cec5SDimitry Andric   }
54580b57cec5SDimitry Andric 
54595ffd83dbSDimitry Andric   case Intrinsic::masked_gather: {
54605ffd83dbSDimitry Andric     const APInt &Alignment =
54615ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
546281ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
54635ffd83dbSDimitry Andric           "masked_gather: alignment must be 0 or a power of 2", Call);
54645ffd83dbSDimitry Andric     break;
54655ffd83dbSDimitry Andric   }
54665ffd83dbSDimitry Andric   case Intrinsic::masked_scatter: {
54675ffd83dbSDimitry Andric     const APInt &Alignment =
54685ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
546981ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
54705ffd83dbSDimitry Andric           "masked_scatter: alignment must be 0 or a power of 2", Call);
54715ffd83dbSDimitry Andric     break;
54725ffd83dbSDimitry Andric   }
54735ffd83dbSDimitry Andric 
54740b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
547581ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
547681ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
54770b57cec5SDimitry Andric           "experimental_guard must have exactly one "
54780b57cec5SDimitry Andric           "\"deopt\" operand bundle");
54790b57cec5SDimitry Andric     break;
54800b57cec5SDimitry Andric   }
54810b57cec5SDimitry Andric 
54820b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
548381ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
54840b57cec5SDimitry Andric           Call);
548581ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
54860b57cec5SDimitry Andric           "experimental_deoptimize must have exactly one "
54870b57cec5SDimitry Andric           "\"deopt\" operand bundle");
548881ad6265SDimitry Andric     Check(Call.getType() == Call.getFunction()->getReturnType(),
54890b57cec5SDimitry Andric           "experimental_deoptimize return type must match caller return type");
54900b57cec5SDimitry Andric 
54910b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
54920b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
549381ad6265SDimitry Andric       Check(RI,
54940b57cec5SDimitry Andric             "calls to experimental_deoptimize must be followed by a return");
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
549781ad6265SDimitry Andric         Check(RI->getReturnValue() == &Call,
54980b57cec5SDimitry Andric               "calls to experimental_deoptimize must be followed by a return "
54990b57cec5SDimitry Andric               "of the value computed by experimental_deoptimize");
55000b57cec5SDimitry Andric     }
55010b57cec5SDimitry Andric 
55020b57cec5SDimitry Andric     break;
55030b57cec5SDimitry Andric   }
5504fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_and:
5505fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_or:
5506fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_xor:
5507fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_add:
5508fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_mul:
5509fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smax:
5510fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smin:
5511fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umax:
5512fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umin: {
5513fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
551481ad6265SDimitry Andric     Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5515fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5516fe6060f1SDimitry Andric     break;
5517fe6060f1SDimitry Andric   }
5518fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmax:
5519fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmin: {
5520fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
552181ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5522fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5523fe6060f1SDimitry Andric     break;
5524fe6060f1SDimitry Andric   }
5525fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fadd:
5526fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmul: {
5527fe6060f1SDimitry Andric     // Unlike the other reductions, the first argument is a start value. The
5528fe6060f1SDimitry Andric     // second argument is the vector to be reduced.
5529fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(1)->getType();
553081ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5531fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
55320b57cec5SDimitry Andric     break;
55330b57cec5SDimitry Andric   }
55340b57cec5SDimitry Andric   case Intrinsic::smul_fix:
55350b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
55368bcb0991SDimitry Andric   case Intrinsic::umul_fix:
5537480093f4SDimitry Andric   case Intrinsic::umul_fix_sat:
5538480093f4SDimitry Andric   case Intrinsic::sdiv_fix:
55395ffd83dbSDimitry Andric   case Intrinsic::sdiv_fix_sat:
55405ffd83dbSDimitry Andric   case Intrinsic::udiv_fix:
55415ffd83dbSDimitry Andric   case Intrinsic::udiv_fix_sat: {
55420b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
55430b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
554481ad6265SDimitry Andric     Check(Op1->getType()->isIntOrIntVectorTy(),
5545480093f4SDimitry Andric           "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5546480093f4SDimitry Andric           "vector of ints");
554781ad6265SDimitry Andric     Check(Op2->getType()->isIntOrIntVectorTy(),
5548480093f4SDimitry Andric           "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5549480093f4SDimitry Andric           "vector of ints");
55500b57cec5SDimitry Andric 
55510b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
555281ad6265SDimitry Andric     Check(Op3->getType()->getBitWidth() <= 32,
5553480093f4SDimitry Andric           "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
55540b57cec5SDimitry Andric 
5555480093f4SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
55565ffd83dbSDimitry Andric         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
555781ad6265SDimitry Andric       Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5558480093f4SDimitry Andric             "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5559480093f4SDimitry Andric             "the operands");
55600b57cec5SDimitry Andric     } else {
556181ad6265SDimitry Andric       Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5562480093f4SDimitry Andric             "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5563480093f4SDimitry Andric             "to the width of the operands");
55640b57cec5SDimitry Andric     }
55650b57cec5SDimitry Andric     break;
55660b57cec5SDimitry Andric   }
55670b57cec5SDimitry Andric   case Intrinsic::lround:
55680b57cec5SDimitry Andric   case Intrinsic::llround:
55690b57cec5SDimitry Andric   case Intrinsic::lrint:
55700b57cec5SDimitry Andric   case Intrinsic::llrint: {
55710b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
55720b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
557381ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
55740b57cec5SDimitry Andric           "Intrinsic does not support vectors", &Call);
55750b57cec5SDimitry Andric     break;
55760b57cec5SDimitry Andric   }
55775ffd83dbSDimitry Andric   case Intrinsic::bswap: {
55785ffd83dbSDimitry Andric     Type *Ty = Call.getType();
55795ffd83dbSDimitry Andric     unsigned Size = Ty->getScalarSizeInBits();
558081ad6265SDimitry Andric     Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
55815ffd83dbSDimitry Andric     break;
55825ffd83dbSDimitry Andric   }
5583e8d8bef9SDimitry Andric   case Intrinsic::invariant_start: {
5584e8d8bef9SDimitry Andric     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
558581ad6265SDimitry Andric     Check(InvariantSize &&
5586e8d8bef9SDimitry Andric               (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5587e8d8bef9SDimitry Andric           "invariant_start parameter must be -1, 0 or a positive number",
5588e8d8bef9SDimitry Andric           &Call);
5589e8d8bef9SDimitry Andric     break;
5590e8d8bef9SDimitry Andric   }
55915ffd83dbSDimitry Andric   case Intrinsic::matrix_multiply:
55925ffd83dbSDimitry Andric   case Intrinsic::matrix_transpose:
55935ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_load:
55945ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_store: {
55955ffd83dbSDimitry Andric     Function *IF = Call.getCalledFunction();
55965ffd83dbSDimitry Andric     ConstantInt *Stride = nullptr;
55975ffd83dbSDimitry Andric     ConstantInt *NumRows;
55985ffd83dbSDimitry Andric     ConstantInt *NumColumns;
55995ffd83dbSDimitry Andric     VectorType *ResultTy;
56005ffd83dbSDimitry Andric     Type *Op0ElemTy = nullptr;
56015ffd83dbSDimitry Andric     Type *Op1ElemTy = nullptr;
56025ffd83dbSDimitry Andric     switch (ID) {
56035ffd83dbSDimitry Andric     case Intrinsic::matrix_multiply:
56045ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
56055ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
56065ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
56075ffd83dbSDimitry Andric       Op0ElemTy =
56085ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
56095ffd83dbSDimitry Andric       Op1ElemTy =
56105ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
56115ffd83dbSDimitry Andric       break;
56125ffd83dbSDimitry Andric     case Intrinsic::matrix_transpose:
56135ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
56145ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
56155ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
56165ffd83dbSDimitry Andric       Op0ElemTy =
56175ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
56185ffd83dbSDimitry Andric       break;
56194824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_load: {
56205ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
56215ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
56225ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
56235ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
56244824e7fdSDimitry Andric 
56254824e7fdSDimitry Andric       PointerType *Op0PtrTy =
56264824e7fdSDimitry Andric           cast<PointerType>(Call.getArgOperand(0)->getType());
56274824e7fdSDimitry Andric       if (!Op0PtrTy->isOpaque())
562804eeddc0SDimitry Andric         Op0ElemTy = Op0PtrTy->getNonOpaquePointerElementType();
56295ffd83dbSDimitry Andric       break;
56304824e7fdSDimitry Andric     }
56314824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_store: {
56325ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
56335ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
56345ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
56355ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
56365ffd83dbSDimitry Andric       Op0ElemTy =
56375ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
56384824e7fdSDimitry Andric 
56394824e7fdSDimitry Andric       PointerType *Op1PtrTy =
56404824e7fdSDimitry Andric           cast<PointerType>(Call.getArgOperand(1)->getType());
56414824e7fdSDimitry Andric       if (!Op1PtrTy->isOpaque())
564204eeddc0SDimitry Andric         Op1ElemTy = Op1PtrTy->getNonOpaquePointerElementType();
56435ffd83dbSDimitry Andric       break;
56444824e7fdSDimitry Andric     }
56455ffd83dbSDimitry Andric     default:
56465ffd83dbSDimitry Andric       llvm_unreachable("unexpected intrinsic");
56475ffd83dbSDimitry Andric     }
56485ffd83dbSDimitry Andric 
564981ad6265SDimitry Andric     Check(ResultTy->getElementType()->isIntegerTy() ||
56505ffd83dbSDimitry Andric               ResultTy->getElementType()->isFloatingPointTy(),
56515ffd83dbSDimitry Andric           "Result type must be an integer or floating-point type!", IF);
56525ffd83dbSDimitry Andric 
56534824e7fdSDimitry Andric     if (Op0ElemTy)
565481ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op0ElemTy,
56555ffd83dbSDimitry Andric             "Vector element type mismatch of the result and first operand "
565681ad6265SDimitry Andric             "vector!",
565781ad6265SDimitry Andric             IF);
56585ffd83dbSDimitry Andric 
56595ffd83dbSDimitry Andric     if (Op1ElemTy)
566081ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op1ElemTy,
56615ffd83dbSDimitry Andric             "Vector element type mismatch of the result and second operand "
566281ad6265SDimitry Andric             "vector!",
566381ad6265SDimitry Andric             IF);
56645ffd83dbSDimitry Andric 
566581ad6265SDimitry Andric     Check(cast<FixedVectorType>(ResultTy)->getNumElements() ==
56665ffd83dbSDimitry Andric               NumRows->getZExtValue() * NumColumns->getZExtValue(),
56675ffd83dbSDimitry Andric           "Result of a matrix operation does not fit in the returned vector!");
56685ffd83dbSDimitry Andric 
56695ffd83dbSDimitry Andric     if (Stride)
567081ad6265SDimitry Andric       Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
56715ffd83dbSDimitry Andric             "Stride must be greater or equal than the number of rows!", IF);
56725ffd83dbSDimitry Andric 
56735ffd83dbSDimitry Andric     break;
56745ffd83dbSDimitry Andric   }
567504eeddc0SDimitry Andric   case Intrinsic::experimental_vector_splice: {
567604eeddc0SDimitry Andric     VectorType *VecTy = cast<VectorType>(Call.getType());
567704eeddc0SDimitry Andric     int64_t Idx = cast<ConstantInt>(Call.getArgOperand(2))->getSExtValue();
567804eeddc0SDimitry Andric     int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
567904eeddc0SDimitry Andric     if (Call.getParent() && Call.getParent()->getParent()) {
568004eeddc0SDimitry Andric       AttributeList Attrs = Call.getParent()->getParent()->getAttributes();
568104eeddc0SDimitry Andric       if (Attrs.hasFnAttr(Attribute::VScaleRange))
568204eeddc0SDimitry Andric         KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
568304eeddc0SDimitry Andric     }
568481ad6265SDimitry Andric     Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
568504eeddc0SDimitry Andric               (Idx >= 0 && Idx < KnownMinNumElements),
568604eeddc0SDimitry Andric           "The splice index exceeds the range [-VL, VL-1] where VL is the "
568704eeddc0SDimitry Andric           "known minimum number of elements in the vector. For scalable "
568804eeddc0SDimitry Andric           "vectors the minimum number of elements is determined from "
568904eeddc0SDimitry Andric           "vscale_range.",
569004eeddc0SDimitry Andric           &Call);
569104eeddc0SDimitry Andric     break;
569204eeddc0SDimitry Andric   }
5693fe6060f1SDimitry Andric   case Intrinsic::experimental_stepvector: {
5694fe6060f1SDimitry Andric     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
569581ad6265SDimitry Andric     Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5696fe6060f1SDimitry Andric               VecTy->getScalarSizeInBits() >= 8,
5697fe6060f1SDimitry Andric           "experimental_stepvector only supported for vectors of integers "
5698fe6060f1SDimitry Andric           "with a bitwidth of at least 8.",
5699fe6060f1SDimitry Andric           &Call);
5700fe6060f1SDimitry Andric     break;
5701fe6060f1SDimitry Andric   }
570281ad6265SDimitry Andric   case Intrinsic::vector_insert: {
5703fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5704fe6060f1SDimitry Andric     Value *SubVec = Call.getArgOperand(1);
5705fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(2);
5706fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5707e8d8bef9SDimitry Andric 
5708fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5709fe6060f1SDimitry Andric     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5710fe6060f1SDimitry Andric 
5711fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5712fe6060f1SDimitry Andric     ElementCount SubVecEC = SubVecTy->getElementCount();
571381ad6265SDimitry Andric     Check(VecTy->getElementType() == SubVecTy->getElementType(),
571481ad6265SDimitry Andric           "vector_insert parameters must have the same element "
5715e8d8bef9SDimitry Andric           "type.",
5716e8d8bef9SDimitry Andric           &Call);
571781ad6265SDimitry Andric     Check(IdxN % SubVecEC.getKnownMinValue() == 0,
571881ad6265SDimitry Andric           "vector_insert index must be a constant multiple of "
5719fe6060f1SDimitry Andric           "the subvector's known minimum vector length.");
5720fe6060f1SDimitry Andric 
5721fe6060f1SDimitry Andric     // If this insertion is not the 'mixed' case where a fixed vector is
5722fe6060f1SDimitry Andric     // inserted into a scalable vector, ensure that the insertion of the
5723fe6060f1SDimitry Andric     // subvector does not overrun the parent vector.
5724fe6060f1SDimitry Andric     if (VecEC.isScalable() == SubVecEC.isScalable()) {
572581ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
5726fe6060f1SDimitry Andric                 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
572781ad6265SDimitry Andric             "subvector operand of vector_insert would overrun the "
5728fe6060f1SDimitry Andric             "vector being inserted into.");
5729fe6060f1SDimitry Andric     }
5730e8d8bef9SDimitry Andric     break;
5731e8d8bef9SDimitry Andric   }
573281ad6265SDimitry Andric   case Intrinsic::vector_extract: {
5733fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5734fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(1);
5735fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5736fe6060f1SDimitry Andric 
5737e8d8bef9SDimitry Andric     VectorType *ResultTy = cast<VectorType>(Call.getType());
5738fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5739fe6060f1SDimitry Andric 
5740fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5741fe6060f1SDimitry Andric     ElementCount ResultEC = ResultTy->getElementCount();
5742e8d8bef9SDimitry Andric 
574381ad6265SDimitry Andric     Check(ResultTy->getElementType() == VecTy->getElementType(),
574481ad6265SDimitry Andric           "vector_extract result must have the same element "
5745e8d8bef9SDimitry Andric           "type as the input vector.",
5746e8d8bef9SDimitry Andric           &Call);
574781ad6265SDimitry Andric     Check(IdxN % ResultEC.getKnownMinValue() == 0,
574881ad6265SDimitry Andric           "vector_extract index must be a constant multiple of "
5749fe6060f1SDimitry Andric           "the result type's known minimum vector length.");
5750fe6060f1SDimitry Andric 
5751fe6060f1SDimitry Andric     // If this extraction is not the 'mixed' case where a fixed vector is is
5752fe6060f1SDimitry Andric     // extracted from a scalable vector, ensure that the extraction does not
5753fe6060f1SDimitry Andric     // overrun the parent vector.
5754fe6060f1SDimitry Andric     if (VecEC.isScalable() == ResultEC.isScalable()) {
575581ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
5756fe6060f1SDimitry Andric                 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
575781ad6265SDimitry Andric             "vector_extract would overrun.");
5758fe6060f1SDimitry Andric     }
5759e8d8bef9SDimitry Andric     break;
5760e8d8bef9SDimitry Andric   }
5761e8d8bef9SDimitry Andric   case Intrinsic::experimental_noalias_scope_decl: {
5762e8d8bef9SDimitry Andric     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5763e8d8bef9SDimitry Andric     break;
5764e8d8bef9SDimitry Andric   }
5765fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
576681ad6265SDimitry Andric   case Intrinsic::preserve_struct_access_index:
576781ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
576881ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
576981ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
577081ad6265SDimitry Andric   case Intrinsic::arm_ldrex: {
577181ad6265SDimitry Andric     Type *ElemTy = Call.getParamElementType(0);
577281ad6265SDimitry Andric     Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
577381ad6265SDimitry Andric           &Call);
577481ad6265SDimitry Andric     break;
577581ad6265SDimitry Andric   }
577681ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
577781ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
577881ad6265SDimitry Andric   case Intrinsic::arm_stlex:
577981ad6265SDimitry Andric   case Intrinsic::arm_strex: {
578081ad6265SDimitry Andric     Type *ElemTy = Call.getAttributes().getParamElementType(1);
578181ad6265SDimitry Andric     Check(ElemTy,
578281ad6265SDimitry Andric           "Intrinsic requires elementtype attribute on second argument.",
5783fe6060f1SDimitry Andric           &Call);
5784fe6060f1SDimitry Andric     break;
5785fe6060f1SDimitry Andric   }
5786*bdd1243dSDimitry Andric   case Intrinsic::aarch64_prefetch: {
5787*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5788*bdd1243dSDimitry Andric           "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5789*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
5790*bdd1243dSDimitry Andric           "target argument to llvm.aarch64.prefetch must be 0-3", Call);
5791*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5792*bdd1243dSDimitry Andric           "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5793*bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
5794*bdd1243dSDimitry Andric           "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5795*bdd1243dSDimitry Andric     break;
5796*bdd1243dSDimitry Andric   }
57970b57cec5SDimitry Andric   };
57980b57cec5SDimitry Andric }
57990b57cec5SDimitry Andric 
58000b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
58010b57cec5SDimitry Andric ///
58020b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
58030b57cec5SDimitry Andric /// built-in assertions that would typically fire.
58040b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
58050b57cec5SDimitry Andric   if (!LocalScope)
58060b57cec5SDimitry Andric     return nullptr;
58070b57cec5SDimitry Andric 
58080b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
58090b57cec5SDimitry Andric     return SP;
58100b57cec5SDimitry Andric 
58110b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
58120b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
58130b57cec5SDimitry Andric 
58140b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
58150b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
58160b57cec5SDimitry Andric   return nullptr;
58170b57cec5SDimitry Andric }
58180b57cec5SDimitry Andric 
581981ad6265SDimitry Andric void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
582081ad6265SDimitry Andric   if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
582181ad6265SDimitry Andric     auto *RetTy = cast<VectorType>(VPCast->getType());
582281ad6265SDimitry Andric     auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
582381ad6265SDimitry Andric     Check(RetTy->getElementCount() == ValTy->getElementCount(),
582481ad6265SDimitry Andric           "VP cast intrinsic first argument and result vector lengths must be "
582581ad6265SDimitry Andric           "equal",
582681ad6265SDimitry Andric           *VPCast);
582781ad6265SDimitry Andric 
582881ad6265SDimitry Andric     switch (VPCast->getIntrinsicID()) {
582981ad6265SDimitry Andric     default:
583081ad6265SDimitry Andric       llvm_unreachable("Unknown VP cast intrinsic");
583181ad6265SDimitry Andric     case Intrinsic::vp_trunc:
583281ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
583381ad6265SDimitry Andric             "llvm.vp.trunc intrinsic first argument and result element type "
583481ad6265SDimitry Andric             "must be integer",
583581ad6265SDimitry Andric             *VPCast);
583681ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
583781ad6265SDimitry Andric             "llvm.vp.trunc intrinsic the bit size of first argument must be "
583881ad6265SDimitry Andric             "larger than the bit size of the return type",
583981ad6265SDimitry Andric             *VPCast);
584081ad6265SDimitry Andric       break;
584181ad6265SDimitry Andric     case Intrinsic::vp_zext:
584281ad6265SDimitry Andric     case Intrinsic::vp_sext:
584381ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
584481ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
584581ad6265SDimitry Andric             "element type must be integer",
584681ad6265SDimitry Andric             *VPCast);
584781ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
584881ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
584981ad6265SDimitry Andric             "argument must be smaller than the bit size of the return type",
585081ad6265SDimitry Andric             *VPCast);
585181ad6265SDimitry Andric       break;
585281ad6265SDimitry Andric     case Intrinsic::vp_fptoui:
585381ad6265SDimitry Andric     case Intrinsic::vp_fptosi:
585481ad6265SDimitry Andric       Check(
585581ad6265SDimitry Andric           RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
585681ad6265SDimitry Andric           "llvm.vp.fptoui or llvm.vp.fptosi intrinsic first argument element "
585781ad6265SDimitry Andric           "type must be floating-point and result element type must be integer",
585881ad6265SDimitry Andric           *VPCast);
585981ad6265SDimitry Andric       break;
586081ad6265SDimitry Andric     case Intrinsic::vp_uitofp:
586181ad6265SDimitry Andric     case Intrinsic::vp_sitofp:
586281ad6265SDimitry Andric       Check(
586381ad6265SDimitry Andric           RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
586481ad6265SDimitry Andric           "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
586581ad6265SDimitry Andric           "type must be integer and result element type must be floating-point",
586681ad6265SDimitry Andric           *VPCast);
586781ad6265SDimitry Andric       break;
586881ad6265SDimitry Andric     case Intrinsic::vp_fptrunc:
586981ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
587081ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic first argument and result element type "
587181ad6265SDimitry Andric             "must be floating-point",
587281ad6265SDimitry Andric             *VPCast);
587381ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
587481ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
587581ad6265SDimitry Andric             "larger than the bit size of the return type",
587681ad6265SDimitry Andric             *VPCast);
587781ad6265SDimitry Andric       break;
587881ad6265SDimitry Andric     case Intrinsic::vp_fpext:
587981ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
588081ad6265SDimitry Andric             "llvm.vp.fpext intrinsic first argument and result element type "
588181ad6265SDimitry Andric             "must be floating-point",
588281ad6265SDimitry Andric             *VPCast);
588381ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
588481ad6265SDimitry Andric             "llvm.vp.fpext intrinsic the bit size of first argument must be "
588581ad6265SDimitry Andric             "smaller than the bit size of the return type",
588681ad6265SDimitry Andric             *VPCast);
588781ad6265SDimitry Andric       break;
588881ad6265SDimitry Andric     case Intrinsic::vp_ptrtoint:
588981ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
589081ad6265SDimitry Andric             "llvm.vp.ptrtoint intrinsic first argument element type must be "
589181ad6265SDimitry Andric             "pointer and result element type must be integer",
589281ad6265SDimitry Andric             *VPCast);
589381ad6265SDimitry Andric       break;
589481ad6265SDimitry Andric     case Intrinsic::vp_inttoptr:
589581ad6265SDimitry Andric       Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
589681ad6265SDimitry Andric             "llvm.vp.inttoptr intrinsic first argument element type must be "
589781ad6265SDimitry Andric             "integer and result element type must be pointer",
589881ad6265SDimitry Andric             *VPCast);
589981ad6265SDimitry Andric       break;
590081ad6265SDimitry Andric     }
590181ad6265SDimitry Andric   }
590281ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_fcmp) {
590381ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
590481ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
590581ad6265SDimitry Andric           "invalid predicate for VP FP comparison intrinsic", &VPI);
590681ad6265SDimitry Andric   }
590781ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_icmp) {
590881ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
590981ad6265SDimitry Andric     Check(CmpInst::isIntPredicate(Pred),
591081ad6265SDimitry Andric           "invalid predicate for VP integer comparison intrinsic", &VPI);
591181ad6265SDimitry Andric   }
591281ad6265SDimitry Andric }
591381ad6265SDimitry Andric 
59140b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
5915480093f4SDimitry Andric   unsigned NumOperands;
5916480093f4SDimitry Andric   bool HasRoundingMD;
59170b57cec5SDimitry Andric   switch (FPI.getIntrinsicID()) {
59185ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
5919480093f4SDimitry Andric   case Intrinsic::INTRINSIC:                                                   \
5920480093f4SDimitry Andric     NumOperands = NARG;                                                        \
5921480093f4SDimitry Andric     HasRoundingMD = ROUND_MODE;                                                \
59220b57cec5SDimitry Andric     break;
5923480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
5924480093f4SDimitry Andric   default:
5925480093f4SDimitry Andric     llvm_unreachable("Invalid constrained FP intrinsic!");
5926480093f4SDimitry Andric   }
5927480093f4SDimitry Andric   NumOperands += (1 + HasRoundingMD);
5928480093f4SDimitry Andric   // Compare intrinsics carry an extra predicate metadata operand.
5929480093f4SDimitry Andric   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
5930480093f4SDimitry Andric     NumOperands += 1;
593181ad6265SDimitry Andric   Check((FPI.arg_size() == NumOperands),
5932480093f4SDimitry Andric         "invalid arguments for constrained FP intrinsic", &FPI);
59330b57cec5SDimitry Andric 
5934480093f4SDimitry Andric   switch (FPI.getIntrinsicID()) {
59358bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
59368bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
59378bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
59388bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
593981ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
59408bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
59418bcb0991SDimitry Andric   }
59428bcb0991SDimitry Andric     break;
59438bcb0991SDimitry Andric 
59448bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
59458bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
59468bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
59478bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
594881ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
59498bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
59508bcb0991SDimitry Andric     break;
59518bcb0991SDimitry Andric   }
59528bcb0991SDimitry Andric 
5953480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmp:
5954480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmps: {
5955480093f4SDimitry Andric     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
595681ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
5957480093f4SDimitry Andric           "invalid predicate for constrained FP comparison intrinsic", &FPI);
59580b57cec5SDimitry Andric     break;
5959480093f4SDimitry Andric   }
59600b57cec5SDimitry Andric 
59618bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
59628bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
59638bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
59648bcb0991SDimitry Andric     uint64_t NumSrcElem = 0;
596581ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
59668bcb0991SDimitry Andric           "Intrinsic first argument must be floating point", &FPI);
59678bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5968e8d8bef9SDimitry Andric       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
59698bcb0991SDimitry Andric     }
59708bcb0991SDimitry Andric 
59718bcb0991SDimitry Andric     Operand = &FPI;
597281ad6265SDimitry Andric     Check((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
59738bcb0991SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
597481ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
59758bcb0991SDimitry Andric           "Intrinsic result must be an integer", &FPI);
59768bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
597781ad6265SDimitry Andric       Check(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
59788bcb0991SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
59798bcb0991SDimitry Andric             &FPI);
59808bcb0991SDimitry Andric     }
59818bcb0991SDimitry Andric   }
59828bcb0991SDimitry Andric     break;
59838bcb0991SDimitry Andric 
5984480093f4SDimitry Andric   case Intrinsic::experimental_constrained_sitofp:
5985480093f4SDimitry Andric   case Intrinsic::experimental_constrained_uitofp: {
5986480093f4SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
5987480093f4SDimitry Andric     uint64_t NumSrcElem = 0;
598881ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
5989480093f4SDimitry Andric           "Intrinsic first argument must be integer", &FPI);
5990480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
5991e8d8bef9SDimitry Andric       NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements();
5992480093f4SDimitry Andric     }
5993480093f4SDimitry Andric 
5994480093f4SDimitry Andric     Operand = &FPI;
599581ad6265SDimitry Andric     Check((NumSrcElem > 0) == Operand->getType()->isVectorTy(),
5996480093f4SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
599781ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
5998480093f4SDimitry Andric           "Intrinsic result must be a floating point", &FPI);
5999480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
600081ad6265SDimitry Andric       Check(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(),
6001480093f4SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
6002480093f4SDimitry Andric             &FPI);
6003480093f4SDimitry Andric     }
6004480093f4SDimitry Andric   } break;
6005480093f4SDimitry Andric 
60060b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
60070b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
60080b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
60090b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
60100b57cec5SDimitry Andric     Value *Result = &FPI;
60110b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
601281ad6265SDimitry Andric     Check(OperandTy->isFPOrFPVectorTy(),
60130b57cec5SDimitry Andric           "Intrinsic first argument must be FP or FP vector", &FPI);
601481ad6265SDimitry Andric     Check(ResultTy->isFPOrFPVectorTy(),
60150b57cec5SDimitry Andric           "Intrinsic result must be FP or FP vector", &FPI);
601681ad6265SDimitry Andric     Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
60170b57cec5SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
60180b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
601981ad6265SDimitry Andric       Check(cast<FixedVectorType>(OperandTy)->getNumElements() ==
6020e8d8bef9SDimitry Andric                 cast<FixedVectorType>(ResultTy)->getNumElements(),
60210b57cec5SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
60220b57cec5SDimitry Andric             &FPI);
60230b57cec5SDimitry Andric     }
60240b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
602581ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
60260b57cec5SDimitry Andric             "Intrinsic first argument's type must be larger than result type",
60270b57cec5SDimitry Andric             &FPI);
60280b57cec5SDimitry Andric     } else {
602981ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
60300b57cec5SDimitry Andric             "Intrinsic first argument's type must be smaller than result type",
60310b57cec5SDimitry Andric             &FPI);
60320b57cec5SDimitry Andric     }
60330b57cec5SDimitry Andric   }
60340b57cec5SDimitry Andric     break;
60350b57cec5SDimitry Andric 
60360b57cec5SDimitry Andric   default:
6037480093f4SDimitry Andric     break;
60380b57cec5SDimitry Andric   }
60390b57cec5SDimitry Andric 
60400b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
60410b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
60420b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
60430b57cec5SDimitry Andric   // argument type check is needed here.
60440b57cec5SDimitry Andric 
604581ad6265SDimitry Andric   Check(FPI.getExceptionBehavior().has_value(),
60460b57cec5SDimitry Andric         "invalid exception behavior argument", &FPI);
60470b57cec5SDimitry Andric   if (HasRoundingMD) {
604881ad6265SDimitry Andric     Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
604981ad6265SDimitry Andric           &FPI);
60500b57cec5SDimitry Andric   }
60510b57cec5SDimitry Andric }
60520b57cec5SDimitry Andric 
60530b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
6054fe6060f1SDimitry Andric   auto *MD = DII.getRawLocation();
605581ad6265SDimitry Andric   CheckDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
60560b57cec5SDimitry Andric               (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
60570b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
605881ad6265SDimitry Andric   CheckDI(isa<DILocalVariable>(DII.getRawVariable()),
60590b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
60600b57cec5SDimitry Andric           DII.getRawVariable());
606181ad6265SDimitry Andric   CheckDI(isa<DIExpression>(DII.getRawExpression()),
60620b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
60630b57cec5SDimitry Andric           DII.getRawExpression());
60640b57cec5SDimitry Andric 
6065*bdd1243dSDimitry Andric   if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&DII)) {
6066*bdd1243dSDimitry Andric     CheckDI(isa<DIAssignID>(DAI->getRawAssignID()),
6067*bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic DIAssignID", &DII,
6068*bdd1243dSDimitry Andric             DAI->getRawAssignID());
6069*bdd1243dSDimitry Andric     const auto *RawAddr = DAI->getRawAddress();
6070*bdd1243dSDimitry Andric     CheckDI(
6071*bdd1243dSDimitry Andric         isa<ValueAsMetadata>(RawAddr) ||
6072*bdd1243dSDimitry Andric             (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
6073*bdd1243dSDimitry Andric         "invalid llvm.dbg.assign intrinsic address", &DII,
6074*bdd1243dSDimitry Andric         DAI->getRawAddress());
6075*bdd1243dSDimitry Andric     CheckDI(isa<DIExpression>(DAI->getRawAddressExpression()),
6076*bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic address expression", &DII,
6077*bdd1243dSDimitry Andric             DAI->getRawAddressExpression());
6078*bdd1243dSDimitry Andric     // All of the linked instructions should be in the same function as DII.
6079*bdd1243dSDimitry Andric     for (Instruction *I : at::getAssignmentInsts(DAI))
6080*bdd1243dSDimitry Andric       CheckDI(DAI->getFunction() == I->getFunction(),
6081*bdd1243dSDimitry Andric               "inst not in same function as dbg.assign", I, DAI);
6082*bdd1243dSDimitry Andric   }
6083*bdd1243dSDimitry Andric 
60840b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
60850b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
60860b57cec5SDimitry Andric     if (!isa<DILocation>(N))
60870b57cec5SDimitry Andric       return;
60880b57cec5SDimitry Andric 
60890b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
60900b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
60910b57cec5SDimitry Andric 
60920b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
60930b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
60940b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
609581ad6265SDimitry Andric   CheckDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
60960b57cec5SDimitry Andric           &DII, BB, F);
60970b57cec5SDimitry Andric 
60980b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
60990b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
61000b57cec5SDimitry Andric   if (!VarSP || !LocSP)
61010b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
61020b57cec5SDimitry Andric 
610381ad6265SDimitry Andric   CheckDI(VarSP == LocSP,
610481ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
61050b57cec5SDimitry Andric               " variable and !dbg attachment",
61060b57cec5SDimitry Andric           &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
61070b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
61080b57cec5SDimitry Andric 
61090b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
611081ad6265SDimitry Andric   CheckDI(isType(Var->getRawType()), "invalid type ref", Var,
61110b57cec5SDimitry Andric           Var->getRawType());
61120b57cec5SDimitry Andric   verifyFnArgs(DII);
61130b57cec5SDimitry Andric }
61140b57cec5SDimitry Andric 
61150b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
611681ad6265SDimitry Andric   CheckDI(isa<DILabel>(DLI.getRawLabel()),
61170b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
61180b57cec5SDimitry Andric           DLI.getRawLabel());
61190b57cec5SDimitry Andric 
61200b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
61210b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
61220b57cec5SDimitry Andric     if (!isa<DILocation>(N))
61230b57cec5SDimitry Andric       return;
61240b57cec5SDimitry Andric 
61250b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
61260b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
61270b57cec5SDimitry Andric 
61280b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
61290b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
61300b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
613181ad6265SDimitry Andric   Check(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", &DLI,
613281ad6265SDimitry Andric         BB, F);
61330b57cec5SDimitry Andric 
61340b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
61350b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
61360b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
61370b57cec5SDimitry Andric     return;
61380b57cec5SDimitry Andric 
613981ad6265SDimitry Andric   CheckDI(LabelSP == LocSP,
614081ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
61410b57cec5SDimitry Andric               " label and !dbg attachment",
61420b57cec5SDimitry Andric           &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
61430b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
61440b57cec5SDimitry Andric }
61450b57cec5SDimitry Andric 
61460b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
61470b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
61480b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
61490b57cec5SDimitry Andric 
61500b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
61510b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
61520b57cec5SDimitry Andric     return;
61530b57cec5SDimitry Andric 
61540b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
61550b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
61560b57cec5SDimitry Andric   if (!Fragment)
61570b57cec5SDimitry Andric     return;
61580b57cec5SDimitry Andric 
61590b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
61600b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
61610b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
61620b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
61630b57cec5SDimitry Andric   // variable and this check fails.
61640b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
61650b57cec5SDimitry Andric   if (V->isArtificial())
61660b57cec5SDimitry Andric     return;
61670b57cec5SDimitry Andric 
61680b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
61690b57cec5SDimitry Andric }
61700b57cec5SDimitry Andric 
61710b57cec5SDimitry Andric template <typename ValueOrMetadata>
61720b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
61730b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
61740b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
61750b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
61760b57cec5SDimitry Andric   // elsewhere.
61770b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
61780b57cec5SDimitry Andric   if (!VarSize)
61790b57cec5SDimitry Andric     return;
61800b57cec5SDimitry Andric 
61810b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
61820b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
618381ad6265SDimitry Andric   CheckDI(FragSize + FragOffset <= *VarSize,
61840b57cec5SDimitry Andric           "fragment is larger than or outside of variable", Desc, &V);
618581ad6265SDimitry Andric   CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
61860b57cec5SDimitry Andric }
61870b57cec5SDimitry Andric 
61880b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
61890b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
61900b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
61910b57cec5SDimitry Andric   // contain inlined debug intrinsics.
61920b57cec5SDimitry Andric   if (!HasDebugInfo)
61930b57cec5SDimitry Andric     return;
61940b57cec5SDimitry Andric 
61950b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
61960b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
61970b57cec5SDimitry Andric     return;
61980b57cec5SDimitry Andric 
61990b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
620081ad6265SDimitry Andric   CheckDI(Var, "dbg intrinsic without variable");
62010b57cec5SDimitry Andric 
62020b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
62030b57cec5SDimitry Andric   if (!ArgNo)
62040b57cec5SDimitry Andric     return;
62050b57cec5SDimitry Andric 
62060b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
62070b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
62080b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
62090b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
62100b57cec5SDimitry Andric 
62110b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
62120b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
621381ad6265SDimitry Andric   CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
62140b57cec5SDimitry Andric           Prev, Var);
62150b57cec5SDimitry Andric }
62160b57cec5SDimitry Andric 
62178bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
62188bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
62198bcb0991SDimitry Andric 
62208bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
62218bcb0991SDimitry Andric   if (!E || !E->isValid())
62228bcb0991SDimitry Andric     return;
62238bcb0991SDimitry Andric 
622481ad6265SDimitry Andric   CheckDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I);
62258bcb0991SDimitry Andric }
62268bcb0991SDimitry Andric 
62270b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
62280b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
62290b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
62300b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
62310b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
62320b57cec5SDimitry Andric     return;
62330b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
62340b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
62350b57cec5SDimitry Andric   if (CUs)
62360b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
6237*bdd1243dSDimitry Andric   for (const auto *CU : CUVisited)
623881ad6265SDimitry Andric     CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
62390b57cec5SDimitry Andric   CUVisited.clear();
62400b57cec5SDimitry Andric }
62410b57cec5SDimitry Andric 
62420b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
62430b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
62440b57cec5SDimitry Andric     return;
62450b57cec5SDimitry Andric 
62460b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
6247*bdd1243dSDimitry Andric   for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
624881ad6265SDimitry Andric     Check(First->getCallingConv() == F->getCallingConv(),
62490b57cec5SDimitry Andric           "All llvm.experimental.deoptimize declarations must have the same "
62500b57cec5SDimitry Andric           "calling convention",
62510b57cec5SDimitry Andric           First, F);
62520b57cec5SDimitry Andric   }
62530b57cec5SDimitry Andric }
62540b57cec5SDimitry Andric 
6255349cc55cSDimitry Andric void Verifier::verifyAttachedCallBundle(const CallBase &Call,
6256349cc55cSDimitry Andric                                         const OperandBundleUse &BU) {
6257349cc55cSDimitry Andric   FunctionType *FTy = Call.getFunctionType();
6258349cc55cSDimitry Andric 
625981ad6265SDimitry Andric   Check((FTy->getReturnType()->isPointerTy() ||
6260349cc55cSDimitry Andric          (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
6261349cc55cSDimitry Andric         "a call with operand bundle \"clang.arc.attachedcall\" must call a "
6262349cc55cSDimitry Andric         "function returning a pointer or a non-returning function that has a "
6263349cc55cSDimitry Andric         "void return type",
6264349cc55cSDimitry Andric         Call);
6265349cc55cSDimitry Andric 
626681ad6265SDimitry Andric   Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
62671fd87a68SDimitry Andric         "operand bundle \"clang.arc.attachedcall\" requires one function as "
62681fd87a68SDimitry Andric         "an argument",
6269349cc55cSDimitry Andric         Call);
6270349cc55cSDimitry Andric 
6271349cc55cSDimitry Andric   auto *Fn = cast<Function>(BU.Inputs.front());
6272349cc55cSDimitry Andric   Intrinsic::ID IID = Fn->getIntrinsicID();
6273349cc55cSDimitry Andric 
6274349cc55cSDimitry Andric   if (IID) {
627581ad6265SDimitry Andric     Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
6276349cc55cSDimitry Andric            IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
6277349cc55cSDimitry Andric           "invalid function argument", Call);
6278349cc55cSDimitry Andric   } else {
6279349cc55cSDimitry Andric     StringRef FnName = Fn->getName();
628081ad6265SDimitry Andric     Check((FnName == "objc_retainAutoreleasedReturnValue" ||
6281349cc55cSDimitry Andric            FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
6282349cc55cSDimitry Andric           "invalid function argument", Call);
6283349cc55cSDimitry Andric   }
6284349cc55cSDimitry Andric }
6285349cc55cSDimitry Andric 
62860b57cec5SDimitry Andric void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) {
628781ad6265SDimitry Andric   bool HasSource = F.getSource().has_value();
62880b57cec5SDimitry Andric   if (!HasSourceDebugInfo.count(&U))
62890b57cec5SDimitry Andric     HasSourceDebugInfo[&U] = HasSource;
629081ad6265SDimitry Andric   CheckDI(HasSource == HasSourceDebugInfo[&U],
62910b57cec5SDimitry Andric           "inconsistent use of embedded source");
62920b57cec5SDimitry Andric }
62930b57cec5SDimitry Andric 
6294e8d8bef9SDimitry Andric void Verifier::verifyNoAliasScopeDecl() {
6295e8d8bef9SDimitry Andric   if (NoAliasScopeDecls.empty())
6296e8d8bef9SDimitry Andric     return;
6297e8d8bef9SDimitry Andric 
6298e8d8bef9SDimitry Andric   // only a single scope must be declared at a time.
6299e8d8bef9SDimitry Andric   for (auto *II : NoAliasScopeDecls) {
6300e8d8bef9SDimitry Andric     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
6301e8d8bef9SDimitry Andric            "Not a llvm.experimental.noalias.scope.decl ?");
6302e8d8bef9SDimitry Andric     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
6303e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
630481ad6265SDimitry Andric     Check(ScopeListMV != nullptr,
6305e8d8bef9SDimitry Andric           "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
6306e8d8bef9SDimitry Andric           "argument",
6307e8d8bef9SDimitry Andric           II);
6308e8d8bef9SDimitry Andric 
6309e8d8bef9SDimitry Andric     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
631081ad6265SDimitry Andric     Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
631181ad6265SDimitry Andric     Check(ScopeListMD->getNumOperands() == 1,
6312e8d8bef9SDimitry Andric           "!id.scope.list must point to a list with a single scope", II);
6313349cc55cSDimitry Andric     visitAliasScopeListMetadata(ScopeListMD);
6314e8d8bef9SDimitry Andric   }
6315e8d8bef9SDimitry Andric 
6316e8d8bef9SDimitry Andric   // Only check the domination rule when requested. Once all passes have been
6317e8d8bef9SDimitry Andric   // adapted this option can go away.
6318e8d8bef9SDimitry Andric   if (!VerifyNoAliasScopeDomination)
6319e8d8bef9SDimitry Andric     return;
6320e8d8bef9SDimitry Andric 
6321e8d8bef9SDimitry Andric   // Now sort the intrinsics based on the scope MDNode so that declarations of
6322e8d8bef9SDimitry Andric   // the same scopes are next to each other.
6323e8d8bef9SDimitry Andric   auto GetScope = [](IntrinsicInst *II) {
6324e8d8bef9SDimitry Andric     const auto *ScopeListMV = cast<MetadataAsValue>(
6325e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
6326e8d8bef9SDimitry Andric     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
6327e8d8bef9SDimitry Andric   };
6328e8d8bef9SDimitry Andric 
6329e8d8bef9SDimitry Andric   // We are sorting on MDNode pointers here. For valid input IR this is ok.
6330e8d8bef9SDimitry Andric   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
6331e8d8bef9SDimitry Andric   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
6332e8d8bef9SDimitry Andric     return GetScope(Lhs) < GetScope(Rhs);
6333e8d8bef9SDimitry Andric   };
6334e8d8bef9SDimitry Andric 
6335e8d8bef9SDimitry Andric   llvm::sort(NoAliasScopeDecls, Compare);
6336e8d8bef9SDimitry Andric 
6337e8d8bef9SDimitry Andric   // Go over the intrinsics and check that for the same scope, they are not
6338e8d8bef9SDimitry Andric   // dominating each other.
6339e8d8bef9SDimitry Andric   auto ItCurrent = NoAliasScopeDecls.begin();
6340e8d8bef9SDimitry Andric   while (ItCurrent != NoAliasScopeDecls.end()) {
6341e8d8bef9SDimitry Andric     auto CurScope = GetScope(*ItCurrent);
6342e8d8bef9SDimitry Andric     auto ItNext = ItCurrent;
6343e8d8bef9SDimitry Andric     do {
6344e8d8bef9SDimitry Andric       ++ItNext;
6345e8d8bef9SDimitry Andric     } while (ItNext != NoAliasScopeDecls.end() &&
6346e8d8bef9SDimitry Andric              GetScope(*ItNext) == CurScope);
6347e8d8bef9SDimitry Andric 
6348e8d8bef9SDimitry Andric     // [ItCurrent, ItNext) represents the declarations for the same scope.
6349e8d8bef9SDimitry Andric     // Ensure they are not dominating each other.. but only if it is not too
6350e8d8bef9SDimitry Andric     // expensive.
6351e8d8bef9SDimitry Andric     if (ItNext - ItCurrent < 32)
6352e8d8bef9SDimitry Andric       for (auto *I : llvm::make_range(ItCurrent, ItNext))
6353e8d8bef9SDimitry Andric         for (auto *J : llvm::make_range(ItCurrent, ItNext))
6354e8d8bef9SDimitry Andric           if (I != J)
635581ad6265SDimitry Andric             Check(!DT.dominates(I, J),
6356e8d8bef9SDimitry Andric                   "llvm.experimental.noalias.scope.decl dominates another one "
6357e8d8bef9SDimitry Andric                   "with the same scope",
6358e8d8bef9SDimitry Andric                   I);
6359e8d8bef9SDimitry Andric     ItCurrent = ItNext;
6360e8d8bef9SDimitry Andric   }
6361e8d8bef9SDimitry Andric }
6362e8d8bef9SDimitry Andric 
63630b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
63640b57cec5SDimitry Andric //  Implement the public interfaces to this file...
63650b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
63660b57cec5SDimitry Andric 
63670b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
63680b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
63690b57cec5SDimitry Andric 
63700b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
63710b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
63720b57cec5SDimitry Andric 
63730b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
63740b57cec5SDimitry Andric   // expect of a function called "verify".
63750b57cec5SDimitry Andric   return !V.verify(F);
63760b57cec5SDimitry Andric }
63770b57cec5SDimitry Andric 
63780b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
63790b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
63800b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
63810b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
63820b57cec5SDimitry Andric 
63830b57cec5SDimitry Andric   bool Broken = false;
63840b57cec5SDimitry Andric   for (const Function &F : M)
63850b57cec5SDimitry Andric     Broken |= !V.verify(F);
63860b57cec5SDimitry Andric 
63870b57cec5SDimitry Andric   Broken |= !V.verify();
63880b57cec5SDimitry Andric   if (BrokenDebugInfo)
63890b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
63900b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
63910b57cec5SDimitry Andric   // expect of a function called "verify".
63920b57cec5SDimitry Andric   return Broken;
63930b57cec5SDimitry Andric }
63940b57cec5SDimitry Andric 
63950b57cec5SDimitry Andric namespace {
63960b57cec5SDimitry Andric 
63970b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
63980b57cec5SDimitry Andric   static char ID;
63990b57cec5SDimitry Andric 
64000b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
64010b57cec5SDimitry Andric   bool FatalErrors = true;
64020b57cec5SDimitry Andric 
64030b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
64040b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
64050b57cec5SDimitry Andric   }
64060b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
64070b57cec5SDimitry Andric       : FunctionPass(ID),
64080b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
64090b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
64100b57cec5SDimitry Andric   }
64110b57cec5SDimitry Andric 
64120b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
64138bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
64140b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
64150b57cec5SDimitry Andric     return false;
64160b57cec5SDimitry Andric   }
64170b57cec5SDimitry Andric 
64180b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
64190b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
64200b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
64210b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
64220b57cec5SDimitry Andric     }
64230b57cec5SDimitry Andric     return false;
64240b57cec5SDimitry Andric   }
64250b57cec5SDimitry Andric 
64260b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
64270b57cec5SDimitry Andric     bool HasErrors = false;
64280b57cec5SDimitry Andric     for (Function &F : M)
64290b57cec5SDimitry Andric       if (F.isDeclaration())
64300b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
64310b57cec5SDimitry Andric 
64320b57cec5SDimitry Andric     HasErrors |= !V->verify();
64330b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
64340b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
64350b57cec5SDimitry Andric     return false;
64360b57cec5SDimitry Andric   }
64370b57cec5SDimitry Andric 
64380b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
64390b57cec5SDimitry Andric     AU.setPreservesAll();
64400b57cec5SDimitry Andric   }
64410b57cec5SDimitry Andric };
64420b57cec5SDimitry Andric 
64430b57cec5SDimitry Andric } // end anonymous namespace
64440b57cec5SDimitry Andric 
64450b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
64460b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
64470b57cec5SDimitry Andric   if (Diagnostic)
64480b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
64490b57cec5SDimitry Andric }
64500b57cec5SDimitry Andric 
645181ad6265SDimitry Andric #define CheckTBAA(C, ...)                                                      \
64520b57cec5SDimitry Andric   do {                                                                         \
64530b57cec5SDimitry Andric     if (!(C)) {                                                                \
64540b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
64550b57cec5SDimitry Andric       return false;                                                            \
64560b57cec5SDimitry Andric     }                                                                          \
64570b57cec5SDimitry Andric   } while (false)
64580b57cec5SDimitry Andric 
64590b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
64600b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
64610b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
64620b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
64630b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
64640b57cec5SDimitry Andric                                  bool IsNewFormat) {
64650b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
64660b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
64670b57cec5SDimitry Andric     return {true, ~0u};
64680b57cec5SDimitry Andric   }
64690b57cec5SDimitry Andric 
64700b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
64710b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
64720b57cec5SDimitry Andric     return Itr->second;
64730b57cec5SDimitry Andric 
64740b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
64750b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
64760b57cec5SDimitry Andric   (void)InsertResult;
64770b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
64780b57cec5SDimitry Andric   return Result;
64790b57cec5SDimitry Andric }
64800b57cec5SDimitry Andric 
64810b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
64820b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
64830b57cec5SDimitry Andric                                      bool IsNewFormat) {
64840b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
64850b57cec5SDimitry Andric 
64860b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
64870b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
64880b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
64890b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
64900b57cec5SDimitry Andric                : InvalidNode;
64910b57cec5SDimitry Andric   }
64920b57cec5SDimitry Andric 
64930b57cec5SDimitry Andric   if (IsNewFormat) {
64940b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
64950b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
64960b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
64970b57cec5SDimitry Andric       return InvalidNode;
64980b57cec5SDimitry Andric     }
64990b57cec5SDimitry Andric   } else {
65000b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
65010b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
65020b57cec5SDimitry Andric                   BaseNode);
65030b57cec5SDimitry Andric       return InvalidNode;
65040b57cec5SDimitry Andric     }
65050b57cec5SDimitry Andric   }
65060b57cec5SDimitry Andric 
65070b57cec5SDimitry Andric   // Check the type size field.
65080b57cec5SDimitry Andric   if (IsNewFormat) {
65090b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
65100b57cec5SDimitry Andric         BaseNode->getOperand(1));
65110b57cec5SDimitry Andric     if (!TypeSizeNode) {
65120b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
65130b57cec5SDimitry Andric       return InvalidNode;
65140b57cec5SDimitry Andric     }
65150b57cec5SDimitry Andric   }
65160b57cec5SDimitry Andric 
65170b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
65180b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
65190b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
65200b57cec5SDimitry Andric                 BaseNode);
65210b57cec5SDimitry Andric     return InvalidNode;
65220b57cec5SDimitry Andric   }
65230b57cec5SDimitry Andric 
65240b57cec5SDimitry Andric   bool Failed = false;
65250b57cec5SDimitry Andric 
6526*bdd1243dSDimitry Andric   std::optional<APInt> PrevOffset;
65270b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
65280b57cec5SDimitry Andric 
65290b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
65300b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
65310b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
65320b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
65330b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
65340b57cec5SDimitry Andric            Idx += NumOpsPerField) {
65350b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
65360b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
65370b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
65380b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
65390b57cec5SDimitry Andric       Failed = true;
65400b57cec5SDimitry Andric       continue;
65410b57cec5SDimitry Andric     }
65420b57cec5SDimitry Andric 
65430b57cec5SDimitry Andric     auto *OffsetEntryCI =
65440b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
65450b57cec5SDimitry Andric     if (!OffsetEntryCI) {
65460b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
65470b57cec5SDimitry Andric       Failed = true;
65480b57cec5SDimitry Andric       continue;
65490b57cec5SDimitry Andric     }
65500b57cec5SDimitry Andric 
65510b57cec5SDimitry Andric     if (BitWidth == ~0u)
65520b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
65530b57cec5SDimitry Andric 
65540b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
65550b57cec5SDimitry Andric       CheckFailed(
65560b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
65570b57cec5SDimitry Andric           BaseNode);
65580b57cec5SDimitry Andric       Failed = true;
65590b57cec5SDimitry Andric       continue;
65600b57cec5SDimitry Andric     }
65610b57cec5SDimitry Andric 
65620b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
65630b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
65640b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
65650b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
65660b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
65670b57cec5SDimitry Andric     bool IsAscending =
65680b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
65690b57cec5SDimitry Andric 
65700b57cec5SDimitry Andric     if (!IsAscending) {
65710b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
65720b57cec5SDimitry Andric       Failed = true;
65730b57cec5SDimitry Andric     }
65740b57cec5SDimitry Andric 
65750b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
65760b57cec5SDimitry Andric 
65770b57cec5SDimitry Andric     if (IsNewFormat) {
65780b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
65790b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
65800b57cec5SDimitry Andric       if (!MemberSizeNode) {
65810b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
65820b57cec5SDimitry Andric         Failed = true;
65830b57cec5SDimitry Andric         continue;
65840b57cec5SDimitry Andric       }
65850b57cec5SDimitry Andric     }
65860b57cec5SDimitry Andric   }
65870b57cec5SDimitry Andric 
65880b57cec5SDimitry Andric   return Failed ? InvalidNode
65890b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
65900b57cec5SDimitry Andric }
65910b57cec5SDimitry Andric 
65920b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
65930b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
65940b57cec5SDimitry Andric }
65950b57cec5SDimitry Andric 
65960b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
65970b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
65980b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
65990b57cec5SDimitry Andric     return false;
66000b57cec5SDimitry Andric 
66010b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
66020b57cec5SDimitry Andric     return false;
66030b57cec5SDimitry Andric 
66040b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
66050b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
66060b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
66070b57cec5SDimitry Andric       return false;
66080b57cec5SDimitry Andric   }
66090b57cec5SDimitry Andric 
66100b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
66110b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
66120b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
66130b57cec5SDimitry Andric }
66140b57cec5SDimitry Andric 
66150b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
66160b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
66170b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
66180b57cec5SDimitry Andric     return ResultIt->second;
66190b57cec5SDimitry Andric 
66200b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
66210b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
66220b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
66230b57cec5SDimitry Andric   (void)InsertResult;
66240b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
66250b57cec5SDimitry Andric 
66260b57cec5SDimitry Andric   return Result;
66270b57cec5SDimitry Andric }
66280b57cec5SDimitry Andric 
66290b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
66300b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
66310b57cec5SDimitry Andric ///
66320b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
66330b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
66340b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
66350b57cec5SDimitry Andric                                                    APInt &Offset,
66360b57cec5SDimitry Andric                                                    bool IsNewFormat) {
66370b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
66380b57cec5SDimitry Andric 
66390b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
66400b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
664181ad6265SDimitry Andric   // to check that.
66420b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
66430b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
66440b57cec5SDimitry Andric 
66450b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
66460b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
66470b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
66480b57cec5SDimitry Andric            Idx += NumOpsPerField) {
66490b57cec5SDimitry Andric     auto *OffsetEntryCI =
66500b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
66510b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
66520b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
66530b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
66540b57cec5SDimitry Andric                     BaseNode, &Offset);
66550b57cec5SDimitry Andric         return nullptr;
66560b57cec5SDimitry Andric       }
66570b57cec5SDimitry Andric 
66580b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
66590b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
66600b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
66610b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
66620b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
66630b57cec5SDimitry Andric     }
66640b57cec5SDimitry Andric   }
66650b57cec5SDimitry Andric 
66660b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
66670b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
66680b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
66690b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
66700b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
66710b57cec5SDimitry Andric }
66720b57cec5SDimitry Andric 
66730b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
66740b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
66750b57cec5SDimitry Andric     return false;
66760b57cec5SDimitry Andric 
66770b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
66780b57cec5SDimitry Andric   // its first operand.
6679349cc55cSDimitry Andric   return isa_and_nonnull<MDNode>(Type->getOperand(0));
66800b57cec5SDimitry Andric }
66810b57cec5SDimitry Andric 
66820b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
668381ad6265SDimitry Andric   CheckTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
66840b57cec5SDimitry Andric                 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
66850b57cec5SDimitry Andric                 isa<AtomicCmpXchgInst>(I),
66860b57cec5SDimitry Andric             "This instruction shall not have a TBAA access tag!", &I);
66870b57cec5SDimitry Andric 
66880b57cec5SDimitry Andric   bool IsStructPathTBAA =
66890b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
66900b57cec5SDimitry Andric 
669181ad6265SDimitry Andric   CheckTBAA(IsStructPathTBAA,
669281ad6265SDimitry Andric             "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
669381ad6265SDimitry Andric             &I);
66940b57cec5SDimitry Andric 
66950b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
66960b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
66970b57cec5SDimitry Andric 
66980b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
66990b57cec5SDimitry Andric 
67000b57cec5SDimitry Andric   if (IsNewFormat) {
670181ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
67020b57cec5SDimitry Andric               "Access tag metadata must have either 4 or 5 operands", &I, MD);
67030b57cec5SDimitry Andric   } else {
670481ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() < 5,
67050b57cec5SDimitry Andric               "Struct tag metadata must have either 3 or 4 operands", &I, MD);
67060b57cec5SDimitry Andric   }
67070b57cec5SDimitry Andric 
67080b57cec5SDimitry Andric   // Check the access size field.
67090b57cec5SDimitry Andric   if (IsNewFormat) {
67100b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
67110b57cec5SDimitry Andric         MD->getOperand(3));
671281ad6265SDimitry Andric     CheckTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
67130b57cec5SDimitry Andric   }
67140b57cec5SDimitry Andric 
67150b57cec5SDimitry Andric   // Check the immutability flag.
67160b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
67170b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
67180b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
67190b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
672081ad6265SDimitry Andric     CheckTBAA(IsImmutableCI,
672181ad6265SDimitry Andric               "Immutability tag on struct tag metadata must be a constant", &I,
672281ad6265SDimitry Andric               MD);
672381ad6265SDimitry Andric     CheckTBAA(
67240b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
67250b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
67260b57cec5SDimitry Andric         &I, MD);
67270b57cec5SDimitry Andric   }
67280b57cec5SDimitry Andric 
672981ad6265SDimitry Andric   CheckTBAA(BaseNode && AccessType,
67300b57cec5SDimitry Andric             "Malformed struct tag metadata: base and access-type "
67310b57cec5SDimitry Andric             "should be non-null and point to Metadata nodes",
67320b57cec5SDimitry Andric             &I, MD, BaseNode, AccessType);
67330b57cec5SDimitry Andric 
67340b57cec5SDimitry Andric   if (!IsNewFormat) {
673581ad6265SDimitry Andric     CheckTBAA(isValidScalarTBAANode(AccessType),
67360b57cec5SDimitry Andric               "Access type node must be a valid scalar type", &I, MD,
67370b57cec5SDimitry Andric               AccessType);
67380b57cec5SDimitry Andric   }
67390b57cec5SDimitry Andric 
67400b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
674181ad6265SDimitry Andric   CheckTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
67420b57cec5SDimitry Andric 
67430b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
67440b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
67450b57cec5SDimitry Andric 
67460b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
67470b57cec5SDimitry Andric 
67480b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
67490b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
67500b57cec5SDimitry Andric                                                IsNewFormat)) {
67510b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
67520b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
67530b57cec5SDimitry Andric       return false;
67540b57cec5SDimitry Andric     }
67550b57cec5SDimitry Andric 
67560b57cec5SDimitry Andric     bool Invalid;
67570b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
67580b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
67590b57cec5SDimitry Andric                                                              IsNewFormat);
67600b57cec5SDimitry Andric 
67610b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
67620b57cec5SDimitry Andric     // errors we wanted to print.
67630b57cec5SDimitry Andric     if (Invalid)
67640b57cec5SDimitry Andric       return false;
67650b57cec5SDimitry Andric 
67660b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
67670b57cec5SDimitry Andric 
67680b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
676981ad6265SDimitry Andric       CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access",
67700b57cec5SDimitry Andric                 &I, MD, &Offset);
67710b57cec5SDimitry Andric 
677281ad6265SDimitry Andric     CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
67730b57cec5SDimitry Andric                   (BaseNodeBitWidth == 0 && Offset == 0) ||
67740b57cec5SDimitry Andric                   (IsNewFormat && BaseNodeBitWidth == ~0u),
67750b57cec5SDimitry Andric               "Access bit-width not the same as description bit-width", &I, MD,
67760b57cec5SDimitry Andric               BaseNodeBitWidth, Offset.getBitWidth());
67770b57cec5SDimitry Andric 
67780b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
67790b57cec5SDimitry Andric       break;
67800b57cec5SDimitry Andric   }
67810b57cec5SDimitry Andric 
678281ad6265SDimitry Andric   CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", &I,
678381ad6265SDimitry Andric             MD);
67840b57cec5SDimitry Andric   return true;
67850b57cec5SDimitry Andric }
67860b57cec5SDimitry Andric 
67870b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
67880b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
67890b57cec5SDimitry Andric 
67900b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
67910b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
67920b57cec5SDimitry Andric }
67930b57cec5SDimitry Andric 
67940b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
67950b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
67960b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
67970b57cec5SDimitry Andric   Result Res;
67980b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
67990b57cec5SDimitry Andric   return Res;
68000b57cec5SDimitry Andric }
68010b57cec5SDimitry Andric 
68020b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
68030b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
68040b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
68050b57cec5SDimitry Andric }
68060b57cec5SDimitry Andric 
68070b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
68080b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
68090b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
68100b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
68110b57cec5SDimitry Andric 
68120b57cec5SDimitry Andric   return PreservedAnalyses::all();
68130b57cec5SDimitry Andric }
68140b57cec5SDimitry Andric 
68150b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
68160b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
68170b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
68180b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
68190b57cec5SDimitry Andric 
68200b57cec5SDimitry Andric   return PreservedAnalyses::all();
68210b57cec5SDimitry Andric }
6822