xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision 297eecfb02bb25902531dbb5c3b9a88caf8adf29)
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.
4106c3fb27SDimitry Andric //  * Convergence control intrinsics are introduced in ConvergentOperations.rst.
4206c3fb27SDimitry Andric //    The applied restrictions are too numerous to list here.
4306c3fb27SDimitry Andric //  * The convergence entry intrinsic and the loop heart must be the first
4406c3fb27SDimitry Andric //    non-PHI instruction in their respective block. This does not conflict with
4506c3fb27SDimitry Andric //    the landing pads, since these two kinds cannot occur in the same block.
460b57cec5SDimitry Andric //  * All other things that are tested by asserts spread about the code...
470b57cec5SDimitry Andric //
480b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
510b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
520b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
530b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
540b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
550b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
5606c3fb27SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
570b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
580b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
590b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
600b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
610b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
620b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
630b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
640b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
650b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
660b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
6706c3fb27SDimitry Andric #include "llvm/IR/AttributeMask.h"
680b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
690b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
700b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
710b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
720b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
730b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
740b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
750b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
765f757f3fSDimitry Andric #include "llvm/IR/ConvergenceVerifier.h"
770b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
78bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
790b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
800b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
810b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
820b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
8306c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
840b57cec5SDimitry Andric #include "llvm/IR/Function.h"
85bdd1243dSDimitry Andric #include "llvm/IR/GCStrategy.h"
860b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
870b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
880b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
890b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
900b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
910b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
920b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
930b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
940b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
950b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
9681ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
9706c3fb27SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
9881ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
99*297eecfbSDimitry Andric #include "llvm/IR/IntrinsicsNVPTX.h"
100480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
1010b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
1020b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
1030b57cec5SDimitry Andric #include "llvm/IR/Module.h"
1040b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
1050b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
1060b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
1070b57cec5SDimitry Andric #include "llvm/IR/Type.h"
1080b57cec5SDimitry Andric #include "llvm/IR/Use.h"
1090b57cec5SDimitry Andric #include "llvm/IR/User.h"
1100b57cec5SDimitry Andric #include "llvm/IR/Value.h"
111480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1120b57cec5SDimitry Andric #include "llvm/Pass.h"
1130b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1140b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1150b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1160b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1170b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
1180b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1190b57cec5SDimitry Andric #include <algorithm>
1200b57cec5SDimitry Andric #include <cassert>
1210b57cec5SDimitry Andric #include <cstdint>
1220b57cec5SDimitry Andric #include <memory>
123bdd1243dSDimitry Andric #include <optional>
1240b57cec5SDimitry Andric #include <string>
1250b57cec5SDimitry Andric #include <utility>
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric using namespace llvm;
1280b57cec5SDimitry Andric 
129e8d8bef9SDimitry Andric static cl::opt<bool> VerifyNoAliasScopeDomination(
130e8d8bef9SDimitry Andric     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
131e8d8bef9SDimitry Andric     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
132e8d8bef9SDimitry Andric              "scopes are not dominating"));
133e8d8bef9SDimitry Andric 
1340b57cec5SDimitry Andric namespace llvm {
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric struct VerifierSupport {
1370b57cec5SDimitry Andric   raw_ostream *OS;
1380b57cec5SDimitry Andric   const Module &M;
1390b57cec5SDimitry Andric   ModuleSlotTracker MST;
1408bcb0991SDimitry Andric   Triple TT;
1410b57cec5SDimitry Andric   const DataLayout &DL;
1420b57cec5SDimitry Andric   LLVMContext &Context;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1450b57cec5SDimitry Andric   bool Broken = false;
1460b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1470b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1480b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1490b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
1528bcb0991SDimitry Andric       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
1538bcb0991SDimitry Andric         Context(M.getContext()) {}
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric private:
1560b57cec5SDimitry Andric   void Write(const Module *M) {
1570b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1580b57cec5SDimitry Andric   }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   void Write(const Value *V) {
1610b57cec5SDimitry Andric     if (V)
1620b57cec5SDimitry Andric       Write(*V);
1630b57cec5SDimitry Andric   }
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   void Write(const Value &V) {
1660b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1670b57cec5SDimitry Andric       V.print(*OS, MST);
1680b57cec5SDimitry Andric       *OS << '\n';
1690b57cec5SDimitry Andric     } else {
1700b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1710b57cec5SDimitry Andric       *OS << '\n';
1720b57cec5SDimitry Andric     }
1730b57cec5SDimitry Andric   }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   void Write(const Metadata *MD) {
1760b57cec5SDimitry Andric     if (!MD)
1770b57cec5SDimitry Andric       return;
1780b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
1790b57cec5SDimitry Andric     *OS << '\n';
1800b57cec5SDimitry Andric   }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
1830b57cec5SDimitry Andric     Write(MD.get());
1840b57cec5SDimitry Andric   }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
1870b57cec5SDimitry Andric     if (!NMD)
1880b57cec5SDimitry Andric       return;
1890b57cec5SDimitry Andric     NMD->print(*OS, MST);
1900b57cec5SDimitry Andric     *OS << '\n';
1910b57cec5SDimitry Andric   }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   void Write(Type *T) {
1940b57cec5SDimitry Andric     if (!T)
1950b57cec5SDimitry Andric       return;
1960b57cec5SDimitry Andric     *OS << ' ' << *T;
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   void Write(const Comdat *C) {
2000b57cec5SDimitry Andric     if (!C)
2010b57cec5SDimitry Andric       return;
2020b57cec5SDimitry Andric     *OS << *C;
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   void Write(const APInt *AI) {
2060b57cec5SDimitry Andric     if (!AI)
2070b57cec5SDimitry Andric       return;
2080b57cec5SDimitry Andric     *OS << *AI << '\n';
2090b57cec5SDimitry Andric   }
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
2120b57cec5SDimitry Andric 
213fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
214fe6060f1SDimitry Andric   void Write(const Attribute *A) {
215fe6060f1SDimitry Andric     if (!A)
216fe6060f1SDimitry Andric       return;
217fe6060f1SDimitry Andric     *OS << A->getAsString() << '\n';
218fe6060f1SDimitry Andric   }
219fe6060f1SDimitry Andric 
220fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
221fe6060f1SDimitry Andric   void Write(const AttributeSet *AS) {
222fe6060f1SDimitry Andric     if (!AS)
223fe6060f1SDimitry Andric       return;
224fe6060f1SDimitry Andric     *OS << AS->getAsString() << '\n';
225fe6060f1SDimitry Andric   }
226fe6060f1SDimitry Andric 
227fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
228fe6060f1SDimitry Andric   void Write(const AttributeList *AL) {
229fe6060f1SDimitry Andric     if (!AL)
230fe6060f1SDimitry Andric       return;
231fe6060f1SDimitry Andric     AL->print(*OS);
232fe6060f1SDimitry Andric   }
233fe6060f1SDimitry Andric 
23406c3fb27SDimitry Andric   void Write(Printable P) { *OS << P << '\n'; }
23506c3fb27SDimitry Andric 
2360b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
2370b57cec5SDimitry Andric     for (const T &V : Vs)
2380b57cec5SDimitry Andric       Write(V);
2390b57cec5SDimitry Andric   }
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2420b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2430b57cec5SDimitry Andric     Write(V1);
2440b57cec5SDimitry Andric     WriteTs(Vs...);
2450b57cec5SDimitry Andric   }
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric public:
2500b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2510b57cec5SDimitry Andric   ///
2520b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2530b57cec5SDimitry Andric   /// something is not correct.
2540b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2550b57cec5SDimitry Andric     if (OS)
2560b57cec5SDimitry Andric       *OS << Message << '\n';
2570b57cec5SDimitry Andric     Broken = true;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   /// A check failed (with values to print).
2610b57cec5SDimitry Andric   ///
2620b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2630b57cec5SDimitry Andric   /// breakpoint on.
2640b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2650b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2660b57cec5SDimitry Andric     CheckFailed(Message);
2670b57cec5SDimitry Andric     if (OS)
2680b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2690b57cec5SDimitry Andric   }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   /// A debug info check failed.
2720b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
2730b57cec5SDimitry Andric     if (OS)
2740b57cec5SDimitry Andric       *OS << Message << '\n';
2750b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
2760b57cec5SDimitry Andric     BrokenDebugInfo = true;
2770b57cec5SDimitry Andric   }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
2800b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2810b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
2820b57cec5SDimitry Andric                             const Ts &... Vs) {
2830b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
2840b57cec5SDimitry Andric     if (OS)
2850b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric };
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric } // namespace llvm
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric namespace {
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
2940b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
2950b57cec5SDimitry Andric 
29681ad6265SDimitry Andric   // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
29781ad6265SDimitry Andric   // the alignment size should not exceed 2^15. Since encode(Align)
29881ad6265SDimitry Andric   // would plus the shift value by 1, the alignment size should
29981ad6265SDimitry Andric   // not exceed 2^14, otherwise it can NOT be properly lowered
30081ad6265SDimitry Andric   // in backend.
30181ad6265SDimitry Andric   static constexpr unsigned ParamMaxAlignment = 1 << 14;
3020b57cec5SDimitry Andric   DominatorTree DT;
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
3050b57cec5SDimitry Andric   /// instructions we have seen so far.
3060b57cec5SDimitry Andric   ///
3070b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
3080b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
3090b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
3120b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
3150b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
3180b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric   /// The result type for a landingpad.
3210b57cec5SDimitry Andric   Type *LandingPadResultTy;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
3240b57cec5SDimitry Andric   /// already.
3250b57cec5SDimitry Andric   bool SawFrameEscape;
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
3280b57cec5SDimitry Andric   bool HasDebugInfo = false;
3290b57cec5SDimitry Andric 
330e8d8bef9SDimitry Andric   /// The current source language.
331e8d8bef9SDimitry Andric   dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
332e8d8bef9SDimitry Andric 
3330b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
3340b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
3350b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
3380b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
3390b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
3400b57cec5SDimitry Andric 
34106c3fb27SDimitry Andric   /// Cache which blocks are in which funclet, if an EH funclet personality is
34206c3fb27SDimitry Andric   /// in use. Otherwise empty.
34306c3fb27SDimitry Andric   DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
34406c3fb27SDimitry Andric 
3450b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
3460b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
3490b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
3500b57cec5SDimitry Andric 
351fe6060f1SDimitry Andric   /// Cache of attribute lists verified.
352fe6060f1SDimitry Andric   SmallPtrSet<const void *, 32> AttributeListsVisited;
353fe6060f1SDimitry Andric 
3540b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3550b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3560b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3570b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3580b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3610b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3645f757f3fSDimitry Andric   ConvergenceVerifier ConvergenceVerifyHelper;
3650b57cec5SDimitry Andric 
366e8d8bef9SDimitry Andric   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
367e8d8bef9SDimitry Andric 
3680b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric public:
3710b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3720b57cec5SDimitry Andric                     const Module &M)
3730b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3740b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3750b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3760b57cec5SDimitry Andric   }
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   bool verify(const Function &F) {
3810b57cec5SDimitry Andric     assert(F.getParent() == &M &&
3820b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
3850b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
3860b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
3870b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
3880b57cec5SDimitry Andric     // this code outside of a pass manager.
3890b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
3900b57cec5SDimitry Andric     if (!F.empty())
3910b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
3940b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
3950b57cec5SDimitry Andric         continue;
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric       if (OS) {
3980b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
3990b57cec5SDimitry Andric             << "' does not have terminator!\n";
4000b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
4010b57cec5SDimitry Andric         *OS << "\n";
4020b57cec5SDimitry Andric       }
4030b57cec5SDimitry Andric       return false;
4040b57cec5SDimitry Andric     }
4050b57cec5SDimitry Andric 
4065f757f3fSDimitry Andric     auto FailureCB = [this](const Twine &Message) {
4075f757f3fSDimitry Andric       this->CheckFailed(Message);
4085f757f3fSDimitry Andric     };
4095f757f3fSDimitry Andric     ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
4105f757f3fSDimitry Andric 
4110b57cec5SDimitry Andric     Broken = false;
4120b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
4130b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
4140b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
4155f757f3fSDimitry Andric 
4165f757f3fSDimitry Andric     if (ConvergenceVerifyHelper.sawTokens())
4175f757f3fSDimitry Andric       ConvergenceVerifyHelper.verify(DT);
4185f757f3fSDimitry Andric 
4190b57cec5SDimitry Andric     InstsInThisBlock.clear();
4200b57cec5SDimitry Andric     DebugFnArgs.clear();
4210b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
4220b57cec5SDimitry Andric     SawFrameEscape = false;
4230b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
424e8d8bef9SDimitry Andric     verifyNoAliasScopeDecl();
425e8d8bef9SDimitry Andric     NoAliasScopeDecls.clear();
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric     return !Broken;
4280b57cec5SDimitry Andric   }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
4310b57cec5SDimitry Andric   bool verify() {
4320b57cec5SDimitry Andric     Broken = false;
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
4350b57cec5SDimitry Andric     for (const Function &F : M)
4360b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
4370b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
4400b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
4410b57cec5SDimitry Andric     verifyFrameRecoverIndices();
4420b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
4430b57cec5SDimitry Andric       visitGlobalVariable(GV);
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
4460b57cec5SDimitry Andric       visitGlobalAlias(GA);
4470b57cec5SDimitry Andric 
448349cc55cSDimitry Andric     for (const GlobalIFunc &GI : M.ifuncs())
449349cc55cSDimitry Andric       visitGlobalIFunc(GI);
450349cc55cSDimitry Andric 
4510b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
4520b57cec5SDimitry Andric       visitNamedMDNode(NMD);
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
4550b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
4560b57cec5SDimitry Andric 
457349cc55cSDimitry Andric     visitModuleFlags();
458349cc55cSDimitry Andric     visitModuleIdents();
459349cc55cSDimitry Andric     visitModuleCommandLines();
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric     verifyCompileUnits();
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
4640b57cec5SDimitry Andric     DISubprogramAttachments.clear();
4650b57cec5SDimitry Andric     return !Broken;
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric private:
4695ffd83dbSDimitry Andric   /// Whether a metadata node is allowed to be, or contain, a DILocation.
4705ffd83dbSDimitry Andric   enum class AreDebugLocsAllowed { No, Yes };
4715ffd83dbSDimitry Andric 
4720b57cec5SDimitry Andric   // Verification methods...
4730b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4740b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4750b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
476349cc55cSDimitry Andric   void visitGlobalIFunc(const GlobalIFunc &GI);
4770b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
4780b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
4790b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
4800b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
4815ffd83dbSDimitry Andric   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
4820b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
4830b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
4845f757f3fSDimitry Andric   void visitDIArgList(const DIArgList &AL, Function *F);
4850b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
486349cc55cSDimitry Andric   void visitModuleIdents();
487349cc55cSDimitry Andric   void visitModuleCommandLines();
488349cc55cSDimitry Andric   void visitModuleFlags();
4890b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
4900b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
4910b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
4920b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
4930b57cec5SDimitry Andric   void visitFunction(const Function &F);
4940b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
49506c3fb27SDimitry Andric   void verifyRangeMetadata(const Value &V, const MDNode *Range, Type *Ty,
49606c3fb27SDimitry Andric                            bool IsAbsoluteSymbol);
4970b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
4980b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
4998bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
500fcaf7f86SDimitry Andric   void visitCallStackMetadata(MDNode *MD);
501fcaf7f86SDimitry Andric   void visitMemProfMetadata(Instruction &I, MDNode *MD);
502fcaf7f86SDimitry Andric   void visitCallsiteMetadata(Instruction &I, MDNode *MD);
503bdd1243dSDimitry Andric   void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
504e8d8bef9SDimitry Andric   void visitAnnotationMetadata(MDNode *Annotation);
505349cc55cSDimitry Andric   void visitAliasScopeMetadata(const MDNode *MD);
506349cc55cSDimitry Andric   void visitAliasScopeListMetadata(const MDNode *MD);
50781ad6265SDimitry Andric   void visitAccessGroupMetadata(const MDNode *MD);
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
5100b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
5110b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
5120b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
5130b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
5140b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
5150b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // InstVisitor overrides...
5200b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
5210b57cec5SDimitry Andric   void visit(Instruction &I);
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
5240b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
5250b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
5260b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
5270b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
5280b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
5290b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
5300b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
5310b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
5320b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
5330b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
5340b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
5350b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
5360b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
5370b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
5380b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
5390b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
5400b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
5410b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
5420b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
5430b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
5440b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
5450b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
5460b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
5470b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
5480b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
5490b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
5500b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
5510b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
5520b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
5530b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
5540b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
5550b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
5560b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
5570b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
5580b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
5590b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
5600b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
5610b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
5620b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
5630b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
56481ad6265SDimitry Andric   void visitVPIntrinsic(VPIntrinsic &VPI);
5650b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
5660b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
5670b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
5680b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
5690b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
5700b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
5710b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
5720b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
5730b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
5740b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
5750b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
5760b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
5770b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
5780b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
5790b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
5800b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
5810b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
5840b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
5850eae32dcSDimitry Andric   void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
5860b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
5870b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
588fe6060f1SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
5890b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
590fe6060f1SDimitry Andric   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
591fe6060f1SDimitry Andric                                     const Value *V);
5920b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
59304eeddc0SDimitry Andric                            const Value *V, bool IsIntrinsic, bool IsInlineAsm);
5940b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
5970b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
59804eeddc0SDimitry Andric   void verifyInlineAsmCall(const CallBase &Call);
5990b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
6000b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
6010b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
6040b57cec5SDimitry Andric   template <typename ValueOrMetadata>
6050b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
6060b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
6070b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
6080b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
6098bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   /// Module-level debug info verification...
6120b57cec5SDimitry Andric   void verifyCompileUnits();
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
6150b57cec5SDimitry Andric   /// declarations share the same calling convention.
6160b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
6170b57cec5SDimitry Andric 
618349cc55cSDimitry Andric   void verifyAttachedCallBundle(const CallBase &Call,
619349cc55cSDimitry Andric                                 const OperandBundleUse &BU);
620349cc55cSDimitry Andric 
621e8d8bef9SDimitry Andric   /// Verify the llvm.experimental.noalias.scope.decl declarations
622e8d8bef9SDimitry Andric   void verifyNoAliasScopeDecl();
6230b57cec5SDimitry Andric };
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric } // end anonymous namespace
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
62881ad6265SDimitry Andric #define Check(C, ...)                                                          \
62981ad6265SDimitry Andric   do {                                                                         \
63081ad6265SDimitry Andric     if (!(C)) {                                                                \
63181ad6265SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
63281ad6265SDimitry Andric       return;                                                                  \
63381ad6265SDimitry Andric     }                                                                          \
63481ad6265SDimitry Andric   } while (false)
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
6370b57cec5SDimitry Andric /// an error message.
63881ad6265SDimitry Andric #define CheckDI(C, ...)                                                        \
63981ad6265SDimitry Andric   do {                                                                         \
64081ad6265SDimitry Andric     if (!(C)) {                                                                \
64181ad6265SDimitry Andric       DebugInfoCheckFailed(__VA_ARGS__);                                       \
64281ad6265SDimitry Andric       return;                                                                  \
64381ad6265SDimitry Andric     }                                                                          \
64481ad6265SDimitry Andric   } while (false)
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
6470b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
64881ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Operand is null", &I);
6490b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
6500b57cec5SDimitry Andric }
6510b57cec5SDimitry Andric 
6520eae32dcSDimitry Andric // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
6530b57cec5SDimitry Andric static void forEachUser(const Value *User,
6540b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
6550b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
6560b57cec5SDimitry Andric   if (!Visited.insert(User).second)
6570b57cec5SDimitry Andric     return;
6580eae32dcSDimitry Andric 
6590eae32dcSDimitry Andric   SmallVector<const Value *> WorkList;
6600eae32dcSDimitry Andric   append_range(WorkList, User->materialized_users());
6610eae32dcSDimitry Andric   while (!WorkList.empty()) {
6620eae32dcSDimitry Andric    const Value *Cur = WorkList.pop_back_val();
6630eae32dcSDimitry Andric     if (!Visited.insert(Cur).second)
6640eae32dcSDimitry Andric       continue;
6650eae32dcSDimitry Andric     if (Callback(Cur))
6660eae32dcSDimitry Andric       append_range(WorkList, Cur->materialized_users());
6670eae32dcSDimitry Andric   }
6680b57cec5SDimitry Andric }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
67181ad6265SDimitry Andric   Check(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
6720b57cec5SDimitry Andric         "Global is external, but doesn't have external or weak linkage!", &GV);
6730b57cec5SDimitry Andric 
6740eae32dcSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
6750eae32dcSDimitry Andric 
6760eae32dcSDimitry Andric     if (MaybeAlign A = GO->getAlign()) {
67781ad6265SDimitry Andric       Check(A->value() <= Value::MaximumAlignment,
6785ffd83dbSDimitry Andric             "huge alignment values are unsupported", GO);
6790eae32dcSDimitry Andric     }
68006c3fb27SDimitry Andric 
68106c3fb27SDimitry Andric     if (const MDNode *Associated =
68206c3fb27SDimitry Andric             GO->getMetadata(LLVMContext::MD_associated)) {
68306c3fb27SDimitry Andric       Check(Associated->getNumOperands() == 1,
68406c3fb27SDimitry Andric             "associated metadata must have one operand", &GV, Associated);
68506c3fb27SDimitry Andric       const Metadata *Op = Associated->getOperand(0).get();
68606c3fb27SDimitry Andric       Check(Op, "associated metadata must have a global value", GO, Associated);
68706c3fb27SDimitry Andric 
68806c3fb27SDimitry Andric       const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
68906c3fb27SDimitry Andric       Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
69006c3fb27SDimitry Andric       if (VM) {
69106c3fb27SDimitry Andric         Check(isa<PointerType>(VM->getValue()->getType()),
69206c3fb27SDimitry Andric               "associated value must be pointer typed", GV, Associated);
69306c3fb27SDimitry Andric 
69406c3fb27SDimitry Andric         const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
69506c3fb27SDimitry Andric         Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
69606c3fb27SDimitry Andric               "associated metadata must point to a GlobalObject", GO, Stripped);
69706c3fb27SDimitry Andric         Check(Stripped != GO,
69806c3fb27SDimitry Andric               "global values should not associate to themselves", GO,
69906c3fb27SDimitry Andric               Associated);
7000eae32dcSDimitry Andric       }
70106c3fb27SDimitry Andric     }
70206c3fb27SDimitry Andric 
70306c3fb27SDimitry Andric     // FIXME: Why is getMetadata on GlobalValue protected?
70406c3fb27SDimitry Andric     if (const MDNode *AbsoluteSymbol =
70506c3fb27SDimitry Andric             GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
70606c3fb27SDimitry Andric       verifyRangeMetadata(*GO, AbsoluteSymbol, DL.getIntPtrType(GO->getType()),
70706c3fb27SDimitry Andric                           true);
70806c3fb27SDimitry Andric     }
70906c3fb27SDimitry Andric   }
71006c3fb27SDimitry Andric 
71181ad6265SDimitry Andric   Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
7120b57cec5SDimitry Andric         "Only global variables can have appending linkage!", &GV);
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
7150b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
71681ad6265SDimitry Andric     Check(GVar && GVar->getValueType()->isArrayTy(),
7170b57cec5SDimitry Andric           "Only global arrays can have appending linkage!", GVar);
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
72181ad6265SDimitry Andric     Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
7220b57cec5SDimitry Andric 
723bdd1243dSDimitry Andric   if (GV.hasDLLExportStorageClass()) {
724bdd1243dSDimitry Andric     Check(!GV.hasHiddenVisibility(),
725bdd1243dSDimitry Andric           "dllexport GlobalValue must have default or protected visibility",
726bdd1243dSDimitry Andric           &GV);
727bdd1243dSDimitry Andric   }
7280b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
729bdd1243dSDimitry Andric     Check(GV.hasDefaultVisibility(),
730bdd1243dSDimitry Andric           "dllimport GlobalValue must have default visibility", &GV);
73181ad6265SDimitry Andric     Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
73281ad6265SDimitry Andric           &GV);
7330b57cec5SDimitry Andric 
73481ad6265SDimitry Andric     Check((GV.isDeclaration() &&
735e8d8bef9SDimitry Andric            (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
7360b57cec5SDimitry Andric               GV.hasAvailableExternallyLinkage(),
7370b57cec5SDimitry Andric           "Global is marked as dllimport, but not external", &GV);
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric 
7405ffd83dbSDimitry Andric   if (GV.isImplicitDSOLocal())
74181ad6265SDimitry Andric     Check(GV.isDSOLocal(),
7425ffd83dbSDimitry Andric           "GlobalValue with local linkage or non-default "
7435ffd83dbSDimitry Andric           "visibility must be dso_local!",
7440b57cec5SDimitry Andric           &GV);
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
7470b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
7480b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
7490b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
7500b57cec5SDimitry Andric                     I);
7510b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
7520b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
7530b57cec5SDimitry Andric                     I->getParent()->getParent(),
7540b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
7550b57cec5SDimitry Andric       return false;
7560b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
7570b57cec5SDimitry Andric       if (F->getParent() != &M)
7580b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
7590b57cec5SDimitry Andric                     F, F->getParent());
7600b57cec5SDimitry Andric       return false;
7610b57cec5SDimitry Andric     }
7620b57cec5SDimitry Andric     return true;
7630b57cec5SDimitry Andric   });
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
7670b57cec5SDimitry Andric   if (GV.hasInitializer()) {
76881ad6265SDimitry Andric     Check(GV.getInitializer()->getType() == GV.getValueType(),
7690b57cec5SDimitry Andric           "Global variable initializer type does not match global "
7700b57cec5SDimitry Andric           "variable type!",
7710b57cec5SDimitry Andric           &GV);
7720b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
7730b57cec5SDimitry Andric     // cannot be constant.
7740b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
77581ad6265SDimitry Andric       Check(GV.getInitializer()->isNullValue(),
7760b57cec5SDimitry Andric             "'common' global must have a zero initializer!", &GV);
77781ad6265SDimitry Andric       Check(!GV.isConstant(), "'common' global may not be marked constant!",
7780b57cec5SDimitry Andric             &GV);
77981ad6265SDimitry Andric       Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
7800b57cec5SDimitry Andric     }
7810b57cec5SDimitry Andric   }
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
7840b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
78581ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
7860b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
78706c3fb27SDimitry Andric     Check(GV.materialized_use_empty(),
78806c3fb27SDimitry Andric           "invalid uses of intrinsic global variable", &GV);
78906c3fb27SDimitry Andric 
7900b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
7910b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
7920b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
7930b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
7940b57cec5SDimitry Andric       PointerType *FuncPtrTy =
7955f757f3fSDimitry Andric           PointerType::get(Context, DL.getProgramAddressSpace());
79681ad6265SDimitry Andric       Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
7970b57cec5SDimitry Andric                 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
7980b57cec5SDimitry Andric                 STy->getTypeAtIndex(1) == FuncPtrTy,
7990b57cec5SDimitry Andric             "wrong type for intrinsic global variable", &GV);
80081ad6265SDimitry Andric       Check(STy->getNumElements() == 3,
8010b57cec5SDimitry Andric             "the third field of the element type is mandatory, "
802bdd1243dSDimitry Andric             "specify ptr null to migrate from the obsoleted 2-field form");
8030b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
80406c3fb27SDimitry Andric       Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
80506c3fb27SDimitry Andric             &GV);
8060b57cec5SDimitry Andric     }
8070b57cec5SDimitry Andric   }
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
8100b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
81181ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
8120b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
81306c3fb27SDimitry Andric     Check(GV.materialized_use_empty(),
81406c3fb27SDimitry Andric           "invalid uses of intrinsic global variable", &GV);
81506c3fb27SDimitry Andric 
8160b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
8170b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
8180b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
81981ad6265SDimitry Andric       Check(PTy, "wrong type for intrinsic global variable", &GV);
8200b57cec5SDimitry Andric       if (GV.hasInitializer()) {
8210b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
8220b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
82381ad6265SDimitry Andric         Check(InitArray, "wrong initalizer for intrinsic global variable",
8240b57cec5SDimitry Andric               Init);
8250b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
8268bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
82781ad6265SDimitry Andric           Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
8280b57cec5SDimitry Andric                     isa<GlobalAlias>(V),
8290eae32dcSDimitry Andric                 Twine("invalid ") + GV.getName() + " member", V);
83081ad6265SDimitry Andric           Check(V->hasName(),
8310eae32dcSDimitry Andric                 Twine("members of ") + GV.getName() + " must be named", V);
8320b57cec5SDimitry Andric         }
8330b57cec5SDimitry Andric       }
8340b57cec5SDimitry Andric     }
8350b57cec5SDimitry Andric   }
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   // Visit any debug info attachments.
8380b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
8390b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
8400b57cec5SDimitry Andric   for (auto *MD : MDs) {
8410b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
8420b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
8430b57cec5SDimitry Andric     else
84481ad6265SDimitry Andric       CheckDI(false, "!dbg attachment of global variable must be a "
8450b57cec5SDimitry Andric                      "DIGlobalVariableExpression");
8460b57cec5SDimitry Andric   }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
8495f757f3fSDimitry Andric   // the runtime size.
8505f757f3fSDimitry Andric   Check(!GV.getValueType()->isScalableTy(),
8515f757f3fSDimitry Andric         "Globals cannot contain scalable types", &GV);
852e8d8bef9SDimitry Andric 
853bdd1243dSDimitry Andric   // Check if it's a target extension type that disallows being used as a
854bdd1243dSDimitry Andric   // global.
855bdd1243dSDimitry Andric   if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
856bdd1243dSDimitry Andric     Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
857bdd1243dSDimitry Andric           "Global @" + GV.getName() + " has illegal target extension type",
858bdd1243dSDimitry Andric           TTy);
859bdd1243dSDimitry Andric 
8600b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
8610b57cec5SDimitry Andric     visitGlobalValue(GV);
8620b57cec5SDimitry Andric     return;
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
8660b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric   visitGlobalValue(GV);
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
8720b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
8730b57cec5SDimitry Andric   Visited.insert(&GA);
8740b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
8780b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
879bdd1243dSDimitry Andric   if (GA.hasAvailableExternallyLinkage()) {
880bdd1243dSDimitry Andric     Check(isa<GlobalValue>(C) &&
881bdd1243dSDimitry Andric               cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
882bdd1243dSDimitry Andric           "available_externally alias must point to available_externally "
883bdd1243dSDimitry Andric           "global value",
884bdd1243dSDimitry Andric           &GA);
885bdd1243dSDimitry Andric   }
8860b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
887bdd1243dSDimitry Andric     if (!GA.hasAvailableExternallyLinkage()) {
88881ad6265SDimitry Andric       Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
8890b57cec5SDimitry Andric             &GA);
890bdd1243dSDimitry Andric     }
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
89381ad6265SDimitry Andric       Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
8940b57cec5SDimitry Andric 
89581ad6265SDimitry Andric       Check(!GA2->isInterposable(),
89681ad6265SDimitry Andric             "Alias cannot point to an interposable alias", &GA);
8970b57cec5SDimitry Andric     } else {
8980b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
8990b57cec5SDimitry Andric       // Do not recurse into global initializers.
9000b57cec5SDimitry Andric       return;
9010b57cec5SDimitry Andric     }
9020b57cec5SDimitry Andric   }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
9050b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
9080b57cec5SDimitry Andric     Value *V = &*U;
9090b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
9100b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
9110b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
9120b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
9130b57cec5SDimitry Andric   }
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
91781ad6265SDimitry Andric   Check(GlobalAlias::isValidLinkage(GA.getLinkage()),
9180b57cec5SDimitry Andric         "Alias should have private, internal, linkonce, weak, linkonce_odr, "
919bdd1243dSDimitry Andric         "weak_odr, external, or available_externally linkage!",
9200b57cec5SDimitry Andric         &GA);
9210b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
92281ad6265SDimitry Andric   Check(Aliasee, "Aliasee cannot be NULL!", &GA);
92381ad6265SDimitry Andric   Check(GA.getType() == Aliasee->getType(),
9240b57cec5SDimitry Andric         "Alias and aliasee types should match!", &GA);
9250b57cec5SDimitry Andric 
92681ad6265SDimitry Andric   Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
9270b57cec5SDimitry Andric         "Aliasee should be either GlobalValue or ConstantExpr", &GA);
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   visitGlobalValue(GA);
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric 
934349cc55cSDimitry Andric void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
93581ad6265SDimitry Andric   Check(GlobalIFunc::isValidLinkage(GI.getLinkage()),
93681ad6265SDimitry Andric         "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
93781ad6265SDimitry Andric         "weak_odr, or external linkage!",
93881ad6265SDimitry Andric         &GI);
939349cc55cSDimitry Andric   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
94081ad6265SDimitry Andric   // is a Function definition.
941349cc55cSDimitry Andric   const Function *Resolver = GI.getResolverFunction();
94281ad6265SDimitry Andric   Check(Resolver, "IFunc must have a Function resolver", &GI);
94381ad6265SDimitry Andric   Check(!Resolver->isDeclarationForLinker(),
94481ad6265SDimitry Andric         "IFunc resolver must be a definition", &GI);
945349cc55cSDimitry Andric 
946349cc55cSDimitry Andric   // Check that the immediate resolver operand (prior to any bitcasts) has the
94781ad6265SDimitry Andric   // correct type.
948349cc55cSDimitry Andric   const Type *ResolverTy = GI.getResolver()->getType();
949bdd1243dSDimitry Andric 
950bdd1243dSDimitry Andric   Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
951bdd1243dSDimitry Andric         "IFunc resolver must return a pointer", &GI);
952bdd1243dSDimitry Andric 
953349cc55cSDimitry Andric   const Type *ResolverFuncTy =
954349cc55cSDimitry Andric       GlobalIFunc::getResolverFunctionType(GI.getValueType());
955bdd1243dSDimitry Andric   Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
956349cc55cSDimitry Andric         "IFunc resolver has incorrect type", &GI);
957349cc55cSDimitry Andric }
958349cc55cSDimitry Andric 
9590b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
9600b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
9610b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
9625f757f3fSDimitry Andric   if (NMD.getName().starts_with("llvm.dbg."))
96381ad6265SDimitry Andric     CheckDI(NMD.getName() == "llvm.dbg.cu",
96481ad6265SDimitry Andric             "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
9650b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
9660b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
96781ad6265SDimitry Andric       CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric     if (!MD)
9700b57cec5SDimitry Andric       continue;
9710b57cec5SDimitry Andric 
9725ffd83dbSDimitry Andric     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
9730b57cec5SDimitry Andric   }
9740b57cec5SDimitry Andric }
9750b57cec5SDimitry Andric 
9765ffd83dbSDimitry Andric void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
9770b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
9780b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
9790b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
9800b57cec5SDimitry Andric     return;
9810b57cec5SDimitry Andric 
98281ad6265SDimitry Andric   Check(&MD.getContext() == &Context,
983fe6060f1SDimitry Andric         "MDNode context does not match Module context!", &MD);
984fe6060f1SDimitry Andric 
9850b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
9860b57cec5SDimitry Andric   default:
9870b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
9880b57cec5SDimitry Andric   case Metadata::MDTupleKind:
9890b57cec5SDimitry Andric     break;
9900b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
9910b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
9920b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
9930b57cec5SDimitry Andric     break;
9940b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
9950b57cec5SDimitry Andric   }
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
9980b57cec5SDimitry Andric     if (!Op)
9990b57cec5SDimitry Andric       continue;
100081ad6265SDimitry Andric     Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
10010b57cec5SDimitry Andric           &MD, Op);
100281ad6265SDimitry Andric     CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
10035ffd83dbSDimitry Andric             "DILocation not allowed within this metadata node", &MD, Op);
10040b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
10055ffd83dbSDimitry Andric       visitMDNode(*N, AllowLocs);
10060b57cec5SDimitry Andric       continue;
10070b57cec5SDimitry Andric     }
10080b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
10090b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
10100b57cec5SDimitry Andric       continue;
10110b57cec5SDimitry Andric     }
10120b57cec5SDimitry Andric   }
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
101581ad6265SDimitry Andric   Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
101681ad6265SDimitry Andric   Check(MD.isResolved(), "All nodes should be resolved!", &MD);
10170b57cec5SDimitry Andric }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
102081ad6265SDimitry Andric   Check(MD.getValue(), "Expected valid value", &MD);
102181ad6265SDimitry Andric   Check(!MD.getValue()->getType()->isMetadataTy(),
10220b57cec5SDimitry Andric         "Unexpected metadata round-trip through values", &MD, MD.getValue());
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
10250b57cec5SDimitry Andric   if (!L)
10260b57cec5SDimitry Andric     return;
10270b57cec5SDimitry Andric 
102881ad6265SDimitry Andric   Check(F, "function-local metadata used outside a function", L);
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
10310b57cec5SDimitry Andric   // function that we expect.
10320b57cec5SDimitry Andric   Function *ActualF = nullptr;
10330b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
103481ad6265SDimitry Andric     Check(I->getParent(), "function-local metadata not in basic block", L, I);
10350b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
10360b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
10370b57cec5SDimitry Andric     ActualF = BB->getParent();
10380b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
10390b57cec5SDimitry Andric     ActualF = A->getParent();
10400b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
10410b57cec5SDimitry Andric 
104281ad6265SDimitry Andric   Check(ActualF == F, "function-local metadata used in wrong function", L);
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric 
10455f757f3fSDimitry Andric void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
10465f757f3fSDimitry Andric   for (const ValueAsMetadata *VAM : AL.getArgs())
10475f757f3fSDimitry Andric     visitValueAsMetadata(*VAM, F);
10485f757f3fSDimitry Andric }
10495f757f3fSDimitry Andric 
10500b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
10510b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
10520b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
10535ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::No);
10540b57cec5SDimitry Andric     return;
10550b57cec5SDimitry Andric   }
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
10580b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
10590b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
10600b57cec5SDimitry Andric     return;
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
10630b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
10645f757f3fSDimitry Andric 
10655f757f3fSDimitry Andric   if (auto *AL = dyn_cast<DIArgList>(MD))
10665f757f3fSDimitry Andric     visitDIArgList(*AL, F);
10670b57cec5SDimitry Andric }
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
10700b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
10710b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
107481ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
10750b57cec5SDimitry Andric           "location requires a valid scope", &N, N.getRawScope());
10760b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
107781ad6265SDimitry Andric     CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
10780b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
107981ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
108381ad6265SDimitry Andric   CheckDI(N.getTag(), "invalid tag", &N);
10840b57cec5SDimitry Andric }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
10870b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
108881ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
10890b57cec5SDimitry Andric }
10900b57cec5SDimitry Andric 
10910b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
109281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1093e8d8bef9SDimitry Andric   bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
109481ad6265SDimitry Andric   CheckDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
1095e8d8bef9SDimitry Andric               N.getRawUpperBound(),
10965ffd83dbSDimitry Andric           "Subrange must contain count or upperBound", &N);
109781ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
10985ffd83dbSDimitry Andric           "Subrange can have any one of count or upperBound", &N);
1099fe6060f1SDimitry Andric   auto *CBound = N.getRawCountNode();
110081ad6265SDimitry Andric   CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1101fe6060f1SDimitry Andric               isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1102fe6060f1SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
11030b57cec5SDimitry Andric   auto Count = N.getCount();
110406c3fb27SDimitry Andric   CheckDI(!Count || !isa<ConstantInt *>(Count) ||
110506c3fb27SDimitry Andric               cast<ConstantInt *>(Count)->getSExtValue() >= -1,
11060b57cec5SDimitry Andric           "invalid subrange count", &N);
11075ffd83dbSDimitry Andric   auto *LBound = N.getRawLowerBound();
110881ad6265SDimitry Andric   CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
11095ffd83dbSDimitry Andric               isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
11105ffd83dbSDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
11115ffd83dbSDimitry Andric           &N);
11125ffd83dbSDimitry Andric   auto *UBound = N.getRawUpperBound();
111381ad6265SDimitry Andric   CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
11145ffd83dbSDimitry Andric               isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
11155ffd83dbSDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
11165ffd83dbSDimitry Andric           &N);
11175ffd83dbSDimitry Andric   auto *Stride = N.getRawStride();
111881ad6265SDimitry Andric   CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
11195ffd83dbSDimitry Andric               isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
11205ffd83dbSDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
11210b57cec5SDimitry Andric }
11220b57cec5SDimitry Andric 
1123e8d8bef9SDimitry Andric void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
112481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
112581ad6265SDimitry Andric   CheckDI(N.getRawCountNode() || N.getRawUpperBound(),
1126e8d8bef9SDimitry Andric           "GenericSubrange must contain count or upperBound", &N);
112781ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1128e8d8bef9SDimitry Andric           "GenericSubrange can have any one of count or upperBound", &N);
1129e8d8bef9SDimitry Andric   auto *CBound = N.getRawCountNode();
113081ad6265SDimitry Andric   CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1131e8d8bef9SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
1132e8d8bef9SDimitry Andric   auto *LBound = N.getRawLowerBound();
113381ad6265SDimitry Andric   CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
113481ad6265SDimitry Andric   CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1135e8d8bef9SDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
1136e8d8bef9SDimitry Andric           &N);
1137e8d8bef9SDimitry Andric   auto *UBound = N.getRawUpperBound();
113881ad6265SDimitry Andric   CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1139e8d8bef9SDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
1140e8d8bef9SDimitry Andric           &N);
1141e8d8bef9SDimitry Andric   auto *Stride = N.getRawStride();
114281ad6265SDimitry Andric   CheckDI(Stride, "GenericSubrange must contain stride", &N);
114381ad6265SDimitry Andric   CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1144e8d8bef9SDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
1145e8d8bef9SDimitry Andric }
1146e8d8bef9SDimitry Andric 
11470b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
114881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
115281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1153e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_unspecified_type ||
1154e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_string_type,
11550b57cec5SDimitry Andric           "invalid tag", &N);
1156e8d8bef9SDimitry Andric }
1157e8d8bef9SDimitry Andric 
1158e8d8bef9SDimitry Andric void Verifier::visitDIStringType(const DIStringType &N) {
115981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
116081ad6265SDimitry Andric   CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
116181ad6265SDimitry Andric           &N);
11620b57cec5SDimitry Andric }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
11650b57cec5SDimitry Andric   // Common scope checks.
11660b57cec5SDimitry Andric   visitDIScope(N);
11670b57cec5SDimitry Andric 
116881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
11690b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_pointer_type ||
11700b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
11710b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_reference_type ||
11720b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
11730b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_const_type ||
117404eeddc0SDimitry Andric               N.getTag() == dwarf::DW_TAG_immutable_type ||
11750b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_volatile_type ||
11760b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_restrict_type ||
11770b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_atomic_type ||
11780b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_member ||
11795f757f3fSDimitry Andric               (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
11800b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_inheritance ||
1181fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_friend ||
1182fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_set_type,
11830b57cec5SDimitry Andric           "invalid tag", &N);
11840b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
118581ad6265SDimitry Andric     CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
11860b57cec5SDimitry Andric             N.getRawExtraData());
11870b57cec5SDimitry Andric   }
11880b57cec5SDimitry Andric 
1189fe6060f1SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_set_type) {
1190fe6060f1SDimitry Andric     if (auto *T = N.getRawBaseType()) {
1191fe6060f1SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1192fe6060f1SDimitry Andric       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
119381ad6265SDimitry Andric       CheckDI(
1194fe6060f1SDimitry Andric           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1195fe6060f1SDimitry Andric               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1196fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1197fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1198fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1199fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1200fe6060f1SDimitry Andric           "invalid set base type", &N, T);
1201fe6060f1SDimitry Andric     }
1202fe6060f1SDimitry Andric   }
1203fe6060f1SDimitry Andric 
120481ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
120581ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
12060b57cec5SDimitry Andric           N.getRawBaseType());
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
120981ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
12100b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_reference_type ||
12110b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
12120b57cec5SDimitry Andric             "DWARF address space only applies to pointer or reference types",
12130b57cec5SDimitry Andric             &N);
12140b57cec5SDimitry Andric   }
12150b57cec5SDimitry Andric }
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric /// Detect mutually exclusive flags.
12180b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
12190b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
12200b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
12210b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
12220b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
12230b57cec5SDimitry Andric }
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
12260b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
122781ad6265SDimitry Andric   CheckDI(Params, "invalid template params", &N, &RawParams);
12280b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
122981ad6265SDimitry Andric     CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
12300b57cec5SDimitry Andric             &N, Params, Op);
12310b57cec5SDimitry Andric   }
12320b57cec5SDimitry Andric }
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
12350b57cec5SDimitry Andric   // Common scope checks.
12360b57cec5SDimitry Andric   visitDIScope(N);
12370b57cec5SDimitry Andric 
123881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
12390b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_structure_type ||
12400b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_union_type ||
12410b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_enumeration_type ||
12420b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_class_type ||
1243349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_variant_part ||
1244349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_namelist,
12450b57cec5SDimitry Andric           "invalid tag", &N);
12460b57cec5SDimitry Andric 
124781ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
124881ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
12490b57cec5SDimitry Andric           N.getRawBaseType());
12500b57cec5SDimitry Andric 
125181ad6265SDimitry Andric   CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
12520b57cec5SDimitry Andric           "invalid composite elements", &N, N.getRawElements());
125381ad6265SDimitry Andric   CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
12540b57cec5SDimitry Andric           N.getRawVTableHolder());
125581ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
12560b57cec5SDimitry Andric           "invalid reference flags", &N);
12578bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
125881ad6265SDimitry Andric   CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
12598bcb0991SDimitry Andric           "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric   if (N.isVector()) {
12620b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
126381ad6265SDimitry Andric     CheckDI(Elements.size() == 1 &&
12640b57cec5SDimitry Andric                 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
12650b57cec5SDimitry Andric             "invalid vector, expected one element of type subrange", &N);
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
12690b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
127281ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
12730b57cec5SDimitry Andric             "discriminator can only appear on variant part");
12740b57cec5SDimitry Andric   }
12755ffd83dbSDimitry Andric 
12765ffd83dbSDimitry Andric   if (N.getRawDataLocation()) {
127781ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
12785ffd83dbSDimitry Andric             "dataLocation can only appear in array type");
12795ffd83dbSDimitry Andric   }
1280e8d8bef9SDimitry Andric 
1281e8d8bef9SDimitry Andric   if (N.getRawAssociated()) {
128281ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1283e8d8bef9SDimitry Andric             "associated can only appear in array type");
1284e8d8bef9SDimitry Andric   }
1285e8d8bef9SDimitry Andric 
1286e8d8bef9SDimitry Andric   if (N.getRawAllocated()) {
128781ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1288e8d8bef9SDimitry Andric             "allocated can only appear in array type");
1289e8d8bef9SDimitry Andric   }
1290e8d8bef9SDimitry Andric 
1291e8d8bef9SDimitry Andric   if (N.getRawRank()) {
129281ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1293e8d8bef9SDimitry Andric             "rank can only appear in array type");
1294e8d8bef9SDimitry Andric   }
12955f757f3fSDimitry Andric 
12965f757f3fSDimitry Andric   if (N.getTag() == dwarf::DW_TAG_array_type) {
12975f757f3fSDimitry Andric     CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
12985f757f3fSDimitry Andric   }
12990b57cec5SDimitry Andric }
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
130281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
13030b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
130481ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
13050b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
130681ad6265SDimitry Andric       CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
13070b57cec5SDimitry Andric     }
13080b57cec5SDimitry Andric   }
130981ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
13100b57cec5SDimitry Andric           "invalid reference flags", &N);
13110b57cec5SDimitry Andric }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
131481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1315bdd1243dSDimitry Andric   std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
13160b57cec5SDimitry Andric   if (Checksum) {
131781ad6265SDimitry Andric     CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
13180b57cec5SDimitry Andric             "invalid checksum kind", &N);
13190b57cec5SDimitry Andric     size_t Size;
13200b57cec5SDimitry Andric     switch (Checksum->Kind) {
13210b57cec5SDimitry Andric     case DIFile::CSK_MD5:
13220b57cec5SDimitry Andric       Size = 32;
13230b57cec5SDimitry Andric       break;
13240b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
13250b57cec5SDimitry Andric       Size = 40;
13260b57cec5SDimitry Andric       break;
13275ffd83dbSDimitry Andric     case DIFile::CSK_SHA256:
13285ffd83dbSDimitry Andric       Size = 64;
13295ffd83dbSDimitry Andric       break;
13300b57cec5SDimitry Andric     }
133181ad6265SDimitry Andric     CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
133281ad6265SDimitry Andric     CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
13330b57cec5SDimitry Andric             "invalid checksum", &N);
13340b57cec5SDimitry Andric   }
13350b57cec5SDimitry Andric }
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
133881ad6265SDimitry Andric   CheckDI(N.isDistinct(), "compile units must be distinct", &N);
133981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
13420b57cec5SDimitry Andric   // as those could be empty.
134381ad6265SDimitry Andric   CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
13440b57cec5SDimitry Andric           N.getRawFile());
134581ad6265SDimitry Andric   CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
13460b57cec5SDimitry Andric           N.getFile());
13470b57cec5SDimitry Andric 
1348e8d8bef9SDimitry Andric   CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1349e8d8bef9SDimitry Andric 
135081ad6265SDimitry Andric   CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
13510b57cec5SDimitry Andric           "invalid emission kind", &N);
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
135481ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
13550b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
13560b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
135781ad6265SDimitry Andric       CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
13580b57cec5SDimitry Andric               "invalid enum type", &N, N.getEnumTypes(), Op);
13590b57cec5SDimitry Andric     }
13600b57cec5SDimitry Andric   }
13610b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
136281ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
13630b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
136481ad6265SDimitry Andric       CheckDI(
136581ad6265SDimitry Andric           Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
13660b57cec5SDimitry Andric                                      !cast<DISubprogram>(Op)->isDefinition())),
13670b57cec5SDimitry Andric           "invalid retained type", &N, Op);
13680b57cec5SDimitry Andric     }
13690b57cec5SDimitry Andric   }
13700b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
137181ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
13720b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
137381ad6265SDimitry Andric       CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
13740b57cec5SDimitry Andric               "invalid global variable ref", &N, Op);
13750b57cec5SDimitry Andric     }
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
137881ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
13790b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
138081ad6265SDimitry Andric       CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
13810b57cec5SDimitry Andric               &N, Op);
13820b57cec5SDimitry Andric     }
13830b57cec5SDimitry Andric   }
13840b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
138581ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
13860b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
138781ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
13880b57cec5SDimitry Andric     }
13890b57cec5SDimitry Andric   }
13900b57cec5SDimitry Andric   CUVisited.insert(&N);
13910b57cec5SDimitry Andric }
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
139481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
139581ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
13960b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
139781ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
13980b57cec5SDimitry Andric   else
139981ad6265SDimitry Andric     CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
14000b57cec5SDimitry Andric   if (auto *T = N.getRawType())
140181ad6265SDimitry Andric     CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
140281ad6265SDimitry Andric   CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
14030b57cec5SDimitry Andric           N.getRawContainingType());
14040b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
14050b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
14060b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
140781ad6265SDimitry Andric     CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
14080b57cec5SDimitry Andric             "invalid subprogram declaration", &N, S);
14090b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
14100b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
141181ad6265SDimitry Andric     CheckDI(Node, "invalid retained nodes list", &N, RawNode);
14120b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
141306c3fb27SDimitry Andric       CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op) ||
141406c3fb27SDimitry Andric                      isa<DIImportedEntity>(Op)),
141506c3fb27SDimitry Andric               "invalid retained nodes, expected DILocalVariable, DILabel or "
141606c3fb27SDimitry Andric               "DIImportedEntity",
141706c3fb27SDimitry Andric               &N, Node, Op);
14180b57cec5SDimitry Andric     }
14190b57cec5SDimitry Andric   }
142081ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
14210b57cec5SDimitry Andric           "invalid reference flags", &N);
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
14240b57cec5SDimitry Andric   if (N.isDefinition()) {
14250b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
142681ad6265SDimitry Andric     CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
142781ad6265SDimitry Andric     CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
142881ad6265SDimitry Andric     CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
14295f757f3fSDimitry Andric     // There's no good way to cross the CU boundary to insert a nested
14305f757f3fSDimitry Andric     // DISubprogram definition in one CU into a type defined in another CU.
14315f757f3fSDimitry Andric     auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
14325f757f3fSDimitry Andric     if (CT && CT->getRawIdentifier() &&
14335f757f3fSDimitry Andric         M.getContext().isODRUniquingDebugTypes())
14345f757f3fSDimitry Andric       CheckDI(N.getDeclaration(),
14355f757f3fSDimitry Andric               "definition subprograms cannot be nested within DICompositeType "
14365f757f3fSDimitry Andric               "when enabling ODR",
14375f757f3fSDimitry Andric               &N);
14380b57cec5SDimitry Andric   } else {
14390b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
144081ad6265SDimitry Andric     CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
144106c3fb27SDimitry Andric     CheckDI(!N.getRawDeclaration(),
144206c3fb27SDimitry Andric             "subprogram declaration must not have a declaration field");
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
14460b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
144781ad6265SDimitry Andric     CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
14480b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
144981ad6265SDimitry Andric       CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
14500b57cec5SDimitry Andric               Op);
14510b57cec5SDimitry Andric   }
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
145481ad6265SDimitry Andric     CheckDI(N.isDefinition(),
14550b57cec5SDimitry Andric             "DIFlagAllCallsDescribed must be attached to a definition");
14560b57cec5SDimitry Andric }
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
145981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
146081ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
14610b57cec5SDimitry Andric           "invalid local scope", &N, N.getRawScope());
14620b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
146381ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
14640b57cec5SDimitry Andric }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
14670b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
14680b57cec5SDimitry Andric 
146981ad6265SDimitry Andric   CheckDI(N.getLine() || !N.getColumn(),
14700b57cec5SDimitry Andric           "cannot have column info without line info", &N);
14710b57cec5SDimitry Andric }
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
14740b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
14750b57cec5SDimitry Andric }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
147881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
14790b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
148081ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
14810b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
148281ad6265SDimitry Andric     CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
14830b57cec5SDimitry Andric }
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
148681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
14870b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
148881ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
14890b57cec5SDimitry Andric }
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
149281ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
14930b57cec5SDimitry Andric               N.getMacinfoType() == dwarf::DW_MACINFO_undef,
14940b57cec5SDimitry Andric           "invalid macinfo type", &N);
149581ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous macro", &N);
14960b57cec5SDimitry Andric   if (!N.getValue().empty()) {
14970b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
14980b57cec5SDimitry Andric   }
14990b57cec5SDimitry Andric }
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
150281ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
15030b57cec5SDimitry Andric           "invalid macinfo type", &N);
15040b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
150581ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
150881ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
15090b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
151081ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
15110b57cec5SDimitry Andric     }
15120b57cec5SDimitry Andric   }
15130b57cec5SDimitry Andric }
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
151681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
151781ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous module", &N);
15180b57cec5SDimitry Andric }
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
152181ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
15220b57cec5SDimitry Andric }
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
15250b57cec5SDimitry Andric   visitDITemplateParameter(N);
15260b57cec5SDimitry Andric 
152781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
15280b57cec5SDimitry Andric           &N);
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
15320b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
15330b57cec5SDimitry Andric   visitDITemplateParameter(N);
15340b57cec5SDimitry Andric 
153581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
15360b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
15370b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
15380b57cec5SDimitry Andric           "invalid tag", &N);
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
15420b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
154381ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
15440b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
154581ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15460b57cec5SDimitry Andric }
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
15490b57cec5SDimitry Andric   // Checks common to all variables.
15500b57cec5SDimitry Andric   visitDIVariable(N);
15510b57cec5SDimitry Andric 
155281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
155381ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
155481ad6265SDimitry Andric   // Check only if the global variable is not an extern
15555ffd83dbSDimitry Andric   if (N.isDefinition())
155681ad6265SDimitry Andric     CheckDI(N.getType(), "missing global variable type", &N);
15570b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
155881ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(Member),
15590b57cec5SDimitry Andric             "invalid static data member declaration", &N, Member);
15600b57cec5SDimitry Andric   }
15610b57cec5SDimitry Andric }
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
15640b57cec5SDimitry Andric   // Checks common to all variables.
15650b57cec5SDimitry Andric   visitDIVariable(N);
15660b57cec5SDimitry Andric 
156781ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
156881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
156981ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15700b57cec5SDimitry Andric           "local variable requires a valid scope", &N, N.getRawScope());
15710b57cec5SDimitry Andric   if (auto Ty = N.getType())
157281ad6265SDimitry Andric     CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
15730b57cec5SDimitry Andric }
15740b57cec5SDimitry Andric 
1575bdd1243dSDimitry Andric void Verifier::visitDIAssignID(const DIAssignID &N) {
1576bdd1243dSDimitry Andric   CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1577bdd1243dSDimitry Andric   CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1578bdd1243dSDimitry Andric }
1579bdd1243dSDimitry Andric 
15800b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
15810b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
158281ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
15830b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
158481ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15850b57cec5SDimitry Andric 
158681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
158781ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15880b57cec5SDimitry Andric           "label requires a valid scope", &N, N.getRawScope());
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
159281ad6265SDimitry Andric   CheckDI(N.isValid(), "invalid expression", &N);
15930b57cec5SDimitry Andric }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
15960b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
159781ad6265SDimitry Andric   CheckDI(GVE.getVariable(), "missing variable");
15980b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
15990b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
16000b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
16010b57cec5SDimitry Andric     visitDIExpression(*Expr);
16020b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
16030b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
16040b57cec5SDimitry Andric   }
16050b57cec5SDimitry Andric }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
160881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
16090b57cec5SDimitry Andric   if (auto *T = N.getRawType())
161081ad6265SDimitry Andric     CheckDI(isType(T), "invalid type ref", &N, T);
16110b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
161281ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
16130b57cec5SDimitry Andric }
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
161681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
16170b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_imported_declaration,
16180b57cec5SDimitry Andric           "invalid tag", &N);
16190b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
162081ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
162181ad6265SDimitry Andric   CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
16220b57cec5SDimitry Andric           N.getRawEntity());
16230b57cec5SDimitry Andric }
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
16268bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
16278bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
16288bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
16290b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
163081ad6265SDimitry Andric       Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
163181ad6265SDimitry Andric             GV);
16320b57cec5SDimitry Andric }
16330b57cec5SDimitry Andric 
1634349cc55cSDimitry Andric void Verifier::visitModuleIdents() {
16350b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
16360b57cec5SDimitry Andric   if (!Idents)
16370b57cec5SDimitry Andric     return;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
16400b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
16410b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
164281ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
16430b57cec5SDimitry Andric           "incorrect number of operands in llvm.ident metadata", N);
164481ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
16450b57cec5SDimitry Andric           ("invalid value for llvm.ident metadata entry operand"
16460b57cec5SDimitry Andric            "(the operand should be a string)"),
16470b57cec5SDimitry Andric           N->getOperand(0));
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric }
16500b57cec5SDimitry Andric 
1651349cc55cSDimitry Andric void Verifier::visitModuleCommandLines() {
16520b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
16530b57cec5SDimitry Andric   if (!CommandLines)
16540b57cec5SDimitry Andric     return;
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
16570b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
16580b57cec5SDimitry Andric   // requirement is met.
16590b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
166081ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
16610b57cec5SDimitry Andric           "incorrect number of operands in llvm.commandline metadata", N);
166281ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
16630b57cec5SDimitry Andric           ("invalid value for llvm.commandline metadata entry operand"
16640b57cec5SDimitry Andric            "(the operand should be a string)"),
16650b57cec5SDimitry Andric           N->getOperand(0));
16660b57cec5SDimitry Andric   }
16670b57cec5SDimitry Andric }
16680b57cec5SDimitry Andric 
1669349cc55cSDimitry Andric void Verifier::visitModuleFlags() {
16700b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
16710b57cec5SDimitry Andric   if (!Flags) return;
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
16740b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
16750b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
16760b57cec5SDimitry Andric   for (const MDNode *MDN : Flags->operands())
16770b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
16800b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
16810b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
16820b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
16850b57cec5SDimitry Andric     if (!Op) {
16860b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
16870b57cec5SDimitry Andric                   Flag);
16880b57cec5SDimitry Andric       continue;
16890b57cec5SDimitry Andric     }
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
16920b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
16930b57cec5SDimitry Andric                    "flag does not have the required value"),
16940b57cec5SDimitry Andric                   Flag);
16950b57cec5SDimitry Andric       continue;
16960b57cec5SDimitry Andric     }
16970b57cec5SDimitry Andric   }
16980b57cec5SDimitry Andric }
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric void
17010b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
17020b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
17030b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
17040b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
17050b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
170681ad6265SDimitry Andric   Check(Op->getNumOperands() == 3,
17070b57cec5SDimitry Andric         "incorrect number of operands in module flag", Op);
17080b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
17090b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
171081ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
17110b57cec5SDimitry Andric           "invalid behavior operand in module flag (expected constant integer)",
17120b57cec5SDimitry Andric           Op->getOperand(0));
171381ad6265SDimitry Andric     Check(false,
17140b57cec5SDimitry Andric           "invalid behavior operand in module flag (unexpected constant)",
17150b57cec5SDimitry Andric           Op->getOperand(0));
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
171881ad6265SDimitry Andric   Check(ID, "invalid ID operand in module flag (expected metadata string)",
17190b57cec5SDimitry Andric         Op->getOperand(1));
17200b57cec5SDimitry Andric 
17214824e7fdSDimitry Andric   // Check the values for behaviors with additional requirements.
17220b57cec5SDimitry Andric   switch (MFB) {
17230b57cec5SDimitry Andric   case Module::Error:
17240b57cec5SDimitry Andric   case Module::Warning:
17250b57cec5SDimitry Andric   case Module::Override:
17260b57cec5SDimitry Andric     // These behavior types accept any value.
17270b57cec5SDimitry Andric     break;
17280b57cec5SDimitry Andric 
172981ad6265SDimitry Andric   case Module::Min: {
1730fcaf7f86SDimitry Andric     auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1731fcaf7f86SDimitry Andric     Check(V && V->getValue().isNonNegative(),
1732fcaf7f86SDimitry Andric           "invalid value for 'min' module flag (expected constant non-negative "
1733fcaf7f86SDimitry Andric           "integer)",
173481ad6265SDimitry Andric           Op->getOperand(2));
173581ad6265SDimitry Andric     break;
173681ad6265SDimitry Andric   }
173781ad6265SDimitry Andric 
17380b57cec5SDimitry Andric   case Module::Max: {
173981ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
17400b57cec5SDimitry Andric           "invalid value for 'max' module flag (expected constant integer)",
17410b57cec5SDimitry Andric           Op->getOperand(2));
17420b57cec5SDimitry Andric     break;
17430b57cec5SDimitry Andric   }
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric   case Module::Require: {
17460b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
17470b57cec5SDimitry Andric     // MDString), and a value.
17480b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
174981ad6265SDimitry Andric     Check(Value && Value->getNumOperands() == 2,
17500b57cec5SDimitry Andric           "invalid value for 'require' module flag (expected metadata pair)",
17510b57cec5SDimitry Andric           Op->getOperand(2));
175281ad6265SDimitry Andric     Check(isa<MDString>(Value->getOperand(0)),
17530b57cec5SDimitry Andric           ("invalid value for 'require' module flag "
17540b57cec5SDimitry Andric            "(first value operand should be a string)"),
17550b57cec5SDimitry Andric           Value->getOperand(0));
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
17580b57cec5SDimitry Andric     // scanned.
17590b57cec5SDimitry Andric     Requirements.push_back(Value);
17600b57cec5SDimitry Andric     break;
17610b57cec5SDimitry Andric   }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   case Module::Append:
17640b57cec5SDimitry Andric   case Module::AppendUnique: {
17650b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
176681ad6265SDimitry Andric     Check(isa<MDNode>(Op->getOperand(2)),
17670b57cec5SDimitry Andric           "invalid value for 'append'-type module flag "
17680b57cec5SDimitry Andric           "(expected a metadata node)",
17690b57cec5SDimitry Andric           Op->getOperand(2));
17700b57cec5SDimitry Andric     break;
17710b57cec5SDimitry Andric   }
17720b57cec5SDimitry Andric   }
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
17750b57cec5SDimitry Andric   if (MFB != Module::Require) {
17760b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
177781ad6265SDimitry Andric     Check(Inserted,
17780b57cec5SDimitry Andric           "module flag identifiers must be unique (or of 'require' type)", ID);
17790b57cec5SDimitry Andric   }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
17820b57cec5SDimitry Andric     ConstantInt *Value
17830b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
178481ad6265SDimitry Andric     Check(Value, "wchar_size metadata requires constant integer argument");
17850b57cec5SDimitry Andric   }
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
17880b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
17890b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
17900b57cec5SDimitry Andric     // have been created by a client directly.
179181ad6265SDimitry Andric     Check(M.getNamedMetadata("llvm.linker.options"),
17920b57cec5SDimitry Andric           "'Linker Options' named metadata no longer supported");
17930b57cec5SDimitry Andric   }
17940b57cec5SDimitry Andric 
17955ffd83dbSDimitry Andric   if (ID->getString() == "SemanticInterposition") {
17965ffd83dbSDimitry Andric     ConstantInt *Value =
17975ffd83dbSDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
179881ad6265SDimitry Andric     Check(Value,
17995ffd83dbSDimitry Andric           "SemanticInterposition metadata requires constant integer argument");
18005ffd83dbSDimitry Andric   }
18015ffd83dbSDimitry Andric 
18020b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
18030b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
18040b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
18050b57cec5SDimitry Andric   }
18060b57cec5SDimitry Andric }
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
18090b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
18100b57cec5SDimitry Andric     if (!FuncMDO)
18110b57cec5SDimitry Andric       return;
18120b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
181381ad6265SDimitry Andric     Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
1814e8d8bef9SDimitry Andric           "expected a Function or null", FuncMDO);
18150b57cec5SDimitry Andric   };
18160b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
181781ad6265SDimitry Andric   Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
18180b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
18190b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
18200b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
182181ad6265SDimitry Andric   Check(Count && Count->getType()->isIntegerTy(),
18220b57cec5SDimitry Andric         "expected an integer constant", Node->getOperand(2));
18230b57cec5SDimitry Andric }
18240b57cec5SDimitry Andric 
1825fe6060f1SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
18260b57cec5SDimitry Andric   for (Attribute A : Attrs) {
1827fe6060f1SDimitry Andric 
1828fe6060f1SDimitry Andric     if (A.isStringAttribute()) {
1829fe6060f1SDimitry Andric #define GET_ATTR_NAMES
1830fe6060f1SDimitry Andric #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1831fe6060f1SDimitry Andric #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1832fe6060f1SDimitry Andric   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1833fe6060f1SDimitry Andric     auto V = A.getValueAsString();                                             \
1834fe6060f1SDimitry Andric     if (!(V.empty() || V == "true" || V == "false"))                           \
1835fe6060f1SDimitry Andric       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1836fe6060f1SDimitry Andric                   "");                                                         \
1837fe6060f1SDimitry Andric   }
1838fe6060f1SDimitry Andric 
1839fe6060f1SDimitry Andric #include "llvm/IR/Attributes.inc"
18400b57cec5SDimitry Andric       continue;
1841fe6060f1SDimitry Andric     }
18420b57cec5SDimitry Andric 
1843fe6060f1SDimitry Andric     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
18445ffd83dbSDimitry Andric       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
18455ffd83dbSDimitry Andric                   V);
18465ffd83dbSDimitry Andric       return;
18475ffd83dbSDimitry Andric     }
18480b57cec5SDimitry Andric   }
18490b57cec5SDimitry Andric }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
18520b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
18530b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
18540b57cec5SDimitry Andric                                     const Value *V) {
18550b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
18560b57cec5SDimitry Andric     return;
18570b57cec5SDimitry Andric 
1858fe6060f1SDimitry Andric   verifyAttributeTypes(Attrs, V);
1859fe6060f1SDimitry Andric 
1860fe6060f1SDimitry Andric   for (Attribute Attr : Attrs)
186181ad6265SDimitry Andric     Check(Attr.isStringAttribute() ||
1862fe6060f1SDimitry Andric               Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
186381ad6265SDimitry Andric           "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
1864fe6060f1SDimitry Andric           V);
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
186781ad6265SDimitry Andric     Check(Attrs.getNumAttributes() == 1,
18680b57cec5SDimitry Andric           "Attribute 'immarg' is incompatible with other attributes", V);
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
18720b57cec5SDimitry Andric   // sret.
18730b57cec5SDimitry Andric   unsigned AttrCount = 0;
18740b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
18750b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
18765ffd83dbSDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
18770b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
18780b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
18790b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1880e8d8bef9SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
188181ad6265SDimitry Andric   Check(AttrCount <= 1,
18825ffd83dbSDimitry Andric         "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1883e8d8bef9SDimitry Andric         "'byref', and 'sret' are incompatible!",
18840b57cec5SDimitry Andric         V);
18850b57cec5SDimitry Andric 
188681ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
18870b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
18880b57cec5SDimitry Andric         "Attributes "
18890b57cec5SDimitry Andric         "'inalloca and readonly' are incompatible!",
18900b57cec5SDimitry Andric         V);
18910b57cec5SDimitry Andric 
189281ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
18930b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::Returned)),
18940b57cec5SDimitry Andric         "Attributes "
18950b57cec5SDimitry Andric         "'sret and returned' are incompatible!",
18960b57cec5SDimitry Andric         V);
18970b57cec5SDimitry Andric 
189881ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
18990b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::SExt)),
19000b57cec5SDimitry Andric         "Attributes "
19010b57cec5SDimitry Andric         "'zeroext and signext' are incompatible!",
19020b57cec5SDimitry Andric         V);
19030b57cec5SDimitry Andric 
190481ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
19050b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
19060b57cec5SDimitry Andric         "Attributes "
19070b57cec5SDimitry Andric         "'readnone and readonly' are incompatible!",
19080b57cec5SDimitry Andric         V);
19090b57cec5SDimitry Andric 
191081ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
19110b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
19120b57cec5SDimitry Andric         "Attributes "
19130b57cec5SDimitry Andric         "'readnone and writeonly' are incompatible!",
19140b57cec5SDimitry Andric         V);
19150b57cec5SDimitry Andric 
191681ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
19170b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
19180b57cec5SDimitry Andric         "Attributes "
19190b57cec5SDimitry Andric         "'readonly and writeonly' are incompatible!",
19200b57cec5SDimitry Andric         V);
19210b57cec5SDimitry Andric 
192281ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
19230b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::AlwaysInline)),
19240b57cec5SDimitry Andric         "Attributes "
19250b57cec5SDimitry Andric         "'noinline and alwaysinline' are incompatible!",
19260b57cec5SDimitry Andric         V);
19270b57cec5SDimitry Andric 
19285f757f3fSDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::Writable) &&
19295f757f3fSDimitry Andric           Attrs.hasAttribute(Attribute::ReadNone)),
19305f757f3fSDimitry Andric         "Attributes writable and readnone are incompatible!", V);
19315f757f3fSDimitry Andric 
19325f757f3fSDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::Writable) &&
19335f757f3fSDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
19345f757f3fSDimitry Andric         "Attributes writable and readonly are incompatible!", V);
19355f757f3fSDimitry Andric 
193604eeddc0SDimitry Andric   AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1937fe6060f1SDimitry Andric   for (Attribute Attr : Attrs) {
1938fe6060f1SDimitry Andric     if (!Attr.isStringAttribute() &&
1939fe6060f1SDimitry Andric         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1940fe6060f1SDimitry Andric       CheckFailed("Attribute '" + Attr.getAsString() +
1941fe6060f1SDimitry Andric                   "' applied to incompatible type!", V);
1942fe6060f1SDimitry Andric       return;
1943fe6060f1SDimitry Andric     }
1944fe6060f1SDimitry Andric   }
19450b57cec5SDimitry Andric 
194606c3fb27SDimitry Andric   if (isa<PointerType>(Ty)) {
1947fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByVal)) {
194881ad6265SDimitry Andric       if (Attrs.hasAttribute(Attribute::Alignment)) {
194981ad6265SDimitry Andric         Align AttrAlign = Attrs.getAlignment().valueOrOne();
195081ad6265SDimitry Andric         Align MaxAlign(ParamMaxAlignment);
195181ad6265SDimitry Andric         Check(AttrAlign <= MaxAlign,
195281ad6265SDimitry Andric               "Attribute 'align' exceed the max size 2^14", V);
195381ad6265SDimitry Andric       }
19540b57cec5SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
195581ad6265SDimitry Andric       Check(Attrs.getByValType()->isSized(&Visited),
1956fe6060f1SDimitry Andric             "Attribute 'byval' does not support unsized types!", V);
19570b57cec5SDimitry Andric     }
1958fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByRef)) {
1959fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
196081ad6265SDimitry Andric       Check(Attrs.getByRefType()->isSized(&Visited),
1961fe6060f1SDimitry Andric             "Attribute 'byref' does not support unsized types!", V);
1962fe6060f1SDimitry Andric     }
1963fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::InAlloca)) {
1964fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
196581ad6265SDimitry Andric       Check(Attrs.getInAllocaType()->isSized(&Visited),
1966fe6060f1SDimitry Andric             "Attribute 'inalloca' does not support unsized types!", V);
1967fe6060f1SDimitry Andric     }
1968fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::Preallocated)) {
1969fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
197081ad6265SDimitry Andric       Check(Attrs.getPreallocatedType()->isSized(&Visited),
1971fe6060f1SDimitry Andric             "Attribute 'preallocated' does not support unsized types!", V);
1972fe6060f1SDimitry Andric     }
197306c3fb27SDimitry Andric   }
197406c3fb27SDimitry Andric 
197506c3fb27SDimitry Andric   if (Attrs.hasAttribute(Attribute::NoFPClass)) {
197606c3fb27SDimitry Andric     uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
197706c3fb27SDimitry Andric     Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
19780b57cec5SDimitry Andric           V);
197906c3fb27SDimitry Andric     Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
198006c3fb27SDimitry Andric           "Invalid value for 'nofpclass' test mask", V);
1981fe6060f1SDimitry Andric   }
1982fe6060f1SDimitry Andric }
1983fe6060f1SDimitry Andric 
1984fe6060f1SDimitry Andric void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1985fe6060f1SDimitry Andric                                             const Value *V) {
1986349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attr)) {
1987349cc55cSDimitry Andric     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1988fe6060f1SDimitry Andric     unsigned N;
1989fe6060f1SDimitry Andric     if (S.getAsInteger(10, N))
1990fe6060f1SDimitry Andric       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
19910b57cec5SDimitry Andric   }
19920b57cec5SDimitry Andric }
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric // Check parameter attributes against a function type.
19950b57cec5SDimitry Andric // The value V is printed in error messages.
19960b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
199704eeddc0SDimitry Andric                                    const Value *V, bool IsIntrinsic,
199804eeddc0SDimitry Andric                                    bool IsInlineAsm) {
19990b57cec5SDimitry Andric   if (Attrs.isEmpty())
20000b57cec5SDimitry Andric     return;
20010b57cec5SDimitry Andric 
2002fe6060f1SDimitry Andric   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
200381ad6265SDimitry Andric     Check(Attrs.hasParentContext(Context),
2004fe6060f1SDimitry Andric           "Attribute list does not match Module context!", &Attrs, V);
2005fe6060f1SDimitry Andric     for (const auto &AttrSet : Attrs) {
200681ad6265SDimitry Andric       Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2007fe6060f1SDimitry Andric             "Attribute set does not match Module context!", &AttrSet, V);
2008fe6060f1SDimitry Andric       for (const auto &A : AttrSet) {
200981ad6265SDimitry Andric         Check(A.hasParentContext(Context),
2010fe6060f1SDimitry Andric               "Attribute does not match Module context!", &A, V);
2011fe6060f1SDimitry Andric       }
2012fe6060f1SDimitry Andric     }
2013fe6060f1SDimitry Andric   }
2014fe6060f1SDimitry Andric 
20150b57cec5SDimitry Andric   bool SawNest = false;
20160b57cec5SDimitry Andric   bool SawReturned = false;
20170b57cec5SDimitry Andric   bool SawSRet = false;
20180b57cec5SDimitry Andric   bool SawSwiftSelf = false;
2019fe6060f1SDimitry Andric   bool SawSwiftAsync = false;
20200b57cec5SDimitry Andric   bool SawSwiftError = false;
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric   // Verify return value attributes.
2023349cc55cSDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttrs();
2024fe6060f1SDimitry Andric   for (Attribute RetAttr : RetAttrs)
202581ad6265SDimitry Andric     Check(RetAttr.isStringAttribute() ||
2026fe6060f1SDimitry Andric               Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2027fe6060f1SDimitry Andric           "Attribute '" + RetAttr.getAsString() +
2028fe6060f1SDimitry Andric               "' does not apply to function return values",
20290b57cec5SDimitry Andric           V);
2030fe6060f1SDimitry Andric 
20315f757f3fSDimitry Andric   unsigned MaxParameterWidth = 0;
20325f757f3fSDimitry Andric   auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
20335f757f3fSDimitry Andric     if (Ty->isVectorTy()) {
20345f757f3fSDimitry Andric       if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
20355f757f3fSDimitry Andric         unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
20365f757f3fSDimitry Andric         if (Size > MaxParameterWidth)
20375f757f3fSDimitry Andric           MaxParameterWidth = Size;
20385f757f3fSDimitry Andric       }
20395f757f3fSDimitry Andric     }
20405f757f3fSDimitry Andric   };
20415f757f3fSDimitry Andric   GetMaxParameterWidth(FT->getReturnType());
20420b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   // Verify parameter attributes.
20450b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
20460b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
2047349cc55cSDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
20480b57cec5SDimitry Andric 
20490b57cec5SDimitry Andric     if (!IsIntrinsic) {
205081ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
20510b57cec5SDimitry Andric             "immarg attribute only applies to intrinsics", V);
205204eeddc0SDimitry Andric       if (!IsInlineAsm)
205381ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
205404eeddc0SDimitry Andric               "Attribute 'elementtype' can only be applied to intrinsics"
205581ad6265SDimitry Andric               " and inline asm.",
205681ad6265SDimitry Andric               V);
20570b57cec5SDimitry Andric     }
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
20605f757f3fSDimitry Andric     GetMaxParameterWidth(Ty);
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
206381ad6265SDimitry Andric       Check(!SawNest, "More than one parameter has attribute nest!", V);
20640b57cec5SDimitry Andric       SawNest = true;
20650b57cec5SDimitry Andric     }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
206881ad6265SDimitry Andric       Check(!SawReturned, "More than one parameter has attribute returned!", V);
206981ad6265SDimitry Andric       Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
20700b57cec5SDimitry Andric             "Incompatible argument and return types for 'returned' attribute",
20710b57cec5SDimitry Andric             V);
20720b57cec5SDimitry Andric       SawReturned = true;
20730b57cec5SDimitry Andric     }
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
207681ad6265SDimitry Andric       Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
207781ad6265SDimitry Andric       Check(i == 0 || i == 1,
20780b57cec5SDimitry Andric             "Attribute 'sret' is not on first or second parameter!", V);
20790b57cec5SDimitry Andric       SawSRet = true;
20800b57cec5SDimitry Andric     }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
208381ad6265SDimitry Andric       Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
20840b57cec5SDimitry Andric       SawSwiftSelf = true;
20850b57cec5SDimitry Andric     }
20860b57cec5SDimitry Andric 
2087fe6060f1SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
208881ad6265SDimitry Andric       Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2089fe6060f1SDimitry Andric       SawSwiftAsync = true;
2090fe6060f1SDimitry Andric     }
2091fe6060f1SDimitry Andric 
20920b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
209381ad6265SDimitry Andric       Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
20940b57cec5SDimitry Andric       SawSwiftError = true;
20950b57cec5SDimitry Andric     }
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
209881ad6265SDimitry Andric       Check(i == FT->getNumParams() - 1,
20990b57cec5SDimitry Andric             "inalloca isn't on the last parameter!", V);
21000b57cec5SDimitry Andric     }
21010b57cec5SDimitry Andric   }
21020b57cec5SDimitry Andric 
2103349cc55cSDimitry Andric   if (!Attrs.hasFnAttrs())
21040b57cec5SDimitry Andric     return;
21050b57cec5SDimitry Andric 
2106349cc55cSDimitry Andric   verifyAttributeTypes(Attrs.getFnAttrs(), V);
2107349cc55cSDimitry Andric   for (Attribute FnAttr : Attrs.getFnAttrs())
210881ad6265SDimitry Andric     Check(FnAttr.isStringAttribute() ||
2109fe6060f1SDimitry Andric               Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2110fe6060f1SDimitry Andric           "Attribute '" + FnAttr.getAsString() +
2111fe6060f1SDimitry Andric               "' does not apply to functions!",
2112fe6060f1SDimitry Andric           V);
21130b57cec5SDimitry Andric 
211481ad6265SDimitry Andric   Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2115349cc55cSDimitry Andric           Attrs.hasFnAttr(Attribute::AlwaysInline)),
21160b57cec5SDimitry Andric         "Attributes 'noinline and alwaysinline' are incompatible!", V);
21170b57cec5SDimitry Andric 
2118349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
211981ad6265SDimitry Andric     Check(Attrs.hasFnAttr(Attribute::NoInline),
21200b57cec5SDimitry Andric           "Attribute 'optnone' requires 'noinline'!", V);
21210b57cec5SDimitry Andric 
212281ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
21230b57cec5SDimitry Andric           "Attributes 'optsize and optnone' are incompatible!", V);
21240b57cec5SDimitry Andric 
212581ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
21260b57cec5SDimitry Andric           "Attributes 'minsize and optnone' are incompatible!", V);
21275f757f3fSDimitry Andric 
21285f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
21295f757f3fSDimitry Andric           "Attributes 'optdebug and optnone' are incompatible!", V);
21300b57cec5SDimitry Andric   }
21310b57cec5SDimitry Andric 
21325f757f3fSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
21335f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
21345f757f3fSDimitry Andric           "Attributes 'optsize and optdebug' are incompatible!", V);
21355f757f3fSDimitry Andric 
21365f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
21375f757f3fSDimitry Andric           "Attributes 'minsize and optdebug' are incompatible!", V);
21385f757f3fSDimitry Andric   }
21395f757f3fSDimitry Andric 
21405f757f3fSDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
21415f757f3fSDimitry Andric         isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
21425f757f3fSDimitry Andric         "Attribute writable and memory without argmem: write are incompatible!",
21435f757f3fSDimitry Andric         V);
21445f757f3fSDimitry Andric 
2145bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2146bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2147bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_sm_enabled and "
2148bdd1243dSDimitry Andric            "aarch64_pstate_sm_compatible' are incompatible!",
2149bdd1243dSDimitry Andric            V);
2150bdd1243dSDimitry Andric   }
2151bdd1243dSDimitry Andric 
2152bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_za_new")) {
2153bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_za_preserved"),
2154bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2155bdd1243dSDimitry Andric            "are incompatible!",
2156bdd1243dSDimitry Andric            V);
2157bdd1243dSDimitry Andric 
2158bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_za_shared"),
2159bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2160bdd1243dSDimitry Andric            "are incompatible!",
2161bdd1243dSDimitry Andric            V);
2162bdd1243dSDimitry Andric   }
2163bdd1243dSDimitry Andric 
2164349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
21650b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
216681ad6265SDimitry Andric     Check(GV->hasGlobalUnnamedAddr(),
21670b57cec5SDimitry Andric           "Attribute 'jumptable' requires 'unnamed_addr'", V);
21680b57cec5SDimitry Andric   }
21690b57cec5SDimitry Andric 
2170bdd1243dSDimitry Andric   if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
21710b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
21720b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
21730b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
21740b57cec5SDimitry Andric         return false;
21750b57cec5SDimitry Andric       }
21760b57cec5SDimitry Andric 
21770b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
21780b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
21790b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
21800b57cec5SDimitry Andric                     V);
21810b57cec5SDimitry Andric         return false;
21820b57cec5SDimitry Andric       }
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric       return true;
21850b57cec5SDimitry Andric     };
21860b57cec5SDimitry Andric 
2187bdd1243dSDimitry Andric     if (!CheckParam("element size", Args->first))
21880b57cec5SDimitry Andric       return;
21890b57cec5SDimitry Andric 
2190bdd1243dSDimitry Andric     if (Args->second && !CheckParam("number of elements", *Args->second))
21910b57cec5SDimitry Andric       return;
21920b57cec5SDimitry Andric   }
2193480093f4SDimitry Andric 
219481ad6265SDimitry Andric   if (Attrs.hasFnAttr(Attribute::AllocKind)) {
219581ad6265SDimitry Andric     AllocFnKind K = Attrs.getAllocKind();
219681ad6265SDimitry Andric     AllocFnKind Type =
219781ad6265SDimitry Andric         K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
219881ad6265SDimitry Andric     if (!is_contained(
219981ad6265SDimitry Andric             {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
220081ad6265SDimitry Andric             Type))
220181ad6265SDimitry Andric       CheckFailed(
220281ad6265SDimitry Andric           "'allockind()' requires exactly one of alloc, realloc, and free");
220381ad6265SDimitry Andric     if ((Type == AllocFnKind::Free) &&
220481ad6265SDimitry Andric         ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
220581ad6265SDimitry Andric                AllocFnKind::Aligned)) != AllocFnKind::Unknown))
220681ad6265SDimitry Andric       CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
220781ad6265SDimitry Andric                   "or aligned modifiers.");
220881ad6265SDimitry Andric     AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
220981ad6265SDimitry Andric     if ((K & ZeroedUninit) == ZeroedUninit)
221081ad6265SDimitry Andric       CheckFailed("'allockind()' can't be both zeroed and uninitialized");
221181ad6265SDimitry Andric   }
221281ad6265SDimitry Andric 
2213349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
22140eae32dcSDimitry Andric     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
22150eae32dcSDimitry Andric     if (VScaleMin == 0)
22160eae32dcSDimitry Andric       CheckFailed("'vscale_range' minimum must be greater than 0", V);
221706c3fb27SDimitry Andric     else if (!isPowerOf2_32(VScaleMin))
221806c3fb27SDimitry Andric       CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2219bdd1243dSDimitry Andric     std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
22200eae32dcSDimitry Andric     if (VScaleMax && VScaleMin > VScaleMax)
2221fe6060f1SDimitry Andric       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
222206c3fb27SDimitry Andric     else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
222306c3fb27SDimitry Andric       CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2224fe6060f1SDimitry Andric   }
2225fe6060f1SDimitry Andric 
2226349cc55cSDimitry Andric   if (Attrs.hasFnAttr("frame-pointer")) {
2227349cc55cSDimitry Andric     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2228480093f4SDimitry Andric     if (FP != "all" && FP != "non-leaf" && FP != "none")
2229480093f4SDimitry Andric       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2230480093f4SDimitry Andric   }
2231480093f4SDimitry Andric 
22325f757f3fSDimitry Andric   // Check EVEX512 feature.
22335f757f3fSDimitry Andric   if (MaxParameterWidth >= 512 && Attrs.hasFnAttr("target-features") &&
22345f757f3fSDimitry Andric       TT.isX86()) {
22355f757f3fSDimitry Andric     StringRef TF = Attrs.getFnAttr("target-features").getValueAsString();
22365f757f3fSDimitry Andric     Check(!TF.contains("+avx512f") || !TF.contains("-evex512"),
22375f757f3fSDimitry Andric           "512-bit vector arguments require 'evex512' for AVX512", V);
22385f757f3fSDimitry Andric   }
22395f757f3fSDimitry Andric 
2240fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2241fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2242fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
22435f757f3fSDimitry Andric 
22445f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
22455f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
22465f757f3fSDimitry Andric     if (S != "none" && S != "all" && S != "non-leaf")
22475f757f3fSDimitry Andric       CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
22485f757f3fSDimitry Andric   }
22495f757f3fSDimitry Andric 
22505f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
22515f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
22525f757f3fSDimitry Andric     if (S != "a_key" && S != "b_key")
22535f757f3fSDimitry Andric       CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
22545f757f3fSDimitry Andric                   V);
22555f757f3fSDimitry Andric   }
22565f757f3fSDimitry Andric 
22575f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
22585f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
22595f757f3fSDimitry Andric     if (S != "true" && S != "false")
22605f757f3fSDimitry Andric       CheckFailed(
22615f757f3fSDimitry Andric           "invalid value for 'branch-target-enforcement' attribute: " + S, V);
22625f757f3fSDimitry Andric   }
22630b57cec5SDimitry Andric }
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
22660b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
22670b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
22680b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
22690b57cec5SDimitry Andric       MDNode *MD = Pair.second;
227081ad6265SDimitry Andric       Check(MD->getNumOperands() >= 2,
22710b57cec5SDimitry Andric             "!prof annotations should have no less than 2 operands", MD);
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric       // Check first operand.
227481ad6265SDimitry Andric       Check(MD->getOperand(0) != nullptr, "first operand should not be null",
22750b57cec5SDimitry Andric             MD);
227681ad6265SDimitry Andric       Check(isa<MDString>(MD->getOperand(0)),
22770b57cec5SDimitry Andric             "expected string with name of the !prof annotation", MD);
22780b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
22790b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
228081ad6265SDimitry Andric       Check(ProfName.equals("function_entry_count") ||
22810b57cec5SDimitry Andric                 ProfName.equals("synthetic_function_entry_count"),
22820b57cec5SDimitry Andric             "first operand should be 'function_entry_count'"
22830b57cec5SDimitry Andric             " or 'synthetic_function_entry_count'",
22840b57cec5SDimitry Andric             MD);
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric       // Check second operand.
228781ad6265SDimitry Andric       Check(MD->getOperand(1) != nullptr, "second operand should not be null",
22880b57cec5SDimitry Andric             MD);
228981ad6265SDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
22900b57cec5SDimitry Andric             "expected integer argument to function_entry_count", MD);
2291bdd1243dSDimitry Andric     } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2292bdd1243dSDimitry Andric       MDNode *MD = Pair.second;
2293bdd1243dSDimitry Andric       Check(MD->getNumOperands() == 1,
2294bdd1243dSDimitry Andric             "!kcfi_type must have exactly one operand", MD);
2295bdd1243dSDimitry Andric       Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2296bdd1243dSDimitry Andric             MD);
2297bdd1243dSDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
2298bdd1243dSDimitry Andric             "expected a constant operand for !kcfi_type", MD);
2299bdd1243dSDimitry Andric       Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2300cb14a3feSDimitry Andric       Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2301bdd1243dSDimitry Andric             "expected a constant integer operand for !kcfi_type", MD);
2302cb14a3feSDimitry Andric       Check(cast<ConstantInt>(C)->getBitWidth() == 32,
2303bdd1243dSDimitry Andric             "expected a 32-bit integer constant operand for !kcfi_type", MD);
23040b57cec5SDimitry Andric     }
23050b57cec5SDimitry Andric   }
23060b57cec5SDimitry Andric }
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
23090b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
23100b57cec5SDimitry Andric     return;
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
23130b57cec5SDimitry Andric   Stack.push_back(EntryC);
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   while (!Stack.empty()) {
23160b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
23170b57cec5SDimitry Andric 
23180b57cec5SDimitry Andric     // Check this constant expression.
23190b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
23200b57cec5SDimitry Andric       visitConstantExpr(CE);
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
23230b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
23240b57cec5SDimitry Andric       // that the global value is in the correct module
232581ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!",
23260b57cec5SDimitry Andric             EntryC, &M, GV, GV->getParent());
23270b57cec5SDimitry Andric       continue;
23280b57cec5SDimitry Andric     }
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric     // Visit all sub-expressions.
23310b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
23320b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
23330b57cec5SDimitry Andric       if (!OpC)
23340b57cec5SDimitry Andric         continue;
23350b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
23360b57cec5SDimitry Andric         continue;
23370b57cec5SDimitry Andric       Stack.push_back(OpC);
23380b57cec5SDimitry Andric     }
23390b57cec5SDimitry Andric   }
23400b57cec5SDimitry Andric }
23410b57cec5SDimitry Andric 
23420b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
23430b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
234481ad6265SDimitry Andric     Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
23450b57cec5SDimitry Andric                                 CE->getType()),
23460b57cec5SDimitry Andric           "Invalid bitcast", CE);
23470b57cec5SDimitry Andric }
23480b57cec5SDimitry Andric 
23490b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
23500b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
23510b57cec5SDimitry Andric   // function and return value.
23520b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
23530b57cec5SDimitry Andric }
23540b57cec5SDimitry Andric 
235504eeddc0SDimitry Andric void Verifier::verifyInlineAsmCall(const CallBase &Call) {
235604eeddc0SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
235704eeddc0SDimitry Andric   unsigned ArgNo = 0;
2358fcaf7f86SDimitry Andric   unsigned LabelNo = 0;
235904eeddc0SDimitry Andric   for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2360fcaf7f86SDimitry Andric     if (CI.Type == InlineAsm::isLabel) {
2361fcaf7f86SDimitry Andric       ++LabelNo;
2362fcaf7f86SDimitry Andric       continue;
2363fcaf7f86SDimitry Andric     }
2364fcaf7f86SDimitry Andric 
236504eeddc0SDimitry Andric     // Only deal with constraints that correspond to call arguments.
236604eeddc0SDimitry Andric     if (!CI.hasArg())
236704eeddc0SDimitry Andric       continue;
236804eeddc0SDimitry Andric 
236904eeddc0SDimitry Andric     if (CI.isIndirect) {
237004eeddc0SDimitry Andric       const Value *Arg = Call.getArgOperand(ArgNo);
237181ad6265SDimitry Andric       Check(Arg->getType()->isPointerTy(),
237281ad6265SDimitry Andric             "Operand for indirect constraint must have pointer type", &Call);
237304eeddc0SDimitry Andric 
237481ad6265SDimitry Andric       Check(Call.getParamElementType(ArgNo),
237504eeddc0SDimitry Andric             "Operand for indirect constraint must have elementtype attribute",
237604eeddc0SDimitry Andric             &Call);
237704eeddc0SDimitry Andric     } else {
237881ad6265SDimitry Andric       Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
237904eeddc0SDimitry Andric             "Elementtype attribute can only be applied for indirect "
238081ad6265SDimitry Andric             "constraints",
238181ad6265SDimitry Andric             &Call);
238204eeddc0SDimitry Andric     }
238304eeddc0SDimitry Andric 
238404eeddc0SDimitry Andric     ArgNo++;
238504eeddc0SDimitry Andric   }
2386fcaf7f86SDimitry Andric 
2387fcaf7f86SDimitry Andric   if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2388fcaf7f86SDimitry Andric     Check(LabelNo == CallBr->getNumIndirectDests(),
2389fcaf7f86SDimitry Andric           "Number of label constraints does not match number of callbr dests",
2390fcaf7f86SDimitry Andric           &Call);
2391fcaf7f86SDimitry Andric   } else {
2392fcaf7f86SDimitry Andric     Check(LabelNo == 0, "Label constraints can only be used with callbr",
2393fcaf7f86SDimitry Andric           &Call);
2394fcaf7f86SDimitry Andric   }
239504eeddc0SDimitry Andric }
239604eeddc0SDimitry Andric 
23970b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
23980b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
23990b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
24000b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
24010b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
24020b57cec5SDimitry Andric 
240381ad6265SDimitry Andric   Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
24040b57cec5SDimitry Andric             !Call.onlyAccessesArgMemory(),
24050b57cec5SDimitry Andric         "gc.statepoint must read and write all memory to preserve "
24060b57cec5SDimitry Andric         "reordering restrictions required by safepoint semantics",
24070b57cec5SDimitry Andric         Call);
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric   const int64_t NumPatchBytes =
24100b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
24110b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
241281ad6265SDimitry Andric   Check(NumPatchBytes >= 0,
24130b57cec5SDimitry Andric         "gc.statepoint number of patchable bytes must be "
24140b57cec5SDimitry Andric         "positive",
24150b57cec5SDimitry Andric         Call);
24160b57cec5SDimitry Andric 
241781ad6265SDimitry Andric   Type *TargetElemType = Call.getParamElementType(2);
241881ad6265SDimitry Andric   Check(TargetElemType,
241981ad6265SDimitry Andric         "gc.statepoint callee argument must have elementtype attribute", Call);
242081ad6265SDimitry Andric   FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
242181ad6265SDimitry Andric   Check(TargetFuncType,
242281ad6265SDimitry Andric         "gc.statepoint callee elementtype must be function type", Call);
24230b57cec5SDimitry Andric 
24240b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
242581ad6265SDimitry Andric   Check(NumCallArgs >= 0,
24260b57cec5SDimitry Andric         "gc.statepoint number of arguments to underlying call "
24270b57cec5SDimitry Andric         "must be positive",
24280b57cec5SDimitry Andric         Call);
24290b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
24300b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
243181ad6265SDimitry Andric     Check(NumCallArgs >= NumParams,
24320b57cec5SDimitry Andric           "gc.statepoint mismatch in number of vararg call args", Call);
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric     // TODO: Remove this limitation
243581ad6265SDimitry Andric     Check(TargetFuncType->getReturnType()->isVoidTy(),
24360b57cec5SDimitry Andric           "gc.statepoint doesn't support wrapping non-void "
24370b57cec5SDimitry Andric           "vararg functions yet",
24380b57cec5SDimitry Andric           Call);
24390b57cec5SDimitry Andric   } else
244081ad6265SDimitry Andric     Check(NumCallArgs == NumParams,
24410b57cec5SDimitry Andric           "gc.statepoint mismatch in number of call args", Call);
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric   const uint64_t Flags
24440b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
244581ad6265SDimitry Andric   Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
24460b57cec5SDimitry Andric         "unknown flag used in gc.statepoint flags argument", Call);
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
24490b57cec5SDimitry Andric   // the type of the wrapped callee.
24500b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
24510b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
24520b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
24530b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
245481ad6265SDimitry Andric     Check(ArgType == ParamType,
24550b57cec5SDimitry Andric           "gc.statepoint call argument does not match wrapped "
24560b57cec5SDimitry Andric           "function type",
24570b57cec5SDimitry Andric           Call);
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
2460349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
246181ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
246281ad6265SDimitry Andric             "Attribute 'sret' cannot be used for vararg call arguments!", Call);
24630b57cec5SDimitry Andric     }
24640b57cec5SDimitry Andric   }
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
246981ad6265SDimitry Andric   Check(isa<ConstantInt>(NumTransitionArgsV),
24700b57cec5SDimitry Andric         "gc.statepoint number of transition arguments "
24710b57cec5SDimitry Andric         "must be constant integer",
24720b57cec5SDimitry Andric         Call);
24730b57cec5SDimitry Andric   const int NumTransitionArgs =
24740b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
247581ad6265SDimitry Andric   Check(NumTransitionArgs == 0,
2476e8d8bef9SDimitry Andric         "gc.statepoint w/inline transition bundle is deprecated", Call);
2477e8d8bef9SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
24785ffd83dbSDimitry Andric 
24790b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
248081ad6265SDimitry Andric   Check(isa<ConstantInt>(NumDeoptArgsV),
24810b57cec5SDimitry Andric         "gc.statepoint number of deoptimization arguments "
24820b57cec5SDimitry Andric         "must be constant integer",
24830b57cec5SDimitry Andric         Call);
24840b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
248581ad6265SDimitry Andric   Check(NumDeoptArgs == 0,
2486e8d8bef9SDimitry Andric         "gc.statepoint w/inline deopt operands is deprecated", Call);
24875ffd83dbSDimitry Andric 
2488e8d8bef9SDimitry Andric   const int ExpectedNumArgs = 7 + NumCallArgs;
248981ad6265SDimitry Andric   Check(ExpectedNumArgs == (int)Call.arg_size(),
2490e8d8bef9SDimitry Andric         "gc.statepoint too many arguments", Call);
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
24930b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
24940b57cec5SDimitry Andric   // of the same statepoint sequence
24950b57cec5SDimitry Andric   for (const User *U : Call.users()) {
24960b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
249781ad6265SDimitry Andric     Check(UserCall, "illegal use of statepoint token", Call, U);
24980b57cec5SDimitry Andric     if (!UserCall)
24990b57cec5SDimitry Andric       continue;
250081ad6265SDimitry Andric     Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
25010b57cec5SDimitry Andric           "gc.result or gc.relocate are the only value uses "
25020b57cec5SDimitry Andric           "of a gc.statepoint",
25030b57cec5SDimitry Andric           Call, U);
25040b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
250581ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
25060b57cec5SDimitry Andric             "gc.result connected to wrong gc.statepoint", Call, UserCall);
25070b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
250881ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
25090b57cec5SDimitry Andric             "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
25100b57cec5SDimitry Andric     }
25110b57cec5SDimitry Andric   }
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
25140b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
25150b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
25160b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
25170b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
25180b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
25190b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
25200b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
25210b57cec5SDimitry Andric }
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
25240b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
25250b57cec5SDimitry Andric     Function *F = Counts.first;
25260b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
25270b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
252881ad6265SDimitry Andric     Check(MaxRecoveredIndex <= EscapedObjectCount,
25290b57cec5SDimitry Andric           "all indices passed to llvm.localrecover must be less than the "
25300b57cec5SDimitry Andric           "number of arguments passed to llvm.localescape in the parent "
25310b57cec5SDimitry Andric           "function",
25320b57cec5SDimitry Andric           F);
25330b57cec5SDimitry Andric   }
25340b57cec5SDimitry Andric }
25350b57cec5SDimitry Andric 
25360b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
25370b57cec5SDimitry Andric   BasicBlock *UnwindDest;
25380b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
25390b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
25400b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
25410b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
25420b57cec5SDimitry Andric   else
25430b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
25440b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
25450b57cec5SDimitry Andric }
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
25480b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
25490b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
25500b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
25510b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
25520b57cec5SDimitry Andric     if (Visited.count(PredPad))
25530b57cec5SDimitry Andric       continue;
25540b57cec5SDimitry Andric     Active.insert(PredPad);
25550b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
25560b57cec5SDimitry Andric     do {
25570b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
25580b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
25590b57cec5SDimitry Andric         // Found a cycle; report error
25600b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
25610b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
25620b57cec5SDimitry Andric         do {
25630b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
25640b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
25650b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
25660b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
25670b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
25680b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
256981ad6265SDimitry Andric         Check(false, "EH pads can't handle each other's exceptions",
25700b57cec5SDimitry Andric               ArrayRef<Instruction *>(CycleNodes));
25710b57cec5SDimitry Andric       }
25720b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
25730b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
25740b57cec5SDimitry Andric         break;
25750b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
25760b57cec5SDimitry Andric       PredPad = SuccPad;
25770b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
25780b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
25790b57cec5SDimitry Andric         break;
25800b57cec5SDimitry Andric       Terminator = TermI->second;
25810b57cec5SDimitry Andric       Active.insert(PredPad);
25820b57cec5SDimitry Andric     } while (true);
25830b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
25840b57cec5SDimitry Andric     // nodes' successors.
25850b57cec5SDimitry Andric     Active.clear();
25860b57cec5SDimitry Andric   }
25870b57cec5SDimitry Andric }
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
25900b57cec5SDimitry Andric //
25910b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
25920b57cec5SDimitry Andric   visitGlobalValue(F);
25930b57cec5SDimitry Andric 
25940b57cec5SDimitry Andric   // Check function arguments.
25950b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
25960b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
25970b57cec5SDimitry Andric 
259881ad6265SDimitry Andric   Check(&Context == &F.getContext(),
25990b57cec5SDimitry Andric         "Function context does not match Module context!", &F);
26000b57cec5SDimitry Andric 
260181ad6265SDimitry Andric   Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
260281ad6265SDimitry Andric   Check(FT->getNumParams() == NumArgs,
26030b57cec5SDimitry Andric         "# formal arguments must match # of arguments for function type!", &F,
26040b57cec5SDimitry Andric         FT);
260581ad6265SDimitry Andric   Check(F.getReturnType()->isFirstClassType() ||
26060b57cec5SDimitry Andric             F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
26070b57cec5SDimitry Andric         "Functions cannot return aggregate values!", &F);
26080b57cec5SDimitry Andric 
260981ad6265SDimitry Andric   Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
26100b57cec5SDimitry Andric         "Invalid struct return type!", &F);
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
26130b57cec5SDimitry Andric 
261481ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, FT->getNumParams()),
26150b57cec5SDimitry Andric         "Attribute after last parameter!", &F);
26160b57cec5SDimitry Andric 
2617fe6060f1SDimitry Andric   bool IsIntrinsic = F.isIntrinsic();
26180b57cec5SDimitry Andric 
26190b57cec5SDimitry Andric   // Check function attributes.
262004eeddc0SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
26210b57cec5SDimitry Andric 
26220b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
26230b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
26240b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
262581ad6265SDimitry Andric   Check(!Attrs.hasFnAttr(Attribute::Builtin),
26260b57cec5SDimitry Andric         "Attribute 'builtin' can only be applied to a callsite.", &F);
26270b57cec5SDimitry Andric 
262881ad6265SDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2629fe6060f1SDimitry Andric         "Attribute 'elementtype' can only be applied to a callsite.", &F);
2630fe6060f1SDimitry Andric 
26310b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
26320b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
26330b57cec5SDimitry Andric   // restrictions can be lifted.
26340b57cec5SDimitry Andric   switch (F.getCallingConv()) {
26350b57cec5SDimitry Andric   default:
26360b57cec5SDimitry Andric   case CallingConv::C:
26370b57cec5SDimitry Andric     break;
2638e8d8bef9SDimitry Andric   case CallingConv::X86_INTR: {
263981ad6265SDimitry Andric     Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2640e8d8bef9SDimitry Andric           "Calling convention parameter requires byval", &F);
2641e8d8bef9SDimitry Andric     break;
2642e8d8bef9SDimitry Andric   }
26430b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
26440b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
264506c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_Chain:
264606c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_ChainPreserve:
264781ad6265SDimitry Andric     Check(F.getReturnType()->isVoidTy(),
26480b57cec5SDimitry Andric           "Calling convention requires void return type", &F);
2649bdd1243dSDimitry Andric     [[fallthrough]];
26500b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
26510b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
26520b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
26530b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
26540b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
265581ad6265SDimitry Andric     Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
2656e8d8bef9SDimitry Andric     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2657e8d8bef9SDimitry Andric       const unsigned StackAS = DL.getAllocaAddrSpace();
2658e8d8bef9SDimitry Andric       unsigned i = 0;
2659e8d8bef9SDimitry Andric       for (const Argument &Arg : F.args()) {
266081ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
2661e8d8bef9SDimitry Andric               "Calling convention disallows byval", &F);
266281ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2663e8d8bef9SDimitry Andric               "Calling convention disallows preallocated", &F);
266481ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2665e8d8bef9SDimitry Andric               "Calling convention disallows inalloca", &F);
2666e8d8bef9SDimitry Andric 
2667349cc55cSDimitry Andric         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2668e8d8bef9SDimitry Andric           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2669e8d8bef9SDimitry Andric           // value here.
267081ad6265SDimitry Andric           Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2671e8d8bef9SDimitry Andric                 "Calling convention disallows stack byref", &F);
2672e8d8bef9SDimitry Andric         }
2673e8d8bef9SDimitry Andric 
2674e8d8bef9SDimitry Andric         ++i;
2675e8d8bef9SDimitry Andric       }
2676e8d8bef9SDimitry Andric     }
2677e8d8bef9SDimitry Andric 
2678bdd1243dSDimitry Andric     [[fallthrough]];
26790b57cec5SDimitry Andric   case CallingConv::Fast:
26800b57cec5SDimitry Andric   case CallingConv::Cold:
26810b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
26820b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
26830b57cec5SDimitry Andric   case CallingConv::PTX_Device:
268481ad6265SDimitry Andric     Check(!F.isVarArg(),
268581ad6265SDimitry Andric           "Calling convention does not support varargs or "
26860b57cec5SDimitry Andric           "perfect forwarding!",
26870b57cec5SDimitry Andric           &F);
26880b57cec5SDimitry Andric     break;
26890b57cec5SDimitry Andric   }
26900b57cec5SDimitry Andric 
26910b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
26920b57cec5SDimitry Andric   unsigned i = 0;
26930b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
269481ad6265SDimitry Andric     Check(Arg.getType() == FT->getParamType(i),
26950b57cec5SDimitry Andric           "Argument value does not match function argument type!", &Arg,
26960b57cec5SDimitry Andric           FT->getParamType(i));
269781ad6265SDimitry Andric     Check(Arg.getType()->isFirstClassType(),
26980b57cec5SDimitry Andric           "Function arguments must have first-class types!", &Arg);
2699fe6060f1SDimitry Andric     if (!IsIntrinsic) {
270081ad6265SDimitry Andric       Check(!Arg.getType()->isMetadataTy(),
27010b57cec5SDimitry Andric             "Function takes metadata but isn't an intrinsic", &Arg, &F);
270281ad6265SDimitry Andric       Check(!Arg.getType()->isTokenTy(),
27030b57cec5SDimitry Andric             "Function takes token but isn't an intrinsic", &Arg, &F);
270481ad6265SDimitry Andric       Check(!Arg.getType()->isX86_AMXTy(),
2705fe6060f1SDimitry Andric             "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
27060b57cec5SDimitry Andric     }
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
2709349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
27100b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
27110b57cec5SDimitry Andric     }
27120b57cec5SDimitry Andric     ++i;
27130b57cec5SDimitry Andric   }
27140b57cec5SDimitry Andric 
2715fe6060f1SDimitry Andric   if (!IsIntrinsic) {
271681ad6265SDimitry Andric     Check(!F.getReturnType()->isTokenTy(),
2717fe6060f1SDimitry Andric           "Function returns a token but isn't an intrinsic", &F);
271881ad6265SDimitry Andric     Check(!F.getReturnType()->isX86_AMXTy(),
2719fe6060f1SDimitry Andric           "Function returns a x86_amx but isn't an intrinsic", &F);
2720fe6060f1SDimitry Andric   }
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric   // Get the function metadata attachments.
27230b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
27240b57cec5SDimitry Andric   F.getAllMetadata(MDs);
27250b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
27260b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   // Check validity of the personality function
27290b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
27300b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
27310b57cec5SDimitry Andric     if (Per)
273281ad6265SDimitry Andric       Check(Per->getParent() == F.getParent(),
273381ad6265SDimitry Andric             "Referencing personality function in another module!", &F,
273481ad6265SDimitry Andric             F.getParent(), Per, Per->getParent());
27350b57cec5SDimitry Andric   }
27360b57cec5SDimitry Andric 
273706c3fb27SDimitry Andric   // EH funclet coloring can be expensive, recompute on-demand
273806c3fb27SDimitry Andric   BlockEHFuncletColors.clear();
273906c3fb27SDimitry Andric 
27400b57cec5SDimitry Andric   if (F.isMaterializable()) {
27410b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
274281ad6265SDimitry Andric     Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
27430b57cec5SDimitry Andric           MDs.empty() ? nullptr : MDs.front().second);
27440b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
27450b57cec5SDimitry Andric     for (const auto &I : MDs) {
27460b57cec5SDimitry Andric       // This is used for call site debug information.
274781ad6265SDimitry Andric       CheckDI(I.first != LLVMContext::MD_dbg ||
27480b57cec5SDimitry Andric                   !cast<DISubprogram>(I.second)->isDistinct(),
27490b57cec5SDimitry Andric               "function declaration may only have a unique !dbg attachment",
27500b57cec5SDimitry Andric               &F);
275181ad6265SDimitry Andric       Check(I.first != LLVMContext::MD_prof,
27520b57cec5SDimitry Andric             "function declaration may not have a !prof attachment", &F);
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric       // Verify the metadata itself.
27555ffd83dbSDimitry Andric       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
27560b57cec5SDimitry Andric     }
275781ad6265SDimitry Andric     Check(!F.hasPersonalityFn(),
27580b57cec5SDimitry Andric           "Function declaration shouldn't have a personality routine", &F);
27590b57cec5SDimitry Andric   } else {
27600b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
27610b57cec5SDimitry Andric     // is not legal to define intrinsics.
276281ad6265SDimitry Andric     Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
27630b57cec5SDimitry Andric 
27640b57cec5SDimitry Andric     // Check the entry node
27650b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
276681ad6265SDimitry Andric     Check(pred_empty(Entry),
27670b57cec5SDimitry Andric           "Entry block to function must not have predecessors!", Entry);
27680b57cec5SDimitry Andric 
27690b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
27700b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
277181ad6265SDimitry Andric       Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
27720b57cec5SDimitry Andric             "blockaddress may not be used with the entry block!", Entry);
27730b57cec5SDimitry Andric     }
27740b57cec5SDimitry Andric 
2775bdd1243dSDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2776bdd1243dSDimitry Andric              NumKCFIAttachments = 0;
27770b57cec5SDimitry Andric     // Visit metadata attachments.
27780b57cec5SDimitry Andric     for (const auto &I : MDs) {
27790b57cec5SDimitry Andric       // Verify that the attachment is legal.
27805ffd83dbSDimitry Andric       auto AllowLocs = AreDebugLocsAllowed::No;
27810b57cec5SDimitry Andric       switch (I.first) {
27820b57cec5SDimitry Andric       default:
27830b57cec5SDimitry Andric         break;
27840b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
27850b57cec5SDimitry Andric         ++NumDebugAttachments;
278681ad6265SDimitry Andric         CheckDI(NumDebugAttachments == 1,
27870b57cec5SDimitry Andric                 "function must have a single !dbg attachment", &F, I.second);
278881ad6265SDimitry Andric         CheckDI(isa<DISubprogram>(I.second),
27890b57cec5SDimitry Andric                 "function !dbg attachment must be a subprogram", &F, I.second);
279081ad6265SDimitry Andric         CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
2791e8d8bef9SDimitry Andric                 "function definition may only have a distinct !dbg attachment",
2792e8d8bef9SDimitry Andric                 &F);
2793e8d8bef9SDimitry Andric 
27940b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
27950b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
279681ad6265SDimitry Andric         CheckDI(!AttachedTo || AttachedTo == &F,
27970b57cec5SDimitry Andric                 "DISubprogram attached to more than one function", SP, &F);
27980b57cec5SDimitry Andric         AttachedTo = &F;
27995ffd83dbSDimitry Andric         AllowLocs = AreDebugLocsAllowed::Yes;
28000b57cec5SDimitry Andric         break;
28010b57cec5SDimitry Andric       }
28020b57cec5SDimitry Andric       case LLVMContext::MD_prof:
28030b57cec5SDimitry Andric         ++NumProfAttachments;
280481ad6265SDimitry Andric         Check(NumProfAttachments == 1,
28050b57cec5SDimitry Andric               "function must have a single !prof attachment", &F, I.second);
28060b57cec5SDimitry Andric         break;
2807bdd1243dSDimitry Andric       case LLVMContext::MD_kcfi_type:
2808bdd1243dSDimitry Andric         ++NumKCFIAttachments;
2809bdd1243dSDimitry Andric         Check(NumKCFIAttachments == 1,
2810bdd1243dSDimitry Andric               "function must have a single !kcfi_type attachment", &F,
2811bdd1243dSDimitry Andric               I.second);
2812bdd1243dSDimitry Andric         break;
28130b57cec5SDimitry Andric       }
28140b57cec5SDimitry Andric 
28150b57cec5SDimitry Andric       // Verify the metadata itself.
28165ffd83dbSDimitry Andric       visitMDNode(*I.second, AllowLocs);
28170b57cec5SDimitry Andric     }
28180b57cec5SDimitry Andric   }
28190b57cec5SDimitry Andric 
28200b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
28210b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
28220b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
28230b57cec5SDimitry Andric   // uses.
2824fe6060f1SDimitry Andric   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
28250b57cec5SDimitry Andric     const User *U;
2826349cc55cSDimitry Andric     if (F.hasAddressTaken(&U, false, true, false,
2827349cc55cSDimitry Andric                           /*IgnoreARCAttachedCall=*/true))
282881ad6265SDimitry Andric       Check(false, "Invalid user of intrinsic instruction!", U);
28290b57cec5SDimitry Andric   }
28300b57cec5SDimitry Andric 
2831fe6060f1SDimitry Andric   // Check intrinsics' signatures.
2832fe6060f1SDimitry Andric   switch (F.getIntrinsicID()) {
2833fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_base: {
2834fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
283581ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
283681ad6265SDimitry Andric     Check(isa<PointerType>(F.getReturnType()),
2837fe6060f1SDimitry Andric           "gc.get.pointer.base must return a pointer", F);
283881ad6265SDimitry Andric     Check(FT->getParamType(0) == F.getReturnType(),
283981ad6265SDimitry Andric           "gc.get.pointer.base operand and result must be of the same type", F);
2840fe6060f1SDimitry Andric     break;
2841fe6060f1SDimitry Andric   }
2842fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_offset: {
2843fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
284481ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
284581ad6265SDimitry Andric     Check(isa<PointerType>(FT->getParamType(0)),
2846fe6060f1SDimitry Andric           "gc.get.pointer.offset operand must be a pointer", F);
284781ad6265SDimitry Andric     Check(F.getReturnType()->isIntegerTy(),
2848fe6060f1SDimitry Andric           "gc.get.pointer.offset must return integer", F);
2849fe6060f1SDimitry Andric     break;
2850fe6060f1SDimitry Andric   }
2851fe6060f1SDimitry Andric   }
2852fe6060f1SDimitry Andric 
28530b57cec5SDimitry Andric   auto *N = F.getSubprogram();
28540b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
28550b57cec5SDimitry Andric   if (!HasDebugInfo)
28560b57cec5SDimitry Andric     return;
28570b57cec5SDimitry Andric 
28585ffd83dbSDimitry Andric   // Check that all !dbg attachments lead to back to N.
28590b57cec5SDimitry Andric   //
28600b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
28610b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
28620b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
28630b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
28640b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
28650b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
28660b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
28670b57cec5SDimitry Andric     if (!DL)
28680b57cec5SDimitry Andric       return;
28690b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
28700b57cec5SDimitry Andric       return;
28710b57cec5SDimitry Andric 
28720b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
287381ad6265SDimitry Andric     CheckDI(Parent && isa<DILocalScope>(Parent),
287481ad6265SDimitry Andric             "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
28755ffd83dbSDimitry Andric 
28760b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
287781ad6265SDimitry Andric     Check(Scope, "Failed to find DILocalScope", DL);
28785ffd83dbSDimitry Andric 
28795ffd83dbSDimitry Andric     if (!Seen.insert(Scope).second)
28800b57cec5SDimitry Andric       return;
28810b57cec5SDimitry Andric 
28825ffd83dbSDimitry Andric     DISubprogram *SP = Scope->getSubprogram();
28830b57cec5SDimitry Andric 
28840b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
28850b57cec5SDimitry Andric     // validation in that case
28860b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
28870b57cec5SDimitry Andric       return;
28880b57cec5SDimitry Andric 
288981ad6265SDimitry Andric     CheckDI(SP->describes(&F),
28900b57cec5SDimitry Andric             "!dbg attachment points at wrong subprogram for function", N, &F,
28910b57cec5SDimitry Andric             &I, DL, Scope, SP);
28920b57cec5SDimitry Andric   };
28930b57cec5SDimitry Andric   for (auto &BB : F)
28940b57cec5SDimitry Andric     for (auto &I : BB) {
28950b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
28960b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
28970b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
28980b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
28990b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
29000b57cec5SDimitry Andric       if (BrokenDebugInfo)
29010b57cec5SDimitry Andric         return;
29020b57cec5SDimitry Andric     }
29030b57cec5SDimitry Andric }
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
29060b57cec5SDimitry Andric //
29070b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
29080b57cec5SDimitry Andric   InstsInThisBlock.clear();
29095f757f3fSDimitry Andric   ConvergenceVerifyHelper.visit(BB);
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
291281ad6265SDimitry Andric   Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
29150b57cec5SDimitry Andric   // it.
29160b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
2917e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
29180b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
29190b57cec5SDimitry Andric     llvm::sort(Preds);
29200b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
292181ad6265SDimitry Andric       Check(PN.getNumIncomingValues() == Preds.size(),
29220b57cec5SDimitry Andric             "PHINode should have one entry for each predecessor of its "
29230b57cec5SDimitry Andric             "parent basic block!",
29240b57cec5SDimitry Andric             &PN);
29250b57cec5SDimitry Andric 
29260b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
29270b57cec5SDimitry Andric       Values.clear();
29280b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
29290b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
29300b57cec5SDimitry Andric         Values.push_back(
29310b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
29320b57cec5SDimitry Andric       llvm::sort(Values);
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
29350b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
29360b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
29370b57cec5SDimitry Andric         // all identical.
29380b57cec5SDimitry Andric         //
293981ad6265SDimitry Andric         Check(i == 0 || Values[i].first != Values[i - 1].first ||
29400b57cec5SDimitry Andric                   Values[i].second == Values[i - 1].second,
29410b57cec5SDimitry Andric               "PHI node has multiple entries for the same basic block with "
29420b57cec5SDimitry Andric               "different incoming values!",
29430b57cec5SDimitry Andric               &PN, Values[i].first, Values[i].second, Values[i - 1].second);
29440b57cec5SDimitry Andric 
29450b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
29460b57cec5SDimitry Andric         // matched up.
294781ad6265SDimitry Andric         Check(Values[i].first == Preds[i],
29480b57cec5SDimitry Andric               "PHI node entries do not match predecessors!", &PN,
29490b57cec5SDimitry Andric               Values[i].first, Preds[i]);
29500b57cec5SDimitry Andric       }
29510b57cec5SDimitry Andric     }
29520b57cec5SDimitry Andric   }
29530b57cec5SDimitry Andric 
29540b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
29550b57cec5SDimitry Andric   for (auto &I : BB)
29560b57cec5SDimitry Andric   {
295781ad6265SDimitry Andric     Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
29580b57cec5SDimitry Andric   }
29595f757f3fSDimitry Andric 
29605f757f3fSDimitry Andric   // Confirm that no issues arise from the debug program.
29615f757f3fSDimitry Andric   if (BB.IsNewDbgInfoFormat) {
29625f757f3fSDimitry Andric     // Configure the validate function to not fire assertions, instead print
29635f757f3fSDimitry Andric     // errors and return true if there's a problem.
29645f757f3fSDimitry Andric     bool RetVal = BB.validateDbgValues(false, true, OS);
29655f757f3fSDimitry Andric     Check(!RetVal, "Invalid configuration of new-debug-info data found");
29665f757f3fSDimitry Andric   }
29670b57cec5SDimitry Andric }
29680b57cec5SDimitry Andric 
29690b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
29700b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
297181ad6265SDimitry Andric   Check(&I == I.getParent()->getTerminator(),
29720b57cec5SDimitry Andric         "Terminator found in the middle of a basic block!", I.getParent());
29730b57cec5SDimitry Andric   visitInstruction(I);
29740b57cec5SDimitry Andric }
29750b57cec5SDimitry Andric 
29760b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
29770b57cec5SDimitry Andric   if (BI.isConditional()) {
297881ad6265SDimitry Andric     Check(BI.getCondition()->getType()->isIntegerTy(1),
29790b57cec5SDimitry Andric           "Branch condition is not 'i1' type!", &BI, BI.getCondition());
29800b57cec5SDimitry Andric   }
29810b57cec5SDimitry Andric   visitTerminator(BI);
29820b57cec5SDimitry Andric }
29830b57cec5SDimitry Andric 
29840b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
29850b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
29860b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
29870b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
298881ad6265SDimitry Andric     Check(N == 0,
29890b57cec5SDimitry Andric           "Found return instr that returns non-void in Function of void "
29900b57cec5SDimitry Andric           "return type!",
29910b57cec5SDimitry Andric           &RI, F->getReturnType());
29920b57cec5SDimitry Andric   else
299381ad6265SDimitry Andric     Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
29940b57cec5SDimitry Andric           "Function return type does not match operand "
29950b57cec5SDimitry Andric           "type of return inst!",
29960b57cec5SDimitry Andric           &RI, F->getReturnType());
29970b57cec5SDimitry Andric 
29980b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
29990b57cec5SDimitry Andric   // terminators...
30000b57cec5SDimitry Andric   visitTerminator(RI);
30010b57cec5SDimitry Andric }
30020b57cec5SDimitry Andric 
30030b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
300481ad6265SDimitry Andric   Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
30050b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
30060b57cec5SDimitry Andric   // have the same type as the switched-on value.
30070b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
30080b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
30090b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
3010bdd1243dSDimitry Andric     Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
3011bdd1243dSDimitry Andric           "Case value is not a constant integer.", &SI);
301281ad6265SDimitry Andric     Check(Case.getCaseValue()->getType() == SwitchTy,
30130b57cec5SDimitry Andric           "Switch constants must all be same type as switch value!", &SI);
301481ad6265SDimitry Andric     Check(Constants.insert(Case.getCaseValue()).second,
30150b57cec5SDimitry Andric           "Duplicate integer as switch case", &SI, Case.getCaseValue());
30160b57cec5SDimitry Andric   }
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric   visitTerminator(SI);
30190b57cec5SDimitry Andric }
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
302281ad6265SDimitry Andric   Check(BI.getAddress()->getType()->isPointerTy(),
30230b57cec5SDimitry Andric         "Indirectbr operand must have pointer type!", &BI);
30240b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
302581ad6265SDimitry Andric     Check(BI.getDestination(i)->getType()->isLabelTy(),
30260b57cec5SDimitry Andric           "Indirectbr destinations must all have pointer type!", &BI);
30270b57cec5SDimitry Andric 
30280b57cec5SDimitry Andric   visitTerminator(BI);
30290b57cec5SDimitry Andric }
30300b57cec5SDimitry Andric 
30310b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
303281ad6265SDimitry Andric   Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
3033fe6060f1SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
303481ad6265SDimitry Andric   Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
30350b57cec5SDimitry Andric 
303604eeddc0SDimitry Andric   verifyInlineAsmCall(CBI);
30370b57cec5SDimitry Andric   visitTerminator(CBI);
30380b57cec5SDimitry Andric }
30390b57cec5SDimitry Andric 
30400b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
304181ad6265SDimitry Andric   Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
30420b57cec5SDimitry Andric                                         SI.getOperand(2)),
30430b57cec5SDimitry Andric         "Invalid operands for select instruction!", &SI);
30440b57cec5SDimitry Andric 
304581ad6265SDimitry Andric   Check(SI.getTrueValue()->getType() == SI.getType(),
30460b57cec5SDimitry Andric         "Select values must have same type as select instruction!", &SI);
30470b57cec5SDimitry Andric   visitInstruction(SI);
30480b57cec5SDimitry Andric }
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
30510b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
30520b57cec5SDimitry Andric ///
30530b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
305481ad6265SDimitry Andric   Check(false, "User-defined operators should not live outside of a pass!", &I);
30550b57cec5SDimitry Andric }
30560b57cec5SDimitry Andric 
30570b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
30580b57cec5SDimitry Andric   // Get the source and destination types
30590b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30600b57cec5SDimitry Andric   Type *DestTy = I.getType();
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
30630b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30640b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
30650b57cec5SDimitry Andric 
306681ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
306781ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
306881ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
30690b57cec5SDimitry Andric         "trunc source and destination must both be a vector or neither", &I);
307081ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric   visitInstruction(I);
30730b57cec5SDimitry Andric }
30740b57cec5SDimitry Andric 
30750b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
30760b57cec5SDimitry Andric   // Get the source and destination types
30770b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30780b57cec5SDimitry Andric   Type *DestTy = I.getType();
30790b57cec5SDimitry Andric 
30800b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
308181ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
308281ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
308381ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
30840b57cec5SDimitry Andric         "zext source and destination must both be a vector or neither", &I);
30850b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30860b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
30870b57cec5SDimitry Andric 
308881ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric   visitInstruction(I);
30910b57cec5SDimitry Andric }
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
30940b57cec5SDimitry Andric   // Get the source and destination types
30950b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30960b57cec5SDimitry Andric   Type *DestTy = I.getType();
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
30990b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
31000b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
31010b57cec5SDimitry Andric 
310281ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
310381ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
310481ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
31050b57cec5SDimitry Andric         "sext source and destination must both be a vector or neither", &I);
310681ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
31070b57cec5SDimitry Andric 
31080b57cec5SDimitry Andric   visitInstruction(I);
31090b57cec5SDimitry Andric }
31100b57cec5SDimitry Andric 
31110b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
31120b57cec5SDimitry Andric   // Get the source and destination types
31130b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31140b57cec5SDimitry Andric   Type *DestTy = I.getType();
31150b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
31160b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
31170b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
31180b57cec5SDimitry Andric 
311981ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
312081ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
312181ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
31220b57cec5SDimitry Andric         "fptrunc source and destination must both be a vector or neither", &I);
312381ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric   visitInstruction(I);
31260b57cec5SDimitry Andric }
31270b57cec5SDimitry Andric 
31280b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
31290b57cec5SDimitry Andric   // Get the source and destination types
31300b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31310b57cec5SDimitry Andric   Type *DestTy = I.getType();
31320b57cec5SDimitry Andric 
31330b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
31340b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
31350b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
31360b57cec5SDimitry Andric 
313781ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
313881ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
313981ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
31400b57cec5SDimitry Andric         "fpext source and destination must both be a vector or neither", &I);
314181ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric   visitInstruction(I);
31440b57cec5SDimitry Andric }
31450b57cec5SDimitry Andric 
31460b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
31470b57cec5SDimitry Andric   // Get the source and destination types
31480b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31490b57cec5SDimitry Andric   Type *DestTy = I.getType();
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31520b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31530b57cec5SDimitry Andric 
315481ad6265SDimitry Andric   Check(SrcVec == DstVec,
31550b57cec5SDimitry Andric         "UIToFP source and dest must both be vector or scalar", &I);
315681ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
31570b57cec5SDimitry Andric         "UIToFP source must be integer or integer vector", &I);
315881ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
31590b57cec5SDimitry Andric         &I);
31600b57cec5SDimitry Andric 
31610b57cec5SDimitry Andric   if (SrcVec && DstVec)
316281ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
31635ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
31640b57cec5SDimitry Andric           "UIToFP source and dest vector length mismatch", &I);
31650b57cec5SDimitry Andric 
31660b57cec5SDimitry Andric   visitInstruction(I);
31670b57cec5SDimitry Andric }
31680b57cec5SDimitry Andric 
31690b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
31700b57cec5SDimitry Andric   // Get the source and destination types
31710b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31720b57cec5SDimitry Andric   Type *DestTy = I.getType();
31730b57cec5SDimitry Andric 
31740b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31750b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31760b57cec5SDimitry Andric 
317781ad6265SDimitry Andric   Check(SrcVec == DstVec,
31780b57cec5SDimitry Andric         "SIToFP source and dest must both be vector or scalar", &I);
317981ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
31800b57cec5SDimitry Andric         "SIToFP source must be integer or integer vector", &I);
318181ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
31820b57cec5SDimitry Andric         &I);
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric   if (SrcVec && DstVec)
318581ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
31865ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
31870b57cec5SDimitry Andric           "SIToFP source and dest vector length mismatch", &I);
31880b57cec5SDimitry Andric 
31890b57cec5SDimitry Andric   visitInstruction(I);
31900b57cec5SDimitry Andric }
31910b57cec5SDimitry Andric 
31920b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
31930b57cec5SDimitry Andric   // Get the source and destination types
31940b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31950b57cec5SDimitry Andric   Type *DestTy = I.getType();
31960b57cec5SDimitry Andric 
31970b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31980b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31990b57cec5SDimitry Andric 
320081ad6265SDimitry Andric   Check(SrcVec == DstVec,
32010b57cec5SDimitry Andric         "FPToUI source and dest must both be vector or scalar", &I);
320281ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
320381ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
32040b57cec5SDimitry Andric         "FPToUI result must be integer or integer vector", &I);
32050b57cec5SDimitry Andric 
32060b57cec5SDimitry Andric   if (SrcVec && DstVec)
320781ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
32085ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
32090b57cec5SDimitry Andric           "FPToUI source and dest vector length mismatch", &I);
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric   visitInstruction(I);
32120b57cec5SDimitry Andric }
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &I) {
32150b57cec5SDimitry Andric   // Get the source and destination types
32160b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32170b57cec5SDimitry Andric   Type *DestTy = I.getType();
32180b57cec5SDimitry Andric 
32190b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
32200b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
32210b57cec5SDimitry Andric 
322281ad6265SDimitry Andric   Check(SrcVec == DstVec,
32230b57cec5SDimitry Andric         "FPToSI source and dest must both be vector or scalar", &I);
322481ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
322581ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
32260b57cec5SDimitry Andric         "FPToSI result must be integer or integer vector", &I);
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric   if (SrcVec && DstVec)
322981ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
32305ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
32310b57cec5SDimitry Andric           "FPToSI source and dest vector length mismatch", &I);
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   visitInstruction(I);
32340b57cec5SDimitry Andric }
32350b57cec5SDimitry Andric 
32360b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
32370b57cec5SDimitry Andric   // Get the source and destination types
32380b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32390b57cec5SDimitry Andric   Type *DestTy = I.getType();
32400b57cec5SDimitry Andric 
324181ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
32420b57cec5SDimitry Andric 
324381ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
324481ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
32450b57cec5SDimitry Andric         &I);
32460b57cec5SDimitry Andric 
32470b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
32485ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
32495ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
325081ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
32510b57cec5SDimitry Andric           "PtrToInt Vector width mismatch", &I);
32520b57cec5SDimitry Andric   }
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   visitInstruction(I);
32550b57cec5SDimitry Andric }
32560b57cec5SDimitry Andric 
32570b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
32580b57cec5SDimitry Andric   // Get the source and destination types
32590b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32600b57cec5SDimitry Andric   Type *DestTy = I.getType();
32610b57cec5SDimitry Andric 
326281ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
326381ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
32640b57cec5SDimitry Andric 
326581ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
32660b57cec5SDimitry Andric         &I);
32670b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
32685ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
32695ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
327081ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
32710b57cec5SDimitry Andric           "IntToPtr Vector width mismatch", &I);
32720b57cec5SDimitry Andric   }
32730b57cec5SDimitry Andric   visitInstruction(I);
32740b57cec5SDimitry Andric }
32750b57cec5SDimitry Andric 
32760b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
327781ad6265SDimitry Andric   Check(
32780b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
32790b57cec5SDimitry Andric       "Invalid bitcast", &I);
32800b57cec5SDimitry Andric   visitInstruction(I);
32810b57cec5SDimitry Andric }
32820b57cec5SDimitry Andric 
32830b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
32840b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32850b57cec5SDimitry Andric   Type *DestTy = I.getType();
32860b57cec5SDimitry Andric 
328781ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
32880b57cec5SDimitry Andric         &I);
328981ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
32900b57cec5SDimitry Andric         &I);
329181ad6265SDimitry Andric   Check(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
32920b57cec5SDimitry Andric         "AddrSpaceCast must be between different address spaces", &I);
32935ffd83dbSDimitry Andric   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
329481ad6265SDimitry Andric     Check(SrcVTy->getElementCount() ==
3295e8d8bef9SDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
32960b57cec5SDimitry Andric           "AddrSpaceCast vector pointer number of elements mismatch", &I);
32970b57cec5SDimitry Andric   visitInstruction(I);
32980b57cec5SDimitry Andric }
32990b57cec5SDimitry Andric 
33000b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
33010b57cec5SDimitry Andric ///
33020b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
33030b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
33040b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
33050b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
33060b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
330781ad6265SDimitry Andric   Check(&PN == &PN.getParent()->front() ||
33080b57cec5SDimitry Andric             isa<PHINode>(--BasicBlock::iterator(&PN)),
33090b57cec5SDimitry Andric         "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
331281ad6265SDimitry Andric   Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
33130b57cec5SDimitry Andric 
33140b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
33150b57cec5SDimitry Andric   // result, and that the incoming blocks are really basic blocks.
33160b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
331781ad6265SDimitry Andric     Check(PN.getType() == IncValue->getType(),
33180b57cec5SDimitry Andric           "PHI node operands are not the same type as the result!", &PN);
33190b57cec5SDimitry Andric   }
33200b57cec5SDimitry Andric 
33210b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
33220b57cec5SDimitry Andric 
33230b57cec5SDimitry Andric   visitInstruction(PN);
33240b57cec5SDimitry Andric }
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
332781ad6265SDimitry Andric   Check(Call.getCalledOperand()->getType()->isPointerTy(),
33280b57cec5SDimitry Andric         "Called function must be a pointer!", Call);
33290b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
33300b57cec5SDimitry Andric 
33310b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
33320b57cec5SDimitry Andric   if (FTy->isVarArg())
333381ad6265SDimitry Andric     Check(Call.arg_size() >= FTy->getNumParams(),
333481ad6265SDimitry Andric           "Called function requires more parameters than were provided!", Call);
33350b57cec5SDimitry Andric   else
333681ad6265SDimitry Andric     Check(Call.arg_size() == FTy->getNumParams(),
33370b57cec5SDimitry Andric           "Incorrect number of arguments passed to called function!", Call);
33380b57cec5SDimitry Andric 
33390b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
33400b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
334181ad6265SDimitry Andric     Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
33420b57cec5SDimitry Andric           "Call parameter type does not match function signature!",
33430b57cec5SDimitry Andric           Call.getArgOperand(i), FTy->getParamType(i), Call);
33440b57cec5SDimitry Andric 
33450b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
33460b57cec5SDimitry Andric 
334781ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, Call.arg_size()),
33480b57cec5SDimitry Andric         "Attribute after last parameter!", Call);
33490b57cec5SDimitry Andric 
3350bdd1243dSDimitry Andric   Function *Callee =
3351bdd1243dSDimitry Andric       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3352bdd1243dSDimitry Andric   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3353bdd1243dSDimitry Andric   if (IsIntrinsic)
3354bdd1243dSDimitry Andric     Check(Callee->getValueType() == FTy,
3355bdd1243dSDimitry Andric           "Intrinsic called with incompatible signature", Call);
3356bdd1243dSDimitry Andric 
335706c3fb27SDimitry Andric   // Disallow calls to functions with the amdgpu_cs_chain[_preserve] calling
335806c3fb27SDimitry Andric   // convention.
335906c3fb27SDimitry Andric   auto CC = Call.getCallingConv();
336006c3fb27SDimitry Andric   Check(CC != CallingConv::AMDGPU_CS_Chain &&
336106c3fb27SDimitry Andric             CC != CallingConv::AMDGPU_CS_ChainPreserve,
336206c3fb27SDimitry Andric         "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
336306c3fb27SDimitry Andric         "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
336406c3fb27SDimitry Andric         Call);
336506c3fb27SDimitry Andric 
336681ad6265SDimitry Andric   auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
336781ad6265SDimitry Andric     if (!Ty->isSized())
336881ad6265SDimitry Andric       return;
336981ad6265SDimitry Andric     Align ABIAlign = DL.getABITypeAlign(Ty);
337081ad6265SDimitry Andric     Align MaxAlign(ParamMaxAlignment);
337181ad6265SDimitry Andric     Check(ABIAlign <= MaxAlign,
337281ad6265SDimitry Andric           "Incorrect alignment of " + Message + " to called function!", Call);
337381ad6265SDimitry Andric   };
337481ad6265SDimitry Andric 
3375bdd1243dSDimitry Andric   if (!IsIntrinsic) {
337681ad6265SDimitry Andric     VerifyTypeAlign(FTy->getReturnType(), "return type");
337781ad6265SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
337881ad6265SDimitry Andric       Type *Ty = FTy->getParamType(i);
337981ad6265SDimitry Andric       VerifyTypeAlign(Ty, "argument passed");
338081ad6265SDimitry Andric     }
3381bdd1243dSDimitry Andric   }
33820b57cec5SDimitry Andric 
3383349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
33840b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
33850b57cec5SDimitry Andric     // declaration is also speculatable.
338681ad6265SDimitry Andric     Check(Callee && Callee->isSpeculatable(),
33870b57cec5SDimitry Andric           "speculatable attribute may not apply to call sites", Call);
33880b57cec5SDimitry Andric   }
33890b57cec5SDimitry Andric 
3390349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
339181ad6265SDimitry Andric     Check(Call.getCalledFunction()->getIntrinsicID() ==
33925ffd83dbSDimitry Andric               Intrinsic::call_preallocated_arg,
33935ffd83dbSDimitry Andric           "preallocated as a call site attribute can only be on "
33945ffd83dbSDimitry Andric           "llvm.call.preallocated.arg");
33955ffd83dbSDimitry Andric   }
33965ffd83dbSDimitry Andric 
33970b57cec5SDimitry Andric   // Verify call attributes.
339804eeddc0SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
33990b57cec5SDimitry Andric 
34000b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
34010b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
34020b57cec5SDimitry Andric   // inalloca.
34030b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
34040b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
34050b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
340681ad6265SDimitry Andric       Check(AI->isUsedWithInAlloca(),
34070b57cec5SDimitry Andric             "inalloca argument for call has mismatched alloca", AI, Call);
34080b57cec5SDimitry Andric   }
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
34110b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
34120b57cec5SDimitry Andric   // well.
34130b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
34140b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
34150b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
34160b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
341781ad6265SDimitry Andric         Check(AI->isSwiftError(),
34180b57cec5SDimitry Andric               "swifterror argument for call has mismatched alloca", AI, Call);
34190b57cec5SDimitry Andric         continue;
34200b57cec5SDimitry Andric       }
34210b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
342281ad6265SDimitry Andric       Check(ArgI, "swifterror argument should come from an alloca or parameter",
34230b57cec5SDimitry Andric             SwiftErrorArg, Call);
342481ad6265SDimitry Andric       Check(ArgI->hasSwiftErrorAttr(),
34250b57cec5SDimitry Andric             "swifterror argument for call has mismatched parameter", ArgI,
34260b57cec5SDimitry Andric             Call);
34270b57cec5SDimitry Andric     }
34280b57cec5SDimitry Andric 
3429349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
34300b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
34310b57cec5SDimitry Andric       // also has the matching immarg.
343281ad6265SDimitry Andric       Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
343381ad6265SDimitry Andric             "immarg may not apply only to call sites", Call.getArgOperand(i),
343481ad6265SDimitry Andric             Call);
34350b57cec5SDimitry Andric     }
34360b57cec5SDimitry Andric 
34370b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
34380b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
343981ad6265SDimitry Andric       Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
34400b57cec5SDimitry Andric             "immarg operand has non-immediate parameter", ArgVal, Call);
34410b57cec5SDimitry Andric     }
34425ffd83dbSDimitry Andric 
34435ffd83dbSDimitry Andric     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
34445ffd83dbSDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
34455ffd83dbSDimitry Andric       bool hasOB =
34465ffd83dbSDimitry Andric           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
34475ffd83dbSDimitry Andric       bool isMustTail = Call.isMustTailCall();
344881ad6265SDimitry Andric       Check(hasOB != isMustTail,
34495ffd83dbSDimitry Andric             "preallocated operand either requires a preallocated bundle or "
34505ffd83dbSDimitry Andric             "the call to be musttail (but not both)",
34515ffd83dbSDimitry Andric             ArgVal, Call);
34525ffd83dbSDimitry Andric     }
34530b57cec5SDimitry Andric   }
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric   if (FTy->isVarArg()) {
34560b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
34570b57cec5SDimitry Andric     bool SawNest = false;
34580b57cec5SDimitry Andric     bool SawReturned = false;
34590b57cec5SDimitry Andric 
34600b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3461349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
34620b57cec5SDimitry Andric         SawNest = true;
3463349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
34640b57cec5SDimitry Andric         SawReturned = true;
34650b57cec5SDimitry Andric     }
34660b57cec5SDimitry Andric 
34670b57cec5SDimitry Andric     // Check attributes on the varargs part.
34680b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
34690b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
3470349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
34710b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
34720b57cec5SDimitry Andric 
34730b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
347481ad6265SDimitry Andric         Check(!SawNest, "More than one parameter has attribute nest!", Call);
34750b57cec5SDimitry Andric         SawNest = true;
34760b57cec5SDimitry Andric       }
34770b57cec5SDimitry Andric 
34780b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
347981ad6265SDimitry Andric         Check(!SawReturned, "More than one parameter has attribute returned!",
34800b57cec5SDimitry Andric               Call);
348181ad6265SDimitry Andric         Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
34820b57cec5SDimitry Andric               "Incompatible argument and return types for 'returned' "
34830b57cec5SDimitry Andric               "attribute",
34840b57cec5SDimitry Andric               Call);
34850b57cec5SDimitry Andric         SawReturned = true;
34860b57cec5SDimitry Andric       }
34870b57cec5SDimitry Andric 
34880b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
34890b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
34900b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
34910b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
34920b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
349381ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
34940b57cec5SDimitry Andric               "Attribute 'sret' cannot be used for vararg call arguments!",
34950b57cec5SDimitry Andric               Call);
34960b57cec5SDimitry Andric 
34970b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
349881ad6265SDimitry Andric         Check(Idx == Call.arg_size() - 1,
34990b57cec5SDimitry Andric               "inalloca isn't on the last argument!", Call);
35000b57cec5SDimitry Andric     }
35010b57cec5SDimitry Andric   }
35020b57cec5SDimitry Andric 
35030b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
35040b57cec5SDimitry Andric   if (!IsIntrinsic) {
35050b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
350681ad6265SDimitry Andric       Check(!ParamTy->isMetadataTy(),
35070b57cec5SDimitry Andric             "Function has metadata parameter but isn't an intrinsic", Call);
350881ad6265SDimitry Andric       Check(!ParamTy->isTokenTy(),
35090b57cec5SDimitry Andric             "Function has token parameter but isn't an intrinsic", Call);
35100b57cec5SDimitry Andric     }
35110b57cec5SDimitry Andric   }
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
3514fe6060f1SDimitry Andric   if (!Call.getCalledFunction()) {
351581ad6265SDimitry Andric     Check(!FTy->getReturnType()->isTokenTy(),
35160b57cec5SDimitry Andric           "Return type cannot be token for indirect call!");
351781ad6265SDimitry Andric     Check(!FTy->getReturnType()->isX86_AMXTy(),
3518fe6060f1SDimitry Andric           "Return type cannot be x86_amx for indirect call!");
3519fe6060f1SDimitry Andric   }
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
35220b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
35230b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
35240b57cec5SDimitry Andric 
3525480093f4SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet", at
352681ad6265SDimitry Andric   // most one "gc-transition", at most one "cfguardtarget", at most one
352781ad6265SDimitry Andric   // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
35280b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
35295ffd83dbSDimitry Andric        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3530fe6060f1SDimitry Andric        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3531bdd1243dSDimitry Andric        FoundPtrauthBundle = false, FoundKCFIBundle = false,
3532fe6060f1SDimitry Andric        FoundAttachedCallBundle = false;
35330b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
35340b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
35350b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
35360b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
353781ad6265SDimitry Andric       Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
35380b57cec5SDimitry Andric       FoundDeoptBundle = true;
35390b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
354081ad6265SDimitry Andric       Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
35410b57cec5SDimitry Andric             Call);
35420b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
35430b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
354481ad6265SDimitry Andric       Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
35450b57cec5SDimitry Andric       FoundFuncletBundle = true;
354681ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
35470b57cec5SDimitry Andric             "Expected exactly one funclet bundle operand", Call);
354881ad6265SDimitry Andric       Check(isa<FuncletPadInst>(BU.Inputs.front()),
35490b57cec5SDimitry Andric             "Funclet bundle operands should correspond to a FuncletPadInst",
35500b57cec5SDimitry Andric             Call);
3551480093f4SDimitry Andric     } else if (Tag == LLVMContext::OB_cfguardtarget) {
355281ad6265SDimitry Andric       Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
355381ad6265SDimitry Andric             Call);
3554480093f4SDimitry Andric       FoundCFGuardTargetBundle = true;
355581ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
3556480093f4SDimitry Andric             "Expected exactly one cfguardtarget bundle operand", Call);
355781ad6265SDimitry Andric     } else if (Tag == LLVMContext::OB_ptrauth) {
355881ad6265SDimitry Andric       Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
355981ad6265SDimitry Andric       FoundPtrauthBundle = true;
356081ad6265SDimitry Andric       Check(BU.Inputs.size() == 2,
356181ad6265SDimitry Andric             "Expected exactly two ptrauth bundle operands", Call);
356281ad6265SDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
356381ad6265SDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
356481ad6265SDimitry Andric             "Ptrauth bundle key operand must be an i32 constant", Call);
356581ad6265SDimitry Andric       Check(BU.Inputs[1]->getType()->isIntegerTy(64),
356681ad6265SDimitry Andric             "Ptrauth bundle discriminator operand must be an i64", Call);
3567bdd1243dSDimitry Andric     } else if (Tag == LLVMContext::OB_kcfi) {
3568bdd1243dSDimitry Andric       Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
3569bdd1243dSDimitry Andric       FoundKCFIBundle = true;
3570bdd1243dSDimitry Andric       Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
3571bdd1243dSDimitry Andric             Call);
3572bdd1243dSDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
3573bdd1243dSDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
3574bdd1243dSDimitry Andric             "Kcfi bundle operand must be an i32 constant", Call);
35755ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_preallocated) {
357681ad6265SDimitry Andric       Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
35775ffd83dbSDimitry Andric             Call);
35785ffd83dbSDimitry Andric       FoundPreallocatedBundle = true;
357981ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
35805ffd83dbSDimitry Andric             "Expected exactly one preallocated bundle operand", Call);
35815ffd83dbSDimitry Andric       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
358281ad6265SDimitry Andric       Check(Input &&
35835ffd83dbSDimitry Andric                 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
35845ffd83dbSDimitry Andric             "\"preallocated\" argument must be a token from "
35855ffd83dbSDimitry Andric             "llvm.call.preallocated.setup",
35865ffd83dbSDimitry Andric             Call);
35875ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_gc_live) {
358881ad6265SDimitry Andric       Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
35895ffd83dbSDimitry Andric       FoundGCLiveBundle = true;
3590fe6060f1SDimitry Andric     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
359181ad6265SDimitry Andric       Check(!FoundAttachedCallBundle,
3592fe6060f1SDimitry Andric             "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3593fe6060f1SDimitry Andric       FoundAttachedCallBundle = true;
3594349cc55cSDimitry Andric       verifyAttachedCallBundle(Call, BU);
35950b57cec5SDimitry Andric     }
35960b57cec5SDimitry Andric   }
35970b57cec5SDimitry Andric 
359881ad6265SDimitry Andric   // Verify that callee and callsite agree on whether to use pointer auth.
359981ad6265SDimitry Andric   Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
360081ad6265SDimitry Andric         "Direct call cannot have a ptrauth bundle", Call);
360181ad6265SDimitry Andric 
36020b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
36030b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
3604bdd1243dSDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info
3605bdd1243dSDimitry Andric   // (Interposable functions are not inlinable, neither are functions without
3606bdd1243dSDimitry Andric   //  definitions.)
36070b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3608bdd1243dSDimitry Andric       !Call.getCalledFunction()->isInterposable() &&
3609bdd1243dSDimitry Andric       !Call.getCalledFunction()->isDeclaration() &&
36100b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
361181ad6265SDimitry Andric     CheckDI(Call.getDebugLoc(),
36120b57cec5SDimitry Andric             "inlinable function call in a function with "
36130b57cec5SDimitry Andric             "debug info must have a !dbg location",
36140b57cec5SDimitry Andric             Call);
36150b57cec5SDimitry Andric 
361604eeddc0SDimitry Andric   if (Call.isInlineAsm())
361704eeddc0SDimitry Andric     verifyInlineAsmCall(Call);
361804eeddc0SDimitry Andric 
36195f757f3fSDimitry Andric   ConvergenceVerifyHelper.visit(Call);
362006c3fb27SDimitry Andric 
36210b57cec5SDimitry Andric   visitInstruction(Call);
36220b57cec5SDimitry Andric }
36230b57cec5SDimitry Andric 
36240eae32dcSDimitry Andric void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3625fe6060f1SDimitry Andric                                          StringRef Context) {
362681ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InAlloca),
3627fe6060f1SDimitry Andric         Twine("inalloca attribute not allowed in ") + Context);
362881ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InReg),
3629fe6060f1SDimitry Andric         Twine("inreg attribute not allowed in ") + Context);
363081ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::SwiftError),
3631fe6060f1SDimitry Andric         Twine("swifterror attribute not allowed in ") + Context);
363281ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::Preallocated),
3633fe6060f1SDimitry Andric         Twine("preallocated attribute not allowed in ") + Context);
363481ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::ByRef),
3635fe6060f1SDimitry Andric         Twine("byref attribute not allowed in ") + Context);
3636fe6060f1SDimitry Andric }
3637fe6060f1SDimitry Andric 
36380b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
36390b57cec5SDimitry Andric /// types with different pointee types and the same address space.
36400b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
36410b57cec5SDimitry Andric   if (L == R)
36420b57cec5SDimitry Andric     return true;
36430b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
36440b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
36450b57cec5SDimitry Andric   if (!PL || !PR)
36460b57cec5SDimitry Andric     return false;
36470b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
36480b57cec5SDimitry Andric }
36490b57cec5SDimitry Andric 
365004eeddc0SDimitry Andric static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
36510b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
36520b57cec5SDimitry Andric       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3653fe6060f1SDimitry Andric       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3654fe6060f1SDimitry Andric       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3655fe6060f1SDimitry Andric       Attribute::ByRef};
365604eeddc0SDimitry Andric   AttrBuilder Copy(C);
36570b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
3658349cc55cSDimitry Andric     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3659fe6060f1SDimitry Andric     if (Attr.isValid())
3660fe6060f1SDimitry Andric       Copy.addAttribute(Attr);
36610b57cec5SDimitry Andric   }
3662e8d8bef9SDimitry Andric 
3663e8d8bef9SDimitry Andric   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3664349cc55cSDimitry Andric   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3665349cc55cSDimitry Andric       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3666349cc55cSDimitry Andric        Attrs.hasParamAttr(I, Attribute::ByRef)))
36670b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
36680b57cec5SDimitry Andric   return Copy;
36690b57cec5SDimitry Andric }
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
367281ad6265SDimitry Andric   Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
36750b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
36760b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
367781ad6265SDimitry Andric   Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
36780b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched varargs", &CI);
367981ad6265SDimitry Andric   Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
36800b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched return types", &CI);
36810b57cec5SDimitry Andric 
36820b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
368381ad6265SDimitry Andric   Check(F->getCallingConv() == CI.getCallingConv(),
36840b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched calling conv", &CI);
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
36870b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
36880b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
36890b57cec5SDimitry Andric   //   produced by the call or void.
36900b57cec5SDimitry Andric   Value *RetVal = &CI;
36910b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
36920b57cec5SDimitry Andric 
36930b57cec5SDimitry Andric   // Handle the optional bitcast.
36940b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
369581ad6265SDimitry Andric     Check(BI->getOperand(0) == RetVal,
36960b57cec5SDimitry Andric           "bitcast following musttail call must use the call", BI);
36970b57cec5SDimitry Andric     RetVal = BI;
36980b57cec5SDimitry Andric     Next = BI->getNextNode();
36990b57cec5SDimitry Andric   }
37000b57cec5SDimitry Andric 
37010b57cec5SDimitry Andric   // Check the return.
37020b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
370381ad6265SDimitry Andric   Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
370481ad6265SDimitry Andric   Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3705fe6060f1SDimitry Andric             isa<UndefValue>(Ret->getReturnValue()),
37060b57cec5SDimitry Andric         "musttail call result must be returned", Ret);
3707fe6060f1SDimitry Andric 
3708fe6060f1SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
3709fe6060f1SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
3710fe6060f1SDimitry Andric   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3711fe6060f1SDimitry Andric       CI.getCallingConv() == CallingConv::Tail) {
3712fe6060f1SDimitry Andric     StringRef CCName =
3713fe6060f1SDimitry Andric         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3714fe6060f1SDimitry Andric 
3715fe6060f1SDimitry Andric     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3716fe6060f1SDimitry Andric     //   are allowed in swifttailcc call
3717349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
371804eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3719fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3720fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3721fe6060f1SDimitry Andric     }
3722349cc55cSDimitry Andric     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
372304eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3724fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3725fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3726fe6060f1SDimitry Andric     }
3727fe6060f1SDimitry Andric     // - Varargs functions are not allowed
372881ad6265SDimitry Andric     Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3729fe6060f1SDimitry Andric                                      " tail call for varargs function");
3730fe6060f1SDimitry Andric     return;
3731fe6060f1SDimitry Andric   }
3732fe6060f1SDimitry Andric 
3733fe6060f1SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
3734fe6060f1SDimitry Andric   //   parameters or return types may differ in pointee type, but not
3735fe6060f1SDimitry Andric   //   address space.
3736fe6060f1SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
373781ad6265SDimitry Andric     Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
373881ad6265SDimitry Andric           "cannot guarantee tail call due to mismatched parameter counts", &CI);
3739349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
374081ad6265SDimitry Andric       Check(
3741fe6060f1SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3742fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
3743fe6060f1SDimitry Andric     }
3744fe6060f1SDimitry Andric   }
3745fe6060f1SDimitry Andric 
3746fe6060f1SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3747fe6060f1SDimitry Andric   //   returned, preallocated, and inalloca, must match.
3748349cc55cSDimitry Andric   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
374904eeddc0SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
375004eeddc0SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
375181ad6265SDimitry Andric     Check(CallerABIAttrs == CalleeABIAttrs,
3752fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched ABI impacting "
3753fe6060f1SDimitry Andric           "function attributes",
3754fe6060f1SDimitry Andric           &CI, CI.getOperand(I));
3755fe6060f1SDimitry Andric   }
37560b57cec5SDimitry Andric }
37570b57cec5SDimitry Andric 
37580b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
37590b57cec5SDimitry Andric   visitCallBase(CI);
37600b57cec5SDimitry Andric 
37610b57cec5SDimitry Andric   if (CI.isMustTailCall())
37620b57cec5SDimitry Andric     verifyMustTailCall(CI);
37630b57cec5SDimitry Andric }
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
37660b57cec5SDimitry Andric   visitCallBase(II);
37670b57cec5SDimitry Andric 
37680b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
37690b57cec5SDimitry Andric   // exception handling instruction.
377081ad6265SDimitry Andric   Check(
37710b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
37720b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
37730b57cec5SDimitry Andric       &II);
37740b57cec5SDimitry Andric 
37750b57cec5SDimitry Andric   visitTerminator(II);
37760b57cec5SDimitry Andric }
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
37790b57cec5SDimitry Andric ///
37800b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
378181ad6265SDimitry Andric   Check(U.getType() == U.getOperand(0)->getType(),
37820b57cec5SDimitry Andric         "Unary operators must have same type for"
37830b57cec5SDimitry Andric         "operands and result!",
37840b57cec5SDimitry Andric         &U);
37850b57cec5SDimitry Andric 
37860b57cec5SDimitry Andric   switch (U.getOpcode()) {
37870b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
37880b57cec5SDimitry Andric   // floating-point operands.
37890b57cec5SDimitry Andric   case Instruction::FNeg:
379081ad6265SDimitry Andric     Check(U.getType()->isFPOrFPVectorTy(),
37910b57cec5SDimitry Andric           "FNeg operator only works with float types!", &U);
37920b57cec5SDimitry Andric     break;
37930b57cec5SDimitry Andric   default:
37940b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
37950b57cec5SDimitry Andric   }
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric   visitInstruction(U);
37980b57cec5SDimitry Andric }
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
38010b57cec5SDimitry Andric /// of the same type!
38020b57cec5SDimitry Andric ///
38030b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
380481ad6265SDimitry Andric   Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
38050b57cec5SDimitry Andric         "Both operands to a binary operator are not of the same type!", &B);
38060b57cec5SDimitry Andric 
38070b57cec5SDimitry Andric   switch (B.getOpcode()) {
38080b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
38090b57cec5SDimitry Andric   // integral operands.
38100b57cec5SDimitry Andric   case Instruction::Add:
38110b57cec5SDimitry Andric   case Instruction::Sub:
38120b57cec5SDimitry Andric   case Instruction::Mul:
38130b57cec5SDimitry Andric   case Instruction::SDiv:
38140b57cec5SDimitry Andric   case Instruction::UDiv:
38150b57cec5SDimitry Andric   case Instruction::SRem:
38160b57cec5SDimitry Andric   case Instruction::URem:
381781ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
38180b57cec5SDimitry Andric           "Integer arithmetic operators only work with integral types!", &B);
381981ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
38200b57cec5SDimitry Andric           "Integer arithmetic operators must have same type "
38210b57cec5SDimitry Andric           "for operands and result!",
38220b57cec5SDimitry Andric           &B);
38230b57cec5SDimitry Andric     break;
38240b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
38250b57cec5SDimitry Andric   // floating-point operands.
38260b57cec5SDimitry Andric   case Instruction::FAdd:
38270b57cec5SDimitry Andric   case Instruction::FSub:
38280b57cec5SDimitry Andric   case Instruction::FMul:
38290b57cec5SDimitry Andric   case Instruction::FDiv:
38300b57cec5SDimitry Andric   case Instruction::FRem:
383181ad6265SDimitry Andric     Check(B.getType()->isFPOrFPVectorTy(),
38320b57cec5SDimitry Andric           "Floating-point arithmetic operators only work with "
38330b57cec5SDimitry Andric           "floating-point types!",
38340b57cec5SDimitry Andric           &B);
383581ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
38360b57cec5SDimitry Andric           "Floating-point arithmetic operators must have same type "
38370b57cec5SDimitry Andric           "for operands and result!",
38380b57cec5SDimitry Andric           &B);
38390b57cec5SDimitry Andric     break;
38400b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
38410b57cec5SDimitry Andric   case Instruction::And:
38420b57cec5SDimitry Andric   case Instruction::Or:
38430b57cec5SDimitry Andric   case Instruction::Xor:
384481ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
38450b57cec5SDimitry Andric           "Logical operators only work with integral types!", &B);
384681ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
384781ad6265SDimitry Andric           "Logical operators must have same type for operands and result!", &B);
38480b57cec5SDimitry Andric     break;
38490b57cec5SDimitry Andric   case Instruction::Shl:
38500b57cec5SDimitry Andric   case Instruction::LShr:
38510b57cec5SDimitry Andric   case Instruction::AShr:
385281ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
38530b57cec5SDimitry Andric           "Shifts only work with integral types!", &B);
385481ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
38550b57cec5SDimitry Andric           "Shift return type must be same as operands!", &B);
38560b57cec5SDimitry Andric     break;
38570b57cec5SDimitry Andric   default:
38580b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
38590b57cec5SDimitry Andric   }
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric   visitInstruction(B);
38620b57cec5SDimitry Andric }
38630b57cec5SDimitry Andric 
38640b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
38650b57cec5SDimitry Andric   // Check that the operands are the same type
38660b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
38670b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
386881ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
38690b57cec5SDimitry Andric         "Both operands to ICmp instruction are not of the same type!", &IC);
38700b57cec5SDimitry Andric   // Check that the operands are the right type
387181ad6265SDimitry Andric   Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
38720b57cec5SDimitry Andric         "Invalid operand types for ICmp instruction", &IC);
38730b57cec5SDimitry Andric   // Check that the predicate is valid.
387481ad6265SDimitry Andric   Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric   visitInstruction(IC);
38770b57cec5SDimitry Andric }
38780b57cec5SDimitry Andric 
38790b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
38800b57cec5SDimitry Andric   // Check that the operands are the same type
38810b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
38820b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
388381ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
38840b57cec5SDimitry Andric         "Both operands to FCmp instruction are not of the same type!", &FC);
38850b57cec5SDimitry Andric   // Check that the operands are the right type
388681ad6265SDimitry Andric   Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
388781ad6265SDimitry Andric         &FC);
38880b57cec5SDimitry Andric   // Check that the predicate is valid.
388981ad6265SDimitry Andric   Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
38900b57cec5SDimitry Andric 
38910b57cec5SDimitry Andric   visitInstruction(FC);
38920b57cec5SDimitry Andric }
38930b57cec5SDimitry Andric 
38940b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
389581ad6265SDimitry Andric   Check(ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
38960b57cec5SDimitry Andric         "Invalid extractelement operands!", &EI);
38970b57cec5SDimitry Andric   visitInstruction(EI);
38980b57cec5SDimitry Andric }
38990b57cec5SDimitry Andric 
39000b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
390181ad6265SDimitry Andric   Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
39020b57cec5SDimitry Andric                                            IE.getOperand(2)),
39030b57cec5SDimitry Andric         "Invalid insertelement operands!", &IE);
39040b57cec5SDimitry Andric   visitInstruction(IE);
39050b57cec5SDimitry Andric }
39060b57cec5SDimitry Andric 
39070b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
390881ad6265SDimitry Andric   Check(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
39095ffd83dbSDimitry Andric                                            SV.getShuffleMask()),
39100b57cec5SDimitry Andric         "Invalid shufflevector operands!", &SV);
39110b57cec5SDimitry Andric   visitInstruction(SV);
39120b57cec5SDimitry Andric }
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
39150b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
39160b57cec5SDimitry Andric 
391781ad6265SDimitry Andric   Check(isa<PointerType>(TargetTy),
39180b57cec5SDimitry Andric         "GEP base pointer is not a vector or a vector of pointers", &GEP);
391981ad6265SDimitry Andric   Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
39200b57cec5SDimitry Andric 
392106c3fb27SDimitry Andric   if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
392206c3fb27SDimitry Andric     SmallPtrSet<Type *, 4> Visited;
392306c3fb27SDimitry Andric     Check(!STy->containsScalableVectorType(&Visited),
392406c3fb27SDimitry Andric           "getelementptr cannot target structure that contains scalable vector"
392506c3fb27SDimitry Andric           "type",
392606c3fb27SDimitry Andric           &GEP);
392706c3fb27SDimitry Andric   }
392806c3fb27SDimitry Andric 
3929e8d8bef9SDimitry Andric   SmallVector<Value *, 16> Idxs(GEP.indices());
393081ad6265SDimitry Andric   Check(
393181ad6265SDimitry Andric       all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
39320b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
39330b57cec5SDimitry Andric   Type *ElTy =
39340b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
393581ad6265SDimitry Andric   Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
39360b57cec5SDimitry Andric 
393781ad6265SDimitry Andric   Check(GEP.getType()->isPtrOrPtrVectorTy() &&
39380b57cec5SDimitry Andric             GEP.getResultElementType() == ElTy,
39390b57cec5SDimitry Andric         "GEP is not of right type for indices!", &GEP, ElTy);
39400b57cec5SDimitry Andric 
39415ffd83dbSDimitry Andric   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
39420b57cec5SDimitry Andric     // Additional checks for vector GEPs.
39435ffd83dbSDimitry Andric     ElementCount GEPWidth = GEPVTy->getElementCount();
39440b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
394581ad6265SDimitry Andric       Check(
39465ffd83dbSDimitry Andric           GEPWidth ==
39475ffd83dbSDimitry Andric               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
39480b57cec5SDimitry Andric           "Vector GEP result width doesn't match operand's", &GEP);
39490b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
39500b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
39515ffd83dbSDimitry Andric       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
39525ffd83dbSDimitry Andric         ElementCount IndexWidth = IndexVTy->getElementCount();
395381ad6265SDimitry Andric         Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
39540b57cec5SDimitry Andric       }
395581ad6265SDimitry Andric       Check(IndexTy->isIntOrIntVectorTy(),
39560b57cec5SDimitry Andric             "All GEP indices should be of integer type");
39570b57cec5SDimitry Andric     }
39580b57cec5SDimitry Andric   }
39590b57cec5SDimitry Andric 
39600b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
396181ad6265SDimitry Andric     Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
39620b57cec5SDimitry Andric           "GEP address space doesn't match type", &GEP);
39630b57cec5SDimitry Andric   }
39640b57cec5SDimitry Andric 
39650b57cec5SDimitry Andric   visitInstruction(GEP);
39660b57cec5SDimitry Andric }
39670b57cec5SDimitry Andric 
39680b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
39690b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
39700b57cec5SDimitry Andric }
39710b57cec5SDimitry Andric 
397206c3fb27SDimitry Andric /// Verify !range and !absolute_symbol metadata. These have the same
397306c3fb27SDimitry Andric /// restrictions, except !absolute_symbol allows the full set.
397406c3fb27SDimitry Andric void Verifier::verifyRangeMetadata(const Value &I, const MDNode *Range,
397506c3fb27SDimitry Andric                                    Type *Ty, bool IsAbsoluteSymbol) {
39760b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
397781ad6265SDimitry Andric   Check(NumOperands % 2 == 0, "Unfinished range!", Range);
39780b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
397981ad6265SDimitry Andric   Check(NumRanges >= 1, "It should have at least one range!", Range);
39800b57cec5SDimitry Andric 
39810b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
39820b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
39830b57cec5SDimitry Andric     ConstantInt *Low =
39840b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
398581ad6265SDimitry Andric     Check(Low, "The lower limit must be an integer!", Low);
39860b57cec5SDimitry Andric     ConstantInt *High =
39870b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
398881ad6265SDimitry Andric     Check(High, "The upper limit must be an integer!", High);
398906c3fb27SDimitry Andric     Check(High->getType() == Low->getType() &&
399006c3fb27SDimitry Andric           High->getType() == Ty->getScalarType(),
39910b57cec5SDimitry Andric           "Range types must match instruction type!", &I);
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric     APInt HighV = High->getValue();
39940b57cec5SDimitry Andric     APInt LowV = Low->getValue();
399506c3fb27SDimitry Andric 
399606c3fb27SDimitry Andric     // ConstantRange asserts if the ranges are the same except for the min/max
399706c3fb27SDimitry Andric     // value. Leave the cases it tolerates for the empty range error below.
399806c3fb27SDimitry Andric     Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
399906c3fb27SDimitry Andric           "The upper and lower limits cannot be the same value", &I);
400006c3fb27SDimitry Andric 
40010b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
400206c3fb27SDimitry Andric     Check(!CurRange.isEmptySet() && (IsAbsoluteSymbol || !CurRange.isFullSet()),
40030b57cec5SDimitry Andric           "Range must not be empty!", Range);
40040b57cec5SDimitry Andric     if (i != 0) {
400581ad6265SDimitry Andric       Check(CurRange.intersectWith(LastRange).isEmptySet(),
40060b57cec5SDimitry Andric             "Intervals are overlapping", Range);
400781ad6265SDimitry Andric       Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
40080b57cec5SDimitry Andric             Range);
400981ad6265SDimitry Andric       Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
40100b57cec5SDimitry Andric             Range);
40110b57cec5SDimitry Andric     }
40120b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
40130b57cec5SDimitry Andric   }
40140b57cec5SDimitry Andric   if (NumRanges > 2) {
40150b57cec5SDimitry Andric     APInt FirstLow =
40160b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
40170b57cec5SDimitry Andric     APInt FirstHigh =
40180b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
40190b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
402081ad6265SDimitry Andric     Check(FirstRange.intersectWith(LastRange).isEmptySet(),
40210b57cec5SDimitry Andric           "Intervals are overlapping", Range);
402281ad6265SDimitry Andric     Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
40230b57cec5SDimitry Andric           Range);
40240b57cec5SDimitry Andric   }
40250b57cec5SDimitry Andric }
40260b57cec5SDimitry Andric 
402706c3fb27SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
402806c3fb27SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
402906c3fb27SDimitry Andric          "precondition violation");
403006c3fb27SDimitry Andric   verifyRangeMetadata(I, Range, Ty, false);
403106c3fb27SDimitry Andric }
403206c3fb27SDimitry Andric 
40330b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
40340b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
403581ad6265SDimitry Andric   Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
403681ad6265SDimitry Andric   Check(!(Size & (Size - 1)),
40370b57cec5SDimitry Andric         "atomic memory access' operand must have a power-of-two size", Ty, I);
40380b57cec5SDimitry Andric }
40390b57cec5SDimitry Andric 
40400b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
40410b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
404281ad6265SDimitry Andric   Check(PTy, "Load operand must be a pointer.", &LI);
40430b57cec5SDimitry Andric   Type *ElTy = LI.getType();
40440eae32dcSDimitry Andric   if (MaybeAlign A = LI.getAlign()) {
404581ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
40460b57cec5SDimitry Andric           "huge alignment values are unsupported", &LI);
40470eae32dcSDimitry Andric   }
404881ad6265SDimitry Andric   Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
40490b57cec5SDimitry Andric   if (LI.isAtomic()) {
405081ad6265SDimitry Andric     Check(LI.getOrdering() != AtomicOrdering::Release &&
40510b57cec5SDimitry Andric               LI.getOrdering() != AtomicOrdering::AcquireRelease,
40520b57cec5SDimitry Andric           "Load cannot have Release ordering", &LI);
405381ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
40540b57cec5SDimitry Andric           "atomic load operand must have integer, pointer, or floating point "
40550b57cec5SDimitry Andric           "type!",
40560b57cec5SDimitry Andric           ElTy, &LI);
40570b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
40580b57cec5SDimitry Andric   } else {
405981ad6265SDimitry Andric     Check(LI.getSyncScopeID() == SyncScope::System,
40600b57cec5SDimitry Andric           "Non-atomic load cannot have SynchronizationScope specified", &LI);
40610b57cec5SDimitry Andric   }
40620b57cec5SDimitry Andric 
40630b57cec5SDimitry Andric   visitInstruction(LI);
40640b57cec5SDimitry Andric }
40650b57cec5SDimitry Andric 
40660b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
40670b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
406881ad6265SDimitry Andric   Check(PTy, "Store operand must be a pointer.", &SI);
4069fe6060f1SDimitry Andric   Type *ElTy = SI.getOperand(0)->getType();
40700eae32dcSDimitry Andric   if (MaybeAlign A = SI.getAlign()) {
407181ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
40720b57cec5SDimitry Andric           "huge alignment values are unsupported", &SI);
40730eae32dcSDimitry Andric   }
407481ad6265SDimitry Andric   Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
40750b57cec5SDimitry Andric   if (SI.isAtomic()) {
407681ad6265SDimitry Andric     Check(SI.getOrdering() != AtomicOrdering::Acquire &&
40770b57cec5SDimitry Andric               SI.getOrdering() != AtomicOrdering::AcquireRelease,
40780b57cec5SDimitry Andric           "Store cannot have Acquire ordering", &SI);
407981ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
40800b57cec5SDimitry Andric           "atomic store operand must have integer, pointer, or floating point "
40810b57cec5SDimitry Andric           "type!",
40820b57cec5SDimitry Andric           ElTy, &SI);
40830b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
40840b57cec5SDimitry Andric   } else {
408581ad6265SDimitry Andric     Check(SI.getSyncScopeID() == SyncScope::System,
40860b57cec5SDimitry Andric           "Non-atomic store cannot have SynchronizationScope specified", &SI);
40870b57cec5SDimitry Andric   }
40880b57cec5SDimitry Andric   visitInstruction(SI);
40890b57cec5SDimitry Andric }
40900b57cec5SDimitry Andric 
40910b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
40920b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
40930b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
4094fe6060f1SDimitry Andric   for (const auto &I : llvm::enumerate(Call.args())) {
4095fe6060f1SDimitry Andric     if (I.value() == SwiftErrorVal) {
409681ad6265SDimitry Andric       Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
40970b57cec5SDimitry Andric             "swifterror value when used in a callsite should be marked "
40980b57cec5SDimitry Andric             "with swifterror attribute",
40990b57cec5SDimitry Andric             SwiftErrorVal, Call);
41000b57cec5SDimitry Andric     }
41010b57cec5SDimitry Andric   }
41020b57cec5SDimitry Andric }
41030b57cec5SDimitry Andric 
41040b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
41050b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
41060b57cec5SDimitry Andric   // a swifterror argument.
41070b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
410881ad6265SDimitry Andric     Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
41090b57cec5SDimitry Andric               isa<InvokeInst>(U),
41100b57cec5SDimitry Andric           "swifterror value can only be loaded and stored from, or "
41110b57cec5SDimitry Andric           "as a swifterror argument!",
41120b57cec5SDimitry Andric           SwiftErrorVal, U);
41130b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
41140b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
411581ad6265SDimitry Andric       Check(StoreI->getOperand(1) == SwiftErrorVal,
41160b57cec5SDimitry Andric             "swifterror value should be the second operand when used "
411781ad6265SDimitry Andric             "by stores",
411881ad6265SDimitry Andric             SwiftErrorVal, U);
41190b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
41200b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
41210b57cec5SDimitry Andric   }
41220b57cec5SDimitry Andric }
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
41250b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
412681ad6265SDimitry Andric   Check(AI.getAllocatedType()->isSized(&Visited),
41270b57cec5SDimitry Andric         "Cannot allocate unsized type", &AI);
412881ad6265SDimitry Andric   Check(AI.getArraySize()->getType()->isIntegerTy(),
41290b57cec5SDimitry Andric         "Alloca array size must have integer type", &AI);
41300eae32dcSDimitry Andric   if (MaybeAlign A = AI.getAlign()) {
413181ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
41320b57cec5SDimitry Andric           "huge alignment values are unsupported", &AI);
41330eae32dcSDimitry Andric   }
41340b57cec5SDimitry Andric 
41350b57cec5SDimitry Andric   if (AI.isSwiftError()) {
413681ad6265SDimitry Andric     Check(AI.getAllocatedType()->isPointerTy(),
413781ad6265SDimitry Andric           "swifterror alloca must have pointer type", &AI);
413881ad6265SDimitry Andric     Check(!AI.isArrayAllocation(),
413981ad6265SDimitry Andric           "swifterror alloca must not be array allocation", &AI);
41400b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
41410b57cec5SDimitry Andric   }
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric   visitInstruction(AI);
41440b57cec5SDimitry Andric }
41450b57cec5SDimitry Andric 
41460b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4147fe6060f1SDimitry Andric   Type *ElTy = CXI.getOperand(1)->getType();
414881ad6265SDimitry Andric   Check(ElTy->isIntOrPtrTy(),
41490b57cec5SDimitry Andric         "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
41500b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
41510b57cec5SDimitry Andric   visitInstruction(CXI);
41520b57cec5SDimitry Andric }
41530b57cec5SDimitry Andric 
41540b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
415581ad6265SDimitry Andric   Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
41560b57cec5SDimitry Andric         "atomicrmw instructions cannot be unordered.", &RMWI);
41570b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
4158fe6060f1SDimitry Andric   Type *ElTy = RMWI.getOperand(1)->getType();
41590b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
416081ad6265SDimitry Andric     Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
416181ad6265SDimitry Andric               ElTy->isPointerTy(),
416281ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
41630b57cec5SDimitry Andric               " operand must have integer or floating point type!",
41640b57cec5SDimitry Andric           &RMWI, ElTy);
41650b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
416681ad6265SDimitry Andric     Check(ElTy->isFloatingPointTy(),
416781ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
41680b57cec5SDimitry Andric               " operand must have floating point type!",
41690b57cec5SDimitry Andric           &RMWI, ElTy);
41700b57cec5SDimitry Andric   } else {
417181ad6265SDimitry Andric     Check(ElTy->isIntegerTy(),
417281ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
41730b57cec5SDimitry Andric               " operand must have integer type!",
41740b57cec5SDimitry Andric           &RMWI, ElTy);
41750b57cec5SDimitry Andric   }
41760b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
417781ad6265SDimitry Andric   Check(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
41780b57cec5SDimitry Andric         "Invalid binary operation!", &RMWI);
41790b57cec5SDimitry Andric   visitInstruction(RMWI);
41800b57cec5SDimitry Andric }
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
41830b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
418481ad6265SDimitry Andric   Check(Ordering == AtomicOrdering::Acquire ||
41850b57cec5SDimitry Andric             Ordering == AtomicOrdering::Release ||
41860b57cec5SDimitry Andric             Ordering == AtomicOrdering::AcquireRelease ||
41870b57cec5SDimitry Andric             Ordering == AtomicOrdering::SequentiallyConsistent,
41880b57cec5SDimitry Andric         "fence instructions may only have acquire, release, acq_rel, or "
41890b57cec5SDimitry Andric         "seq_cst ordering.",
41900b57cec5SDimitry Andric         &FI);
41910b57cec5SDimitry Andric   visitInstruction(FI);
41920b57cec5SDimitry Andric }
41930b57cec5SDimitry Andric 
41940b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
419581ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
41960b57cec5SDimitry Andric                                          EVI.getIndices()) == EVI.getType(),
41970b57cec5SDimitry Andric         "Invalid ExtractValueInst operands!", &EVI);
41980b57cec5SDimitry Andric 
41990b57cec5SDimitry Andric   visitInstruction(EVI);
42000b57cec5SDimitry Andric }
42010b57cec5SDimitry Andric 
42020b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
420381ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
42040b57cec5SDimitry Andric                                          IVI.getIndices()) ==
42050b57cec5SDimitry Andric             IVI.getOperand(1)->getType(),
42060b57cec5SDimitry Andric         "Invalid InsertValueInst operands!", &IVI);
42070b57cec5SDimitry Andric 
42080b57cec5SDimitry Andric   visitInstruction(IVI);
42090b57cec5SDimitry Andric }
42100b57cec5SDimitry Andric 
42110b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
42120b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
42130b57cec5SDimitry Andric     return FPI->getParentPad();
42140b57cec5SDimitry Andric 
42150b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
42160b57cec5SDimitry Andric }
42170b57cec5SDimitry Andric 
42180b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
42190b57cec5SDimitry Andric   assert(I.isEHPad());
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
42220b57cec5SDimitry Andric   Function *F = BB->getParent();
42230b57cec5SDimitry Andric 
422481ad6265SDimitry Andric   Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
42250b57cec5SDimitry Andric 
42260b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
42270b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
42280b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
42290b57cec5SDimitry Andric     // invoke.
42300b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
42310b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
423281ad6265SDimitry Andric       Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
42330b57cec5SDimitry Andric             "Block containing LandingPadInst must be jumped to "
42340b57cec5SDimitry Andric             "only by the unwind edge of an invoke.",
42350b57cec5SDimitry Andric             LPI);
42360b57cec5SDimitry Andric     }
42370b57cec5SDimitry Andric     return;
42380b57cec5SDimitry Andric   }
42390b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
42400b57cec5SDimitry Andric     if (!pred_empty(BB))
424181ad6265SDimitry Andric       Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
42420b57cec5SDimitry Andric             "Block containg CatchPadInst must be jumped to "
42430b57cec5SDimitry Andric             "only by its catchswitch.",
42440b57cec5SDimitry Andric             CPI);
424581ad6265SDimitry Andric     Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
42460b57cec5SDimitry Andric           "Catchswitch cannot unwind to one of its catchpads",
42470b57cec5SDimitry Andric           CPI->getCatchSwitch(), CPI);
42480b57cec5SDimitry Andric     return;
42490b57cec5SDimitry Andric   }
42500b57cec5SDimitry Andric 
42510b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
42520b57cec5SDimitry Andric   // pad relationship.
42530b57cec5SDimitry Andric   Instruction *ToPad = &I;
42540b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
42550b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
42560b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
42570b57cec5SDimitry Andric     Value *FromPad;
42580b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
425981ad6265SDimitry Andric       Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
42600b57cec5SDimitry Andric             "EH pad must be jumped to via an unwind edge", ToPad, II);
42610b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
42620b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
42630b57cec5SDimitry Andric       else
42640b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
42650b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
42660b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
426781ad6265SDimitry Andric       Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
42680b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
42690b57cec5SDimitry Andric       FromPad = CSI;
42700b57cec5SDimitry Andric     } else {
427181ad6265SDimitry Andric       Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
42720b57cec5SDimitry Andric     }
42730b57cec5SDimitry Andric 
42740b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
42750b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
42760b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
427781ad6265SDimitry Andric       Check(FromPad != ToPad,
42780b57cec5SDimitry Andric             "EH pad cannot handle exceptions raised within it", FromPad, TI);
42790b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
42800b57cec5SDimitry Andric         // This is a legal unwind edge.
42810b57cec5SDimitry Andric         break;
42820b57cec5SDimitry Andric       }
428381ad6265SDimitry Andric       Check(!isa<ConstantTokenNone>(FromPad),
42840b57cec5SDimitry Andric             "A single unwind edge may only enter one EH pad", TI);
428581ad6265SDimitry Andric       Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
428681ad6265SDimitry Andric             FromPad);
428704eeddc0SDimitry Andric 
428804eeddc0SDimitry Andric       // This will be diagnosed on the corresponding instruction already. We
428904eeddc0SDimitry Andric       // need the extra check here to make sure getParentPad() works.
429081ad6265SDimitry Andric       Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
429104eeddc0SDimitry Andric             "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
42920b57cec5SDimitry Andric     }
42930b57cec5SDimitry Andric   }
42940b57cec5SDimitry Andric }
42950b57cec5SDimitry Andric 
42960b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
42970b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
42980b57cec5SDimitry Andric   // isn't a cleanup.
429981ad6265SDimitry Andric   Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
43000b57cec5SDimitry Andric         "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
43010b57cec5SDimitry Andric 
43020b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
43030b57cec5SDimitry Andric 
43040b57cec5SDimitry Andric   if (!LandingPadResultTy)
43050b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
43060b57cec5SDimitry Andric   else
430781ad6265SDimitry Andric     Check(LandingPadResultTy == LPI.getType(),
43080b57cec5SDimitry Andric           "The landingpad instruction should have a consistent result type "
43090b57cec5SDimitry Andric           "inside a function.",
43100b57cec5SDimitry Andric           &LPI);
43110b57cec5SDimitry Andric 
43120b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
431381ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
43140b57cec5SDimitry Andric         "LandingPadInst needs to be in a function with a personality.", &LPI);
43150b57cec5SDimitry Andric 
43160b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
43170b57cec5SDimitry Andric   // block.
431881ad6265SDimitry Andric   Check(LPI.getParent()->getLandingPadInst() == &LPI,
431981ad6265SDimitry Andric         "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
43200b57cec5SDimitry Andric 
43210b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
43220b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
43230b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
432481ad6265SDimitry Andric       Check(isa<PointerType>(Clause->getType()),
43250b57cec5SDimitry Andric             "Catch operand does not have pointer type!", &LPI);
43260b57cec5SDimitry Andric     } else {
432781ad6265SDimitry Andric       Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
432881ad6265SDimitry Andric       Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
43290b57cec5SDimitry Andric             "Filter operand is not an array of constants!", &LPI);
43300b57cec5SDimitry Andric     }
43310b57cec5SDimitry Andric   }
43320b57cec5SDimitry Andric 
43330b57cec5SDimitry Andric   visitInstruction(LPI);
43340b57cec5SDimitry Andric }
43350b57cec5SDimitry Andric 
43360b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
433781ad6265SDimitry Andric   Check(RI.getFunction()->hasPersonalityFn(),
43380b57cec5SDimitry Andric         "ResumeInst needs to be in a function with a personality.", &RI);
43390b57cec5SDimitry Andric 
43400b57cec5SDimitry Andric   if (!LandingPadResultTy)
43410b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
43420b57cec5SDimitry Andric   else
434381ad6265SDimitry Andric     Check(LandingPadResultTy == RI.getValue()->getType(),
43440b57cec5SDimitry Andric           "The resume instruction should have a consistent result type "
43450b57cec5SDimitry Andric           "inside a function.",
43460b57cec5SDimitry Andric           &RI);
43470b57cec5SDimitry Andric 
43480b57cec5SDimitry Andric   visitTerminator(RI);
43490b57cec5SDimitry Andric }
43500b57cec5SDimitry Andric 
43510b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
43520b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
43530b57cec5SDimitry Andric 
43540b57cec5SDimitry Andric   Function *F = BB->getParent();
435581ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
43560b57cec5SDimitry Andric         "CatchPadInst needs to be in a function with a personality.", &CPI);
43570b57cec5SDimitry Andric 
435881ad6265SDimitry Andric   Check(isa<CatchSwitchInst>(CPI.getParentPad()),
43590b57cec5SDimitry Andric         "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
43600b57cec5SDimitry Andric         CPI.getParentPad());
43610b57cec5SDimitry Andric 
43620b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
43630b57cec5SDimitry Andric   // block.
436481ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
43650b57cec5SDimitry Andric         "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
43660b57cec5SDimitry Andric 
43670b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
43680b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
43690b57cec5SDimitry Andric }
43700b57cec5SDimitry Andric 
43710b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
437281ad6265SDimitry Andric   Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
43730b57cec5SDimitry Andric         "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
43740b57cec5SDimitry Andric         CatchReturn.getOperand(0));
43750b57cec5SDimitry Andric 
43760b57cec5SDimitry Andric   visitTerminator(CatchReturn);
43770b57cec5SDimitry Andric }
43780b57cec5SDimitry Andric 
43790b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
43800b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
43810b57cec5SDimitry Andric 
43820b57cec5SDimitry Andric   Function *F = BB->getParent();
438381ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
43840b57cec5SDimitry Andric         "CleanupPadInst needs to be in a function with a personality.", &CPI);
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
43870b57cec5SDimitry Andric   // block.
438881ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
438981ad6265SDimitry Andric         "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
43900b57cec5SDimitry Andric 
43910b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
439281ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
43930b57cec5SDimitry Andric         "CleanupPadInst has an invalid parent.", &CPI);
43940b57cec5SDimitry Andric 
43950b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
43960b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
43970b57cec5SDimitry Andric }
43980b57cec5SDimitry Andric 
43990b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
44000b57cec5SDimitry Andric   User *FirstUser = nullptr;
44010b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
44020b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
44030b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
44040b57cec5SDimitry Andric 
44050b57cec5SDimitry Andric   while (!Worklist.empty()) {
44060b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
440781ad6265SDimitry Andric     Check(Seen.insert(CurrentPad).second,
44080b57cec5SDimitry Andric           "FuncletPadInst must not be nested within itself", CurrentPad);
44090b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
44100b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
44110b57cec5SDimitry Andric       BasicBlock *UnwindDest;
44120b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
44130b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
44140b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
44150b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
44160b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
44170b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
44180b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
44190b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
44200b57cec5SDimitry Andric           continue;
44210b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
44220b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
44230b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
44240b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
44250b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
44260b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
44270b57cec5SDimitry Andric         // such calls to be annotated nounwind.
44280b57cec5SDimitry Andric         continue;
44290b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
44300b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
44310b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
44320b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
44330b57cec5SDimitry Andric         Worklist.push_back(CPI);
44340b57cec5SDimitry Andric         continue;
44350b57cec5SDimitry Andric       } else {
443681ad6265SDimitry Andric         Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
44370b57cec5SDimitry Andric         continue;
44380b57cec5SDimitry Andric       }
44390b57cec5SDimitry Andric 
44400b57cec5SDimitry Andric       Value *UnwindPad;
44410b57cec5SDimitry Andric       bool ExitsFPI;
44420b57cec5SDimitry Andric       if (UnwindDest) {
44430b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
44440b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
44450b57cec5SDimitry Andric           continue;
44460b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
44470b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
44480b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
44490b57cec5SDimitry Andric           continue;
44500b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
44510b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
44520b57cec5SDimitry Andric         // of them are exited so we can stop searching their
44530b57cec5SDimitry Andric         // children.
44540b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
44550b57cec5SDimitry Andric         ExitsFPI = false;
44560b57cec5SDimitry Andric         do {
44570b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
44580b57cec5SDimitry Andric             ExitsFPI = true;
44590b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
44600b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
44610b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
44620b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
44630b57cec5SDimitry Andric             break;
44640b57cec5SDimitry Andric           }
44650b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
44660b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
44670b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
44680b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
44690b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
44700b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
44710b57cec5SDimitry Andric             break;
44720b57cec5SDimitry Andric           }
44730b57cec5SDimitry Andric           ExitedPad = ExitedParent;
44740b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
44750b57cec5SDimitry Andric       } else {
44760b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
44770b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
44780b57cec5SDimitry Andric         ExitsFPI = true;
44790b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
44800b57cec5SDimitry Andric       }
44810b57cec5SDimitry Andric 
44820b57cec5SDimitry Andric       if (ExitsFPI) {
44830b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
44840b57cec5SDimitry Andric         // such edges.
44850b57cec5SDimitry Andric         if (FirstUser) {
448681ad6265SDimitry Andric           Check(UnwindPad == FirstUnwindPad,
448781ad6265SDimitry Andric                 "Unwind edges out of a funclet "
44880b57cec5SDimitry Andric                 "pad must have the same unwind "
44890b57cec5SDimitry Andric                 "dest",
44900b57cec5SDimitry Andric                 &FPI, U, FirstUser);
44910b57cec5SDimitry Andric         } else {
44920b57cec5SDimitry Andric           FirstUser = U;
44930b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
44940b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
44950b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
44960b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
44970b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
44980b57cec5SDimitry Andric         }
44990b57cec5SDimitry Andric       }
45000b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
45010b57cec5SDimitry Andric       // soon as we know where they unwind to.
45020b57cec5SDimitry Andric       if (CurrentPad != &FPI)
45030b57cec5SDimitry Andric         break;
45040b57cec5SDimitry Andric     }
45050b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
45060b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
45070b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
45080b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
45090b57cec5SDimitry Andric         // all direct uses of FPI.
45100b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
45110b57cec5SDimitry Andric         continue;
45120b57cec5SDimitry Andric       }
45130b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
45140b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
45150b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
45160b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
45170b57cec5SDimitry Andric       // UnresolvedAncestorPad.
45180b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
45190b57cec5SDimitry Andric       while (!Worklist.empty()) {
45200b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
45210b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
45220b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
45230b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
45240b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
45250b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
45260b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
45270b57cec5SDimitry Andric             break;
45280b57cec5SDimitry Andric           }
45290b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
45300b57cec5SDimitry Andric         }
45310b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
45320b57cec5SDimitry Andric         // then the uncle is not yet resolved.
45330b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
45340b57cec5SDimitry Andric           break;
45350b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
45360b57cec5SDimitry Andric         Worklist.pop_back();
45370b57cec5SDimitry Andric       }
45380b57cec5SDimitry Andric     }
45390b57cec5SDimitry Andric   }
45400b57cec5SDimitry Andric 
45410b57cec5SDimitry Andric   if (FirstUnwindPad) {
45420b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
45430b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
45440b57cec5SDimitry Andric       Value *SwitchUnwindPad;
45450b57cec5SDimitry Andric       if (SwitchUnwindDest)
45460b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
45470b57cec5SDimitry Andric       else
45480b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
454981ad6265SDimitry Andric       Check(SwitchUnwindPad == FirstUnwindPad,
45500b57cec5SDimitry Andric             "Unwind edges out of a catch must have the same unwind dest as "
45510b57cec5SDimitry Andric             "the parent catchswitch",
45520b57cec5SDimitry Andric             &FPI, FirstUser, CatchSwitch);
45530b57cec5SDimitry Andric     }
45540b57cec5SDimitry Andric   }
45550b57cec5SDimitry Andric 
45560b57cec5SDimitry Andric   visitInstruction(FPI);
45570b57cec5SDimitry Andric }
45580b57cec5SDimitry Andric 
45590b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
45600b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
45610b57cec5SDimitry Andric 
45620b57cec5SDimitry Andric   Function *F = BB->getParent();
456381ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
45640b57cec5SDimitry Andric         "CatchSwitchInst needs to be in a function with a personality.",
45650b57cec5SDimitry Andric         &CatchSwitch);
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
45680b57cec5SDimitry Andric   // block.
456981ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CatchSwitch,
45700b57cec5SDimitry Andric         "CatchSwitchInst not the first non-PHI instruction in the block.",
45710b57cec5SDimitry Andric         &CatchSwitch);
45720b57cec5SDimitry Andric 
45730b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
457481ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
45750b57cec5SDimitry Andric         "CatchSwitchInst has an invalid parent.", ParentPad);
45760b57cec5SDimitry Andric 
45770b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
45780b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
457981ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
45800b57cec5SDimitry Andric           "CatchSwitchInst must unwind to an EH block which is not a "
45810b57cec5SDimitry Andric           "landingpad.",
45820b57cec5SDimitry Andric           &CatchSwitch);
45830b57cec5SDimitry Andric 
45840b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
45850b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
45860b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
45870b57cec5SDimitry Andric   }
45880b57cec5SDimitry Andric 
458981ad6265SDimitry Andric   Check(CatchSwitch.getNumHandlers() != 0,
45900b57cec5SDimitry Andric         "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
45910b57cec5SDimitry Andric 
45920b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
459381ad6265SDimitry Andric     Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
45940b57cec5SDimitry Andric           "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
45950b57cec5SDimitry Andric   }
45960b57cec5SDimitry Andric 
45970b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
45980b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
45990b57cec5SDimitry Andric }
46000b57cec5SDimitry Andric 
46010b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
460281ad6265SDimitry Andric   Check(isa<CleanupPadInst>(CRI.getOperand(0)),
46030b57cec5SDimitry Andric         "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
46040b57cec5SDimitry Andric         CRI.getOperand(0));
46050b57cec5SDimitry Andric 
46060b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
46070b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
460881ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
46090b57cec5SDimitry Andric           "CleanupReturnInst must unwind to an EH block which is not a "
46100b57cec5SDimitry Andric           "landingpad.",
46110b57cec5SDimitry Andric           &CRI);
46120b57cec5SDimitry Andric   }
46130b57cec5SDimitry Andric 
46140b57cec5SDimitry Andric   visitTerminator(CRI);
46150b57cec5SDimitry Andric }
46160b57cec5SDimitry Andric 
46170b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
46180b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
46190b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
46200b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
46210b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
46220b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
46230b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
46240b57cec5SDimitry Andric       return;
46250b57cec5SDimitry Andric   }
46260b57cec5SDimitry Andric 
46270b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
46280b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
46290b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
46300b57cec5SDimitry Andric   //
46310b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
46320b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
46330b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
46340b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
46350b57cec5SDimitry Andric     return;
46360b57cec5SDimitry Andric 
46370b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
463881ad6265SDimitry Andric   Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
46390b57cec5SDimitry Andric }
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
464281ad6265SDimitry Andric   Check(I.getType()->isPointerTy(),
464381ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
464481ad6265SDimitry Andric         "apply only to pointer types",
464581ad6265SDimitry Andric         &I);
464681ad6265SDimitry Andric   Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
46470b57cec5SDimitry Andric         "dereferenceable, dereferenceable_or_null apply only to load"
464881ad6265SDimitry Andric         " and inttoptr instructions, use attributes for calls or invokes",
464981ad6265SDimitry Andric         &I);
465081ad6265SDimitry Andric   Check(MD->getNumOperands() == 1,
465181ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
465281ad6265SDimitry Andric         "take one operand!",
465381ad6265SDimitry Andric         &I);
46540b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
465581ad6265SDimitry Andric   Check(CI && CI->getType()->isIntegerTy(64),
465681ad6265SDimitry Andric         "dereferenceable, "
465781ad6265SDimitry Andric         "dereferenceable_or_null metadata value must be an i64!",
465881ad6265SDimitry Andric         &I);
46590b57cec5SDimitry Andric }
46600b57cec5SDimitry Andric 
46618bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
466281ad6265SDimitry Andric   Check(MD->getNumOperands() >= 2,
46638bcb0991SDimitry Andric         "!prof annotations should have no less than 2 operands", MD);
46648bcb0991SDimitry Andric 
46658bcb0991SDimitry Andric   // Check first operand.
466681ad6265SDimitry Andric   Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
466781ad6265SDimitry Andric   Check(isa<MDString>(MD->getOperand(0)),
46688bcb0991SDimitry Andric         "expected string with name of the !prof annotation", MD);
46698bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
46708bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
46718bcb0991SDimitry Andric 
46728bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
46738bcb0991SDimitry Andric   if (ProfName.equals("branch_weights")) {
46745ffd83dbSDimitry Andric     if (isa<InvokeInst>(&I)) {
467581ad6265SDimitry Andric       Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
46765ffd83dbSDimitry Andric             "Wrong number of InvokeInst branch_weights operands", MD);
46775ffd83dbSDimitry Andric     } else {
46788bcb0991SDimitry Andric       unsigned ExpectedNumOperands = 0;
46798bcb0991SDimitry Andric       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
46808bcb0991SDimitry Andric         ExpectedNumOperands = BI->getNumSuccessors();
46818bcb0991SDimitry Andric       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
46828bcb0991SDimitry Andric         ExpectedNumOperands = SI->getNumSuccessors();
46835ffd83dbSDimitry Andric       else if (isa<CallInst>(&I))
46848bcb0991SDimitry Andric         ExpectedNumOperands = 1;
46858bcb0991SDimitry Andric       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
46868bcb0991SDimitry Andric         ExpectedNumOperands = IBI->getNumDestinations();
46878bcb0991SDimitry Andric       else if (isa<SelectInst>(&I))
46888bcb0991SDimitry Andric         ExpectedNumOperands = 2;
4689bdd1243dSDimitry Andric       else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
4690bdd1243dSDimitry Andric         ExpectedNumOperands = CI->getNumSuccessors();
46918bcb0991SDimitry Andric       else
46928bcb0991SDimitry Andric         CheckFailed("!prof branch_weights are not allowed for this instruction",
46938bcb0991SDimitry Andric                     MD);
46948bcb0991SDimitry Andric 
469581ad6265SDimitry Andric       Check(MD->getNumOperands() == 1 + ExpectedNumOperands,
46968bcb0991SDimitry Andric             "Wrong number of operands", MD);
46975ffd83dbSDimitry Andric     }
46988bcb0991SDimitry Andric     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
46998bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
470081ad6265SDimitry Andric       Check(MDO, "second operand should not be null", MD);
470181ad6265SDimitry Andric       Check(mdconst::dyn_extract<ConstantInt>(MDO),
47028bcb0991SDimitry Andric             "!prof brunch_weights operand is not a const int");
47038bcb0991SDimitry Andric     }
47048bcb0991SDimitry Andric   }
47058bcb0991SDimitry Andric }
47068bcb0991SDimitry Andric 
4707bdd1243dSDimitry Andric void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
4708bdd1243dSDimitry Andric   assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
4709bdd1243dSDimitry Andric   bool ExpectedInstTy =
4710bdd1243dSDimitry Andric       isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
4711bdd1243dSDimitry Andric   CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
4712bdd1243dSDimitry Andric           I, MD);
4713bdd1243dSDimitry Andric   // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4714bdd1243dSDimitry Andric   // only be found as DbgAssignIntrinsic operands.
4715bdd1243dSDimitry Andric   if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
4716bdd1243dSDimitry Andric     for (auto *User : AsValue->users()) {
4717bdd1243dSDimitry Andric       CheckDI(isa<DbgAssignIntrinsic>(User),
4718bdd1243dSDimitry Andric               "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4719bdd1243dSDimitry Andric               MD, User);
4720bdd1243dSDimitry Andric       // All of the dbg.assign intrinsics should be in the same function as I.
4721bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
4722bdd1243dSDimitry Andric         CheckDI(DAI->getFunction() == I.getFunction(),
4723bdd1243dSDimitry Andric                 "dbg.assign not in same function as inst", DAI, &I);
4724bdd1243dSDimitry Andric     }
4725bdd1243dSDimitry Andric   }
4726bdd1243dSDimitry Andric }
4727bdd1243dSDimitry Andric 
4728fcaf7f86SDimitry Andric void Verifier::visitCallStackMetadata(MDNode *MD) {
4729fcaf7f86SDimitry Andric   // Call stack metadata should consist of a list of at least 1 constant int
4730fcaf7f86SDimitry Andric   // (representing a hash of the location).
4731fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4732fcaf7f86SDimitry Andric         "call stack metadata should have at least 1 operand", MD);
4733fcaf7f86SDimitry Andric 
4734fcaf7f86SDimitry Andric   for (const auto &Op : MD->operands())
4735fcaf7f86SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
4736fcaf7f86SDimitry Andric           "call stack metadata operand should be constant integer", Op);
4737fcaf7f86SDimitry Andric }
4738fcaf7f86SDimitry Andric 
4739fcaf7f86SDimitry Andric void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
4740fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
4741fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4742fcaf7f86SDimitry Andric         "!memprof annotations should have at least 1 metadata operand "
4743fcaf7f86SDimitry Andric         "(MemInfoBlock)",
4744fcaf7f86SDimitry Andric         MD);
4745fcaf7f86SDimitry Andric 
4746fcaf7f86SDimitry Andric   // Check each MIB
4747fcaf7f86SDimitry Andric   for (auto &MIBOp : MD->operands()) {
4748fcaf7f86SDimitry Andric     MDNode *MIB = dyn_cast<MDNode>(MIBOp);
4749fcaf7f86SDimitry Andric     // The first operand of an MIB should be the call stack metadata.
4750fcaf7f86SDimitry Andric     // There rest of the operands should be MDString tags, and there should be
4751fcaf7f86SDimitry Andric     // at least one.
4752fcaf7f86SDimitry Andric     Check(MIB->getNumOperands() >= 2,
4753fcaf7f86SDimitry Andric           "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
4754fcaf7f86SDimitry Andric 
4755fcaf7f86SDimitry Andric     // Check call stack metadata (first operand).
4756fcaf7f86SDimitry Andric     Check(MIB->getOperand(0) != nullptr,
4757fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should not be null", MIB);
4758fcaf7f86SDimitry Andric     Check(isa<MDNode>(MIB->getOperand(0)),
4759fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should be an MDNode", MIB);
4760fcaf7f86SDimitry Andric     MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
4761fcaf7f86SDimitry Andric     visitCallStackMetadata(StackMD);
4762fcaf7f86SDimitry Andric 
4763fcaf7f86SDimitry Andric     // Check that remaining operands are MDString.
4764bdd1243dSDimitry Andric     Check(llvm::all_of(llvm::drop_begin(MIB->operands()),
4765fcaf7f86SDimitry Andric                        [](const MDOperand &Op) { return isa<MDString>(Op); }),
4766fcaf7f86SDimitry Andric           "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB);
4767fcaf7f86SDimitry Andric   }
4768fcaf7f86SDimitry Andric }
4769fcaf7f86SDimitry Andric 
4770fcaf7f86SDimitry Andric void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
4771fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
4772fcaf7f86SDimitry Andric   // Verify the partial callstack annotated from memprof profiles. This callsite
4773fcaf7f86SDimitry Andric   // is a part of a profiled allocation callstack.
4774fcaf7f86SDimitry Andric   visitCallStackMetadata(MD);
4775fcaf7f86SDimitry Andric }
4776fcaf7f86SDimitry Andric 
4777e8d8bef9SDimitry Andric void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
477881ad6265SDimitry Andric   Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
477981ad6265SDimitry Andric   Check(Annotation->getNumOperands() >= 1,
4780e8d8bef9SDimitry Andric         "annotation must have at least one operand");
478106c3fb27SDimitry Andric   for (const MDOperand &Op : Annotation->operands()) {
478206c3fb27SDimitry Andric     bool TupleOfStrings =
478306c3fb27SDimitry Andric         isa<MDTuple>(Op.get()) &&
478406c3fb27SDimitry Andric         all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
478506c3fb27SDimitry Andric           return isa<MDString>(Annotation.get());
478606c3fb27SDimitry Andric         });
478706c3fb27SDimitry Andric     Check(isa<MDString>(Op.get()) || TupleOfStrings,
478806c3fb27SDimitry Andric           "operands must be a string or a tuple of strings");
478906c3fb27SDimitry Andric   }
4790e8d8bef9SDimitry Andric }
4791e8d8bef9SDimitry Andric 
4792349cc55cSDimitry Andric void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4793349cc55cSDimitry Andric   unsigned NumOps = MD->getNumOperands();
479481ad6265SDimitry Andric   Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4795349cc55cSDimitry Andric         MD);
479681ad6265SDimitry Andric   Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4797349cc55cSDimitry Andric         "first scope operand must be self-referential or string", MD);
4798349cc55cSDimitry Andric   if (NumOps == 3)
479981ad6265SDimitry Andric     Check(isa<MDString>(MD->getOperand(2)),
4800349cc55cSDimitry Andric           "third scope operand must be string (if used)", MD);
4801349cc55cSDimitry Andric 
4802349cc55cSDimitry Andric   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
480381ad6265SDimitry Andric   Check(Domain != nullptr, "second scope operand must be MDNode", MD);
4804349cc55cSDimitry Andric 
4805349cc55cSDimitry Andric   unsigned NumDomainOps = Domain->getNumOperands();
480681ad6265SDimitry Andric   Check(NumDomainOps >= 1 && NumDomainOps <= 2,
4807349cc55cSDimitry Andric         "domain must have one or two operands", Domain);
480881ad6265SDimitry Andric   Check(Domain->getOperand(0).get() == Domain ||
4809349cc55cSDimitry Andric             isa<MDString>(Domain->getOperand(0)),
4810349cc55cSDimitry Andric         "first domain operand must be self-referential or string", Domain);
4811349cc55cSDimitry Andric   if (NumDomainOps == 2)
481281ad6265SDimitry Andric     Check(isa<MDString>(Domain->getOperand(1)),
4813349cc55cSDimitry Andric           "second domain operand must be string (if used)", Domain);
4814349cc55cSDimitry Andric }
4815349cc55cSDimitry Andric 
4816349cc55cSDimitry Andric void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4817349cc55cSDimitry Andric   for (const MDOperand &Op : MD->operands()) {
4818349cc55cSDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
481981ad6265SDimitry Andric     Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4820349cc55cSDimitry Andric     visitAliasScopeMetadata(OpMD);
4821349cc55cSDimitry Andric   }
4822349cc55cSDimitry Andric }
4823349cc55cSDimitry Andric 
482481ad6265SDimitry Andric void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
482581ad6265SDimitry Andric   auto IsValidAccessScope = [](const MDNode *MD) {
482681ad6265SDimitry Andric     return MD->getNumOperands() == 0 && MD->isDistinct();
482781ad6265SDimitry Andric   };
482881ad6265SDimitry Andric 
482981ad6265SDimitry Andric   // It must be either an access scope itself...
483081ad6265SDimitry Andric   if (IsValidAccessScope(MD))
483181ad6265SDimitry Andric     return;
483281ad6265SDimitry Andric 
483381ad6265SDimitry Andric   // ...or a list of access scopes.
483481ad6265SDimitry Andric   for (const MDOperand &Op : MD->operands()) {
483581ad6265SDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
483681ad6265SDimitry Andric     Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
483781ad6265SDimitry Andric     Check(IsValidAccessScope(OpMD),
483881ad6265SDimitry Andric           "Access scope list contains invalid access scope", MD);
483981ad6265SDimitry Andric   }
484081ad6265SDimitry Andric }
484181ad6265SDimitry Andric 
48420b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
48430b57cec5SDimitry Andric ///
48440b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
48450b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
484681ad6265SDimitry Andric   Check(BB, "Instruction not embedded in basic block!", &I);
48470b57cec5SDimitry Andric 
48480b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
48490b57cec5SDimitry Andric     for (User *U : I.users()) {
485081ad6265SDimitry Andric       Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
48510b57cec5SDimitry Andric             "Only PHI nodes may reference their own value!", &I);
48520b57cec5SDimitry Andric     }
48530b57cec5SDimitry Andric   }
48540b57cec5SDimitry Andric 
48550b57cec5SDimitry Andric   // Check that void typed values don't have names
485681ad6265SDimitry Andric   Check(!I.getType()->isVoidTy() || !I.hasName(),
48570b57cec5SDimitry Andric         "Instruction has a name, but provides a void value!", &I);
48580b57cec5SDimitry Andric 
48590b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
48600b57cec5SDimitry Andric   // value type.
486181ad6265SDimitry Andric   Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
48620b57cec5SDimitry Andric         "Instruction returns a non-scalar type!", &I);
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
48650b57cec5SDimitry Andric   // checked against the callee type.
486681ad6265SDimitry Andric   Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
48670b57cec5SDimitry Andric         "Invalid use of metadata!", &I);
48680b57cec5SDimitry Andric 
48690b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
48700b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
48710b57cec5SDimitry Andric   // instruction, it is an error!
48720b57cec5SDimitry Andric   for (Use &U : I.uses()) {
48730b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
487481ad6265SDimitry Andric       Check(Used->getParent() != nullptr,
48750b57cec5SDimitry Andric             "Instruction referencing"
48760b57cec5SDimitry Andric             " instruction not embedded in a basic block!",
48770b57cec5SDimitry Andric             &I, Used);
48780b57cec5SDimitry Andric     else {
48790b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
48800b57cec5SDimitry Andric       return;
48810b57cec5SDimitry Andric     }
48820b57cec5SDimitry Andric   }
48830b57cec5SDimitry Andric 
48840b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
48850b57cec5SDimitry Andric   // call.
48860b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
48870b57cec5SDimitry Andric 
48880b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
488981ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
48920b57cec5SDimitry Andric     // instructions.
48930b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
489481ad6265SDimitry Andric       Check(false, "Instruction operands must be first-class values!", &I);
48950b57cec5SDimitry Andric     }
48960b57cec5SDimitry Andric 
48970b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4898349cc55cSDimitry Andric       // This code checks whether the function is used as the operand of a
4899349cc55cSDimitry Andric       // clang_arc_attachedcall operand bundle.
4900349cc55cSDimitry Andric       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4901349cc55cSDimitry Andric                                       int Idx) {
4902349cc55cSDimitry Andric         return CBI && CBI->isOperandBundleOfType(
4903349cc55cSDimitry Andric                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4904349cc55cSDimitry Andric       };
4905349cc55cSDimitry Andric 
49060b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
4907349cc55cSDimitry Andric       // taken. Ignore cases where the address of the intrinsic function is used
4908349cc55cSDimitry Andric       // as the argument of operand bundle "clang.arc.attachedcall" as those
4909349cc55cSDimitry Andric       // cases are handled in verifyAttachedCallBundle.
491081ad6265SDimitry Andric       Check((!F->isIntrinsic() ||
4911349cc55cSDimitry Andric              (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4912349cc55cSDimitry Andric              IsAttachedCallOperand(F, CBI, i)),
49130b57cec5SDimitry Andric             "Cannot take the address of an intrinsic!", &I);
491481ad6265SDimitry Andric       Check(!F->isIntrinsic() || isa<CallInst>(I) ||
49150b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::donothing ||
4916fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4917fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_end ||
4918fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4919fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
49200b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_resume ||
49210b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_destroy ||
492281ad6265SDimitry Andric                 F->getIntrinsicID() ==
492381ad6265SDimitry Andric                     Intrinsic::experimental_patchpoint_void ||
49240b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
49250b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4926349cc55cSDimitry Andric                 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4927349cc55cSDimitry Andric                 IsAttachedCallOperand(F, CBI, i),
49280b57cec5SDimitry Andric             "Cannot invoke an intrinsic other than donothing, patchpoint, "
4929349cc55cSDimitry Andric             "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
49300b57cec5SDimitry Andric             &I);
493181ad6265SDimitry Andric       Check(F->getParent() == &M, "Referencing function in another module!", &I,
493281ad6265SDimitry Andric             &M, F, F->getParent());
49330b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
493481ad6265SDimitry Andric       Check(OpBB->getParent() == BB->getParent(),
49350b57cec5SDimitry Andric             "Referring to a basic block in another function!", &I);
49360b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
493781ad6265SDimitry Andric       Check(OpArg->getParent() == BB->getParent(),
49380b57cec5SDimitry Andric             "Referring to an argument in another function!", &I);
49390b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
494081ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!", &I,
49410b57cec5SDimitry Andric             &M, GV, GV->getParent());
49420b57cec5SDimitry Andric     } else if (isa<Instruction>(I.getOperand(i))) {
49430b57cec5SDimitry Andric       verifyDominatesUse(I, i);
49440b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
494581ad6265SDimitry Andric       Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
49460b57cec5SDimitry Andric             "Cannot take the address of an inline asm!", &I);
49470b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4948fe6060f1SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy()) {
49490b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
4950fe6060f1SDimitry Andric         // illegal bitcast.
49510b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
49520b57cec5SDimitry Andric       }
49530b57cec5SDimitry Andric     }
49540b57cec5SDimitry Andric   }
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
495781ad6265SDimitry Andric     Check(I.getType()->isFPOrFPVectorTy(),
49580b57cec5SDimitry Andric           "fpmath requires a floating point result!", &I);
495981ad6265SDimitry Andric     Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
49600b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
49610b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
49620b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
496381ad6265SDimitry Andric       Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
49640b57cec5SDimitry Andric             "fpmath accuracy must have float type", &I);
496581ad6265SDimitry Andric       Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
49660b57cec5SDimitry Andric             "fpmath accuracy not a positive number!", &I);
49670b57cec5SDimitry Andric     } else {
496881ad6265SDimitry Andric       Check(false, "invalid fpmath accuracy!", &I);
49690b57cec5SDimitry Andric     }
49700b57cec5SDimitry Andric   }
49710b57cec5SDimitry Andric 
49720b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
497381ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
49740b57cec5SDimitry Andric           "Ranges are only for loads, calls and invokes!", &I);
49750b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
49760b57cec5SDimitry Andric   }
49770b57cec5SDimitry Andric 
4978349cc55cSDimitry Andric   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
497981ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<StoreInst>(I),
4980349cc55cSDimitry Andric           "invariant.group metadata is only for loads and stores", &I);
4981349cc55cSDimitry Andric   }
4982349cc55cSDimitry Andric 
4983bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
498481ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
49850b57cec5SDimitry Andric           &I);
498681ad6265SDimitry Andric     Check(isa<LoadInst>(I),
49870b57cec5SDimitry Andric           "nonnull applies only to load instructions, use attributes"
49880b57cec5SDimitry Andric           " for calls or invokes",
49890b57cec5SDimitry Andric           &I);
4990bdd1243dSDimitry Andric     Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
49910b57cec5SDimitry Andric   }
49920b57cec5SDimitry Andric 
49930b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
49940b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
49970b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
50000b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
50010b57cec5SDimitry Andric 
5002349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
5003349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
5004349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
5005349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
5006349cc55cSDimitry Andric 
500781ad6265SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
500881ad6265SDimitry Andric     visitAccessGroupMetadata(MD);
500981ad6265SDimitry Andric 
50100b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
501181ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "align applies only to pointer types",
50120b57cec5SDimitry Andric           &I);
501381ad6265SDimitry Andric     Check(isa<LoadInst>(I),
501481ad6265SDimitry Andric           "align applies only to load instructions, "
501581ad6265SDimitry Andric           "use attributes for calls or invokes",
501681ad6265SDimitry Andric           &I);
501781ad6265SDimitry Andric     Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
50180b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
501981ad6265SDimitry Andric     Check(CI && CI->getType()->isIntegerTy(64),
50200b57cec5SDimitry Andric           "align metadata value must be an i64!", &I);
50210b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
502281ad6265SDimitry Andric     Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
502381ad6265SDimitry Andric           &I);
502481ad6265SDimitry Andric     Check(Align <= Value::MaximumAlignment,
50250b57cec5SDimitry Andric           "alignment is larger that implementation defined limit", &I);
50260b57cec5SDimitry Andric   }
50270b57cec5SDimitry Andric 
50288bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
50298bcb0991SDimitry Andric     visitProfMetadata(I, MD);
50308bcb0991SDimitry Andric 
5031fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
5032fcaf7f86SDimitry Andric     visitMemProfMetadata(I, MD);
5033fcaf7f86SDimitry Andric 
5034fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
5035fcaf7f86SDimitry Andric     visitCallsiteMetadata(I, MD);
5036fcaf7f86SDimitry Andric 
5037bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
5038bdd1243dSDimitry Andric     visitDIAssignIDMetadata(I, MD);
5039bdd1243dSDimitry Andric 
5040e8d8bef9SDimitry Andric   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
5041e8d8bef9SDimitry Andric     visitAnnotationMetadata(Annotation);
5042e8d8bef9SDimitry Andric 
50430b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
504481ad6265SDimitry Andric     CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
50455ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::Yes);
50460b57cec5SDimitry Andric   }
50470b57cec5SDimitry Andric 
50488bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
50490b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
50508bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
50518bcb0991SDimitry Andric   }
50520b57cec5SDimitry Andric 
50535ffd83dbSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
50545ffd83dbSDimitry Andric   I.getAllMetadata(MDs);
50555ffd83dbSDimitry Andric   for (auto Attachment : MDs) {
50565ffd83dbSDimitry Andric     unsigned Kind = Attachment.first;
50575ffd83dbSDimitry Andric     auto AllowLocs =
50585ffd83dbSDimitry Andric         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
50595ffd83dbSDimitry Andric             ? AreDebugLocsAllowed::Yes
50605ffd83dbSDimitry Andric             : AreDebugLocsAllowed::No;
50615ffd83dbSDimitry Andric     visitMDNode(*Attachment.second, AllowLocs);
50625ffd83dbSDimitry Andric   }
50635ffd83dbSDimitry Andric 
50640b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
50650b57cec5SDimitry Andric }
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
50680b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
50690b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
507081ad6265SDimitry Andric   Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
50710b57cec5SDimitry Andric         IF);
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
50740b57cec5SDimitry Andric   // describe.
50750b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
50760b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
50770b57cec5SDimitry Andric 
50780b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
50790b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
50800b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
50810b57cec5SDimitry Andric 
50820b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
50830b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
50840b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
50850b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
508681ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
50870b57cec5SDimitry Andric         "Intrinsic has incorrect return type!", IF);
508881ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
50890b57cec5SDimitry Andric         "Intrinsic has incorrect argument type!", IF);
50900b57cec5SDimitry Andric 
50910b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
50920b57cec5SDimitry Andric   if (IsVarArg)
509381ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
50940b57cec5SDimitry Andric           "Intrinsic was not defined with variable arguments!", IF);
50950b57cec5SDimitry Andric   else
509681ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
50970b57cec5SDimitry Andric           "Callsite was not defined with variable arguments!", IF);
50980b57cec5SDimitry Andric 
50990b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
510081ad6265SDimitry Andric   Check(TableRef.empty(), "Intrinsic has too few arguments!", IF);
51010b57cec5SDimitry Andric 
51020b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
51030b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
51040b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
51050b57cec5SDimitry Andric   // the name.
5106fe6060f1SDimitry Andric   const std::string ExpectedName =
5107fe6060f1SDimitry Andric       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
510881ad6265SDimitry Andric   Check(ExpectedName == IF->getName(),
51090b57cec5SDimitry Andric         "Intrinsic name not mangled correctly for type arguments! "
51100b57cec5SDimitry Andric         "Should be: " +
51110b57cec5SDimitry Andric             ExpectedName,
51120b57cec5SDimitry Andric         IF);
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
51150b57cec5SDimitry Andric   // or are local to *this* function.
5116fe6060f1SDimitry Andric   for (Value *V : Call.args()) {
51170b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
51180b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
5119fe6060f1SDimitry Andric     if (auto *Const = dyn_cast<Constant>(V))
512081ad6265SDimitry Andric       Check(!Const->getType()->isX86_AMXTy(),
5121fe6060f1SDimitry Andric             "const x86_amx is not allowed in argument!");
5122fe6060f1SDimitry Andric   }
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric   switch (ID) {
51250b57cec5SDimitry Andric   default:
51260b57cec5SDimitry Andric     break;
51275ffd83dbSDimitry Andric   case Intrinsic::assume: {
51285ffd83dbSDimitry Andric     for (auto &Elem : Call.bundle_op_infos()) {
5129bdd1243dSDimitry Andric       unsigned ArgCount = Elem.End - Elem.Begin;
5130bdd1243dSDimitry Andric       // Separate storage assumptions are special insofar as they're the only
5131bdd1243dSDimitry Andric       // operand bundles allowed on assumes that aren't parameter attributes.
5132bdd1243dSDimitry Andric       if (Elem.Tag->getKey() == "separate_storage") {
5133bdd1243dSDimitry Andric         Check(ArgCount == 2,
5134bdd1243dSDimitry Andric               "separate_storage assumptions should have 2 arguments", Call);
5135bdd1243dSDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
5136bdd1243dSDimitry Andric                   Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
5137bdd1243dSDimitry Andric               "arguments to separate_storage assumptions should be pointers",
5138bdd1243dSDimitry Andric               Call);
5139bdd1243dSDimitry Andric         return;
5140bdd1243dSDimitry Andric       }
514181ad6265SDimitry Andric       Check(Elem.Tag->getKey() == "ignore" ||
51425ffd83dbSDimitry Andric                 Attribute::isExistingAttribute(Elem.Tag->getKey()),
5143349cc55cSDimitry Andric             "tags must be valid attribute names", Call);
51445ffd83dbSDimitry Andric       Attribute::AttrKind Kind =
51455ffd83dbSDimitry Andric           Attribute::getAttrKindFromName(Elem.Tag->getKey());
5146e8d8bef9SDimitry Andric       if (Kind == Attribute::Alignment) {
514781ad6265SDimitry Andric         Check(ArgCount <= 3 && ArgCount >= 2,
5148349cc55cSDimitry Andric               "alignment assumptions should have 2 or 3 arguments", Call);
514981ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
5150349cc55cSDimitry Andric               "first argument should be a pointer", Call);
515181ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
5152349cc55cSDimitry Andric               "second argument should be an integer", Call);
5153e8d8bef9SDimitry Andric         if (ArgCount == 3)
515481ad6265SDimitry Andric           Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
5155349cc55cSDimitry Andric                 "third argument should be an integer if present", Call);
5156e8d8bef9SDimitry Andric         return;
5157e8d8bef9SDimitry Andric       }
515881ad6265SDimitry Andric       Check(ArgCount <= 2, "too many arguments", Call);
51595ffd83dbSDimitry Andric       if (Kind == Attribute::None)
51605ffd83dbSDimitry Andric         break;
5161fe6060f1SDimitry Andric       if (Attribute::isIntAttrKind(Kind)) {
516281ad6265SDimitry Andric         Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
516381ad6265SDimitry Andric         Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
5164349cc55cSDimitry Andric               "the second argument should be a constant integral value", Call);
5165fe6060f1SDimitry Andric       } else if (Attribute::canUseAsParamAttr(Kind)) {
516681ad6265SDimitry Andric         Check((ArgCount) == 1, "this attribute should have one argument", Call);
5167fe6060f1SDimitry Andric       } else if (Attribute::canUseAsFnAttr(Kind)) {
516881ad6265SDimitry Andric         Check((ArgCount) == 0, "this attribute has no argument", Call);
51695ffd83dbSDimitry Andric       }
51705ffd83dbSDimitry Andric     }
51715ffd83dbSDimitry Andric     break;
51725ffd83dbSDimitry Andric   }
51730b57cec5SDimitry Andric   case Intrinsic::coro_id: {
51740b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
51750b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
51760b57cec5SDimitry Andric       break;
51770b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
517881ad6265SDimitry Andric     Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
5179fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to an initialized "
51800b57cec5SDimitry Andric           "constant");
51810b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
518281ad6265SDimitry Andric     Check(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
5183fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to either a struct or "
51840b57cec5SDimitry Andric           "an array");
51850b57cec5SDimitry Andric     break;
51860b57cec5SDimitry Andric   }
5187bdd1243dSDimitry Andric   case Intrinsic::is_fpclass: {
5188bdd1243dSDimitry Andric     const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
518906c3fb27SDimitry Andric     Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
5190bdd1243dSDimitry Andric           "unsupported bits for llvm.is.fpclass test mask");
5191bdd1243dSDimitry Andric     break;
5192bdd1243dSDimitry Andric   }
519381ad6265SDimitry Andric   case Intrinsic::fptrunc_round: {
519481ad6265SDimitry Andric     // Check the rounding mode
519581ad6265SDimitry Andric     Metadata *MD = nullptr;
519681ad6265SDimitry Andric     auto *MAV = dyn_cast<MetadataAsValue>(Call.getOperand(1));
519781ad6265SDimitry Andric     if (MAV)
519881ad6265SDimitry Andric       MD = MAV->getMetadata();
519981ad6265SDimitry Andric 
520081ad6265SDimitry Andric     Check(MD != nullptr, "missing rounding mode argument", Call);
520181ad6265SDimitry Andric 
520281ad6265SDimitry Andric     Check(isa<MDString>(MD),
520381ad6265SDimitry Andric           ("invalid value for llvm.fptrunc.round metadata operand"
520481ad6265SDimitry Andric            " (the operand should be a string)"),
520581ad6265SDimitry Andric           MD);
520681ad6265SDimitry Andric 
5207bdd1243dSDimitry Andric     std::optional<RoundingMode> RoundMode =
520881ad6265SDimitry Andric         convertStrToRoundingMode(cast<MDString>(MD)->getString());
520981ad6265SDimitry Andric     Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
521081ad6265SDimitry Andric           "unsupported rounding mode argument", Call);
521181ad6265SDimitry Andric     break;
521281ad6265SDimitry Andric   }
521381ad6265SDimitry Andric #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
521481ad6265SDimitry Andric #include "llvm/IR/VPIntrinsics.def"
521581ad6265SDimitry Andric     visitVPIntrinsic(cast<VPIntrinsic>(Call));
521681ad6265SDimitry Andric     break;
52175ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
5218480093f4SDimitry Andric   case Intrinsic::INTRINSIC:
5219480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
52200b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
52210b57cec5SDimitry Andric     break;
52220b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
522381ad6265SDimitry Andric     Check(isa<MetadataAsValue>(Call.getArgOperand(0)),
52240b57cec5SDimitry Andric           "invalid llvm.dbg.declare intrinsic call 1", Call);
52250b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
52260b57cec5SDimitry Andric     break;
52270b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
52280b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
52290b57cec5SDimitry Andric     break;
5230bdd1243dSDimitry Andric   case Intrinsic::dbg_assign: // llvm.dbg.assign
5231bdd1243dSDimitry Andric     visitDbgIntrinsic("assign", cast<DbgVariableIntrinsic>(Call));
5232bdd1243dSDimitry Andric     break;
52330b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
52340b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
52350b57cec5SDimitry Andric     break;
52360b57cec5SDimitry Andric   case Intrinsic::memcpy:
52375ffd83dbSDimitry Andric   case Intrinsic::memcpy_inline:
52380b57cec5SDimitry Andric   case Intrinsic::memmove:
523981ad6265SDimitry Andric   case Intrinsic::memset:
524081ad6265SDimitry Andric   case Intrinsic::memset_inline: {
52410b57cec5SDimitry Andric     break;
52420b57cec5SDimitry Andric   }
52430b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
52440b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
52450b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
52460b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
52470b57cec5SDimitry Andric 
52480b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
52490b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
52500b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
525181ad6265SDimitry Andric     Check(ElementSizeVal.isPowerOf2(),
52520b57cec5SDimitry Andric           "element size of the element-wise atomic memory intrinsic "
52530b57cec5SDimitry Andric           "must be a power of 2",
52540b57cec5SDimitry Andric           Call);
52550b57cec5SDimitry Andric 
5256bdd1243dSDimitry Andric     auto IsValidAlignment = [&](MaybeAlign Alignment) {
5257bdd1243dSDimitry Andric       return Alignment && ElementSizeVal.ule(Alignment->value());
52580b57cec5SDimitry Andric     };
5259bdd1243dSDimitry Andric     Check(IsValidAlignment(AMI->getDestAlign()),
52600b57cec5SDimitry Andric           "incorrect alignment of the destination argument", Call);
52610b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
5262bdd1243dSDimitry Andric       Check(IsValidAlignment(AMT->getSourceAlign()),
52630b57cec5SDimitry Andric             "incorrect alignment of the source argument", Call);
52640b57cec5SDimitry Andric     }
52650b57cec5SDimitry Andric     break;
52660b57cec5SDimitry Andric   }
52675ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_setup: {
52685ffd83dbSDimitry Andric     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
526981ad6265SDimitry Andric     Check(NumArgs != nullptr,
52705ffd83dbSDimitry Andric           "llvm.call.preallocated.setup argument must be a constant");
52715ffd83dbSDimitry Andric     bool FoundCall = false;
52725ffd83dbSDimitry Andric     for (User *U : Call.users()) {
52735ffd83dbSDimitry Andric       auto *UseCall = dyn_cast<CallBase>(U);
527481ad6265SDimitry Andric       Check(UseCall != nullptr,
52755ffd83dbSDimitry Andric             "Uses of llvm.call.preallocated.setup must be calls");
52765ffd83dbSDimitry Andric       const Function *Fn = UseCall->getCalledFunction();
52775ffd83dbSDimitry Andric       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
52785ffd83dbSDimitry Andric         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
527981ad6265SDimitry Andric         Check(AllocArgIndex != nullptr,
52805ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be a constant");
52815ffd83dbSDimitry Andric         auto AllocArgIndexInt = AllocArgIndex->getValue();
528281ad6265SDimitry Andric         Check(AllocArgIndexInt.sge(0) &&
52835ffd83dbSDimitry Andric                   AllocArgIndexInt.slt(NumArgs->getValue()),
52845ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be between 0 and "
52855ffd83dbSDimitry Andric               "corresponding "
52865ffd83dbSDimitry Andric               "llvm.call.preallocated.setup's argument count");
52875ffd83dbSDimitry Andric       } else if (Fn && Fn->getIntrinsicID() ==
52885ffd83dbSDimitry Andric                            Intrinsic::call_preallocated_teardown) {
52895ffd83dbSDimitry Andric         // nothing to do
52905ffd83dbSDimitry Andric       } else {
529181ad6265SDimitry Andric         Check(!FoundCall, "Can have at most one call corresponding to a "
52925ffd83dbSDimitry Andric                           "llvm.call.preallocated.setup");
52935ffd83dbSDimitry Andric         FoundCall = true;
52945ffd83dbSDimitry Andric         size_t NumPreallocatedArgs = 0;
5295349cc55cSDimitry Andric         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
52965ffd83dbSDimitry Andric           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
52975ffd83dbSDimitry Andric             ++NumPreallocatedArgs;
52985ffd83dbSDimitry Andric           }
52995ffd83dbSDimitry Andric         }
530081ad6265SDimitry Andric         Check(NumPreallocatedArgs != 0,
53015ffd83dbSDimitry Andric               "cannot use preallocated intrinsics on a call without "
53025ffd83dbSDimitry Andric               "preallocated arguments");
530381ad6265SDimitry Andric         Check(NumArgs->equalsInt(NumPreallocatedArgs),
53045ffd83dbSDimitry Andric               "llvm.call.preallocated.setup arg size must be equal to number "
53055ffd83dbSDimitry Andric               "of preallocated arguments "
53065ffd83dbSDimitry Andric               "at call site",
53075ffd83dbSDimitry Andric               Call, *UseCall);
53085ffd83dbSDimitry Andric         // getOperandBundle() cannot be called if more than one of the operand
53095ffd83dbSDimitry Andric         // bundle exists. There is already a check elsewhere for this, so skip
53105ffd83dbSDimitry Andric         // here if we see more than one.
53115ffd83dbSDimitry Andric         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
53125ffd83dbSDimitry Andric             1) {
53135ffd83dbSDimitry Andric           return;
53145ffd83dbSDimitry Andric         }
53155ffd83dbSDimitry Andric         auto PreallocatedBundle =
53165ffd83dbSDimitry Andric             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
531781ad6265SDimitry Andric         Check(PreallocatedBundle,
53185ffd83dbSDimitry Andric               "Use of llvm.call.preallocated.setup outside intrinsics "
53195ffd83dbSDimitry Andric               "must be in \"preallocated\" operand bundle");
532081ad6265SDimitry Andric         Check(PreallocatedBundle->Inputs.front().get() == &Call,
53215ffd83dbSDimitry Andric               "preallocated bundle must have token from corresponding "
53225ffd83dbSDimitry Andric               "llvm.call.preallocated.setup");
53235ffd83dbSDimitry Andric       }
53245ffd83dbSDimitry Andric     }
53255ffd83dbSDimitry Andric     break;
53265ffd83dbSDimitry Andric   }
53275ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_arg: {
53285ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
532981ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
53305ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
53315ffd83dbSDimitry Andric           "llvm.call.preallocated.arg token argument must be a "
53325ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
533381ad6265SDimitry Andric     Check(Call.hasFnAttr(Attribute::Preallocated),
53345ffd83dbSDimitry Andric           "llvm.call.preallocated.arg must be called with a \"preallocated\" "
53355ffd83dbSDimitry Andric           "call site attribute");
53365ffd83dbSDimitry Andric     break;
53375ffd83dbSDimitry Andric   }
53385ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_teardown: {
53395ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
534081ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
53415ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
53425ffd83dbSDimitry Andric           "llvm.call.preallocated.teardown token argument must be a "
53435ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
53445ffd83dbSDimitry Andric     break;
53455ffd83dbSDimitry Andric   }
53460b57cec5SDimitry Andric   case Intrinsic::gcroot:
53470b57cec5SDimitry Andric   case Intrinsic::gcwrite:
53480b57cec5SDimitry Andric   case Intrinsic::gcread:
53490b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
53500b57cec5SDimitry Andric       AllocaInst *AI =
53510b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
535281ad6265SDimitry Andric       Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
535381ad6265SDimitry Andric       Check(isa<Constant>(Call.getArgOperand(1)),
53540b57cec5SDimitry Andric             "llvm.gcroot parameter #2 must be a constant.", Call);
53550b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
535681ad6265SDimitry Andric         Check(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
53570b57cec5SDimitry Andric               "llvm.gcroot parameter #1 must either be a pointer alloca, "
53580b57cec5SDimitry Andric               "or argument #2 must be a non-null constant.",
53590b57cec5SDimitry Andric               Call);
53600b57cec5SDimitry Andric       }
53610b57cec5SDimitry Andric     }
53620b57cec5SDimitry Andric 
536381ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
53640b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
53650b57cec5SDimitry Andric     break;
53660b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
536781ad6265SDimitry Andric     Check(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
53680b57cec5SDimitry Andric           "llvm.init_trampoline parameter #2 must resolve to a function.",
53690b57cec5SDimitry Andric           Call);
53700b57cec5SDimitry Andric     break;
53710b57cec5SDimitry Andric   case Intrinsic::prefetch:
5372bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5373bdd1243dSDimitry Andric           "rw argument to llvm.prefetch must be 0-1", Call);
5374bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
53755f757f3fSDimitry Andric           "locality argument to llvm.prefetch must be 0-3", Call);
5376bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5377bdd1243dSDimitry Andric           "cache type argument to llvm.prefetch must be 0-1", Call);
53780b57cec5SDimitry Andric     break;
53790b57cec5SDimitry Andric   case Intrinsic::stackprotector:
538081ad6265SDimitry Andric     Check(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
53810b57cec5SDimitry Andric           "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
53820b57cec5SDimitry Andric     break;
53830b57cec5SDimitry Andric   case Intrinsic::localescape: {
53840b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
5385bdd1243dSDimitry Andric     Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
5386bdd1243dSDimitry Andric           Call);
538781ad6265SDimitry Andric     Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
538881ad6265SDimitry Andric           Call);
53890b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
53900b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
53910b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
53920b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
539381ad6265SDimitry Andric       Check(AI && AI->isStaticAlloca(),
53940b57cec5SDimitry Andric             "llvm.localescape only accepts static allocas", Call);
53950b57cec5SDimitry Andric     }
5396349cc55cSDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
53970b57cec5SDimitry Andric     SawFrameEscape = true;
53980b57cec5SDimitry Andric     break;
53990b57cec5SDimitry Andric   }
54000b57cec5SDimitry Andric   case Intrinsic::localrecover: {
54010b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
54020b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
540381ad6265SDimitry Andric     Check(Fn && !Fn->isDeclaration(),
54040b57cec5SDimitry Andric           "llvm.localrecover first "
54050b57cec5SDimitry Andric           "argument must be function defined in this module",
54060b57cec5SDimitry Andric           Call);
54070b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
54080b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
54090b57cec5SDimitry Andric     Entry.second = unsigned(
54100b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
54110b57cec5SDimitry Andric     break;
54120b57cec5SDimitry Andric   }
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
54150b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
541681ad6265SDimitry Andric       Check(!CI->isInlineAsm(),
54170b57cec5SDimitry Andric             "gc.statepoint support for inline assembly unimplemented", CI);
541881ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
54190b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
54200b57cec5SDimitry Andric 
54210b57cec5SDimitry Andric     verifyStatepoint(Call);
54220b57cec5SDimitry Andric     break;
54230b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
542481ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
54250b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
5426bdd1243dSDimitry Andric 
5427bdd1243dSDimitry Andric     auto *Statepoint = Call.getArgOperand(0);
5428bdd1243dSDimitry Andric     if (isa<UndefValue>(Statepoint))
5429bdd1243dSDimitry Andric       break;
5430bdd1243dSDimitry Andric 
54310b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
5432bdd1243dSDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
54330b57cec5SDimitry Andric     const Function *StatepointFn =
54340b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
543581ad6265SDimitry Andric     Check(StatepointFn && StatepointFn->isDeclaration() &&
54360b57cec5SDimitry Andric               StatepointFn->getIntrinsicID() ==
54370b57cec5SDimitry Andric                   Intrinsic::experimental_gc_statepoint,
54380b57cec5SDimitry Andric           "gc.result operand #1 must be from a statepoint", Call,
54390b57cec5SDimitry Andric           Call.getArgOperand(0));
54400b57cec5SDimitry Andric 
544181ad6265SDimitry Andric     // Check that result type matches wrapped callee.
544281ad6265SDimitry Andric     auto *TargetFuncType =
544381ad6265SDimitry Andric         cast<FunctionType>(StatepointCall->getParamElementType(2));
544481ad6265SDimitry Andric     Check(Call.getType() == TargetFuncType->getReturnType(),
54450b57cec5SDimitry Andric           "gc.result result type does not match wrapped callee", Call);
54460b57cec5SDimitry Andric     break;
54470b57cec5SDimitry Andric   }
54480b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
544981ad6265SDimitry Andric     Check(Call.arg_size() == 3, "wrong number of arguments", Call);
54500b57cec5SDimitry Andric 
545181ad6265SDimitry Andric     Check(isa<PointerType>(Call.getType()->getScalarType()),
54520b57cec5SDimitry Andric           "gc.relocate must return a pointer or a vector of pointers", Call);
54530b57cec5SDimitry Andric 
54540b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
54550b57cec5SDimitry Andric 
54560b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
54570b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
54580b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
54590b57cec5SDimitry Andric 
54600b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
54610b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
54620b57cec5SDimitry Andric 
54630b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
54640b57cec5SDimitry Andric       // statepoint terminator
546581ad6265SDimitry Andric       Check(InvokeBB, "safepoints should have unique landingpads",
54660b57cec5SDimitry Andric             LandingPad->getParent());
546781ad6265SDimitry Andric       Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
54680b57cec5SDimitry Andric             InvokeBB);
546981ad6265SDimitry Andric       Check(isa<GCStatepointInst>(InvokeBB->getTerminator()),
54700b57cec5SDimitry Andric             "gc relocate should be linked to a statepoint", InvokeBB);
54710b57cec5SDimitry Andric     } else {
54720b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
54730b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
54740b57cec5SDimitry Andric       // relocates of a call statepoint.
5475fcaf7f86SDimitry Andric       auto *Token = Call.getArgOperand(0);
5476fcaf7f86SDimitry Andric       Check(isa<GCStatepointInst>(Token) || isa<UndefValue>(Token),
54770b57cec5SDimitry Andric             "gc relocate is incorrectly tied to the statepoint", Call, Token);
54780b57cec5SDimitry Andric     }
54790b57cec5SDimitry Andric 
54800b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
5481fcaf7f86SDimitry Andric     const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
54820b57cec5SDimitry Andric 
54830b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
54840b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
548581ad6265SDimitry Andric     Check(isa<ConstantInt>(Base),
54860b57cec5SDimitry Andric           "gc.relocate operand #2 must be integer offset", Call);
54870b57cec5SDimitry Andric 
54880b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
548981ad6265SDimitry Andric     Check(isa<ConstantInt>(Derived),
54900b57cec5SDimitry Andric           "gc.relocate operand #3 must be integer offset", Call);
54910b57cec5SDimitry Andric 
54925ffd83dbSDimitry Andric     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
54935ffd83dbSDimitry Andric     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
54945ffd83dbSDimitry Andric 
54950b57cec5SDimitry Andric     // Check the bounds
5496fcaf7f86SDimitry Andric     if (isa<UndefValue>(StatepointCall))
5497fcaf7f86SDimitry Andric       break;
5498fcaf7f86SDimitry Andric     if (auto Opt = cast<GCStatepointInst>(StatepointCall)
5499fcaf7f86SDimitry Andric                        .getOperandBundle(LLVMContext::OB_gc_live)) {
550081ad6265SDimitry Andric       Check(BaseIndex < Opt->Inputs.size(),
55010b57cec5SDimitry Andric             "gc.relocate: statepoint base index out of bounds", Call);
550281ad6265SDimitry Andric       Check(DerivedIndex < Opt->Inputs.size(),
55035ffd83dbSDimitry Andric             "gc.relocate: statepoint derived index out of bounds", Call);
55045ffd83dbSDimitry Andric     }
55050b57cec5SDimitry Andric 
55060b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
55070b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
55080b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
55090b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
55100b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5511bdd1243dSDimitry Andric     auto *ResultType = Call.getType();
5512bdd1243dSDimitry Andric     auto *DerivedType = Relocate.getDerivedPtr()->getType();
5513bdd1243dSDimitry Andric     auto *BaseType = Relocate.getBasePtr()->getType();
55140b57cec5SDimitry Andric 
5515bdd1243dSDimitry Andric     Check(BaseType->isPtrOrPtrVectorTy(),
5516bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5517bdd1243dSDimitry Andric     Check(DerivedType->isPtrOrPtrVectorTy(),
5518bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5519bdd1243dSDimitry Andric 
552081ad6265SDimitry Andric     Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
55210b57cec5SDimitry Andric           "gc.relocate: vector relocates to vector and pointer to pointer",
55220b57cec5SDimitry Andric           Call);
552381ad6265SDimitry Andric     Check(
55240b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
55250b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
55260b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
55270b57cec5SDimitry Andric         Call);
5528bdd1243dSDimitry Andric 
5529bdd1243dSDimitry Andric     auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
5530bdd1243dSDimitry Andric     Check(GC, "gc.relocate: calling function must have GCStrategy",
5531bdd1243dSDimitry Andric           Call.getFunction());
5532bdd1243dSDimitry Andric     if (GC) {
5533bdd1243dSDimitry Andric       auto isGCPtr = [&GC](Type *PTy) {
5534bdd1243dSDimitry Andric         return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
5535bdd1243dSDimitry Andric       };
5536bdd1243dSDimitry Andric       Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
5537bdd1243dSDimitry Andric       Check(isGCPtr(BaseType),
5538bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5539bdd1243dSDimitry Andric       Check(isGCPtr(DerivedType),
5540bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5541bdd1243dSDimitry Andric     }
55420b57cec5SDimitry Andric     break;
55430b57cec5SDimitry Andric   }
55440b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
55450b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
554681ad6265SDimitry Andric     Check(isa<CatchPadInst>(Call.getArgOperand(0)),
55470b57cec5SDimitry Andric           "eh.exceptionpointer argument must be a catchpad", Call);
55480b57cec5SDimitry Andric     break;
55490b57cec5SDimitry Andric   }
55505ffd83dbSDimitry Andric   case Intrinsic::get_active_lane_mask: {
555181ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(),
555281ad6265SDimitry Andric           "get_active_lane_mask: must return a "
555381ad6265SDimitry Andric           "vector",
555481ad6265SDimitry Andric           Call);
55555ffd83dbSDimitry Andric     auto *ElemTy = Call.getType()->getScalarType();
555681ad6265SDimitry Andric     Check(ElemTy->isIntegerTy(1),
555781ad6265SDimitry Andric           "get_active_lane_mask: element type is not "
555881ad6265SDimitry Andric           "i1",
555981ad6265SDimitry Andric           Call);
55605ffd83dbSDimitry Andric     break;
55615ffd83dbSDimitry Andric   }
556206c3fb27SDimitry Andric   case Intrinsic::experimental_get_vector_length: {
556306c3fb27SDimitry Andric     ConstantInt *VF = cast<ConstantInt>(Call.getArgOperand(1));
556406c3fb27SDimitry Andric     Check(!VF->isNegative() && !VF->isZero(),
556506c3fb27SDimitry Andric           "get_vector_length: VF must be positive", Call);
556606c3fb27SDimitry Andric     break;
556706c3fb27SDimitry Andric   }
55680b57cec5SDimitry Andric   case Intrinsic::masked_load: {
556981ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
55700b57cec5SDimitry Andric           Call);
55710b57cec5SDimitry Andric 
55720b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
55730b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
55740b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
557581ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
55760b57cec5SDimitry Andric           Call);
557781ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
55780b57cec5SDimitry Andric           "masked_load: alignment must be a power of 2", Call);
557981ad6265SDimitry Andric     Check(PassThru->getType() == Call.getType(),
5580fe6060f1SDimitry Andric           "masked_load: pass through and return type must match", Call);
558181ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5582fe6060f1SDimitry Andric               cast<VectorType>(Call.getType())->getElementCount(),
5583fe6060f1SDimitry Andric           "masked_load: vector mask must be same length as return", Call);
55840b57cec5SDimitry Andric     break;
55850b57cec5SDimitry Andric   }
55860b57cec5SDimitry Andric   case Intrinsic::masked_store: {
55870b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
55880b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
55890b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
559081ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
55910b57cec5SDimitry Andric           Call);
559281ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
55930b57cec5SDimitry Andric           "masked_store: alignment must be a power of 2", Call);
559481ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5595fe6060f1SDimitry Andric               cast<VectorType>(Val->getType())->getElementCount(),
5596fe6060f1SDimitry Andric           "masked_store: vector mask must be same length as value", Call);
55970b57cec5SDimitry Andric     break;
55980b57cec5SDimitry Andric   }
55990b57cec5SDimitry Andric 
56005ffd83dbSDimitry Andric   case Intrinsic::masked_gather: {
56015ffd83dbSDimitry Andric     const APInt &Alignment =
56025ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
560381ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
56045ffd83dbSDimitry Andric           "masked_gather: alignment must be 0 or a power of 2", Call);
56055ffd83dbSDimitry Andric     break;
56065ffd83dbSDimitry Andric   }
56075ffd83dbSDimitry Andric   case Intrinsic::masked_scatter: {
56085ffd83dbSDimitry Andric     const APInt &Alignment =
56095ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
561081ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
56115ffd83dbSDimitry Andric           "masked_scatter: alignment must be 0 or a power of 2", Call);
56125ffd83dbSDimitry Andric     break;
56135ffd83dbSDimitry Andric   }
56145ffd83dbSDimitry Andric 
56150b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
561681ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
561781ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
56180b57cec5SDimitry Andric           "experimental_guard must have exactly one "
56190b57cec5SDimitry Andric           "\"deopt\" operand bundle");
56200b57cec5SDimitry Andric     break;
56210b57cec5SDimitry Andric   }
56220b57cec5SDimitry Andric 
56230b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
562481ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
56250b57cec5SDimitry Andric           Call);
562681ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
56270b57cec5SDimitry Andric           "experimental_deoptimize must have exactly one "
56280b57cec5SDimitry Andric           "\"deopt\" operand bundle");
562981ad6265SDimitry Andric     Check(Call.getType() == Call.getFunction()->getReturnType(),
56300b57cec5SDimitry Andric           "experimental_deoptimize return type must match caller return type");
56310b57cec5SDimitry Andric 
56320b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
56330b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
563481ad6265SDimitry Andric       Check(RI,
56350b57cec5SDimitry Andric             "calls to experimental_deoptimize must be followed by a return");
56360b57cec5SDimitry Andric 
56370b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
563881ad6265SDimitry Andric         Check(RI->getReturnValue() == &Call,
56390b57cec5SDimitry Andric               "calls to experimental_deoptimize must be followed by a return "
56400b57cec5SDimitry Andric               "of the value computed by experimental_deoptimize");
56410b57cec5SDimitry Andric     }
56420b57cec5SDimitry Andric 
56430b57cec5SDimitry Andric     break;
56440b57cec5SDimitry Andric   }
5645fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_and:
5646fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_or:
5647fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_xor:
5648fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_add:
5649fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_mul:
5650fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smax:
5651fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smin:
5652fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umax:
5653fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umin: {
5654fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
565581ad6265SDimitry Andric     Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5656fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5657fe6060f1SDimitry Andric     break;
5658fe6060f1SDimitry Andric   }
5659fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmax:
5660fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmin: {
5661fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
566281ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5663fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5664fe6060f1SDimitry Andric     break;
5665fe6060f1SDimitry Andric   }
5666fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fadd:
5667fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmul: {
5668fe6060f1SDimitry Andric     // Unlike the other reductions, the first argument is a start value. The
5669fe6060f1SDimitry Andric     // second argument is the vector to be reduced.
5670fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(1)->getType();
567181ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5672fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
56730b57cec5SDimitry Andric     break;
56740b57cec5SDimitry Andric   }
56750b57cec5SDimitry Andric   case Intrinsic::smul_fix:
56760b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
56778bcb0991SDimitry Andric   case Intrinsic::umul_fix:
5678480093f4SDimitry Andric   case Intrinsic::umul_fix_sat:
5679480093f4SDimitry Andric   case Intrinsic::sdiv_fix:
56805ffd83dbSDimitry Andric   case Intrinsic::sdiv_fix_sat:
56815ffd83dbSDimitry Andric   case Intrinsic::udiv_fix:
56825ffd83dbSDimitry Andric   case Intrinsic::udiv_fix_sat: {
56830b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
56840b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
568581ad6265SDimitry Andric     Check(Op1->getType()->isIntOrIntVectorTy(),
5686480093f4SDimitry Andric           "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5687480093f4SDimitry Andric           "vector of ints");
568881ad6265SDimitry Andric     Check(Op2->getType()->isIntOrIntVectorTy(),
5689480093f4SDimitry Andric           "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5690480093f4SDimitry Andric           "vector of ints");
56910b57cec5SDimitry Andric 
56920b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5693cb14a3feSDimitry Andric     Check(Op3->getType()->isIntegerTy(),
5694cb14a3feSDimitry Andric           "third operand of [us][mul|div]_fix[_sat] must be an int type");
5695cb14a3feSDimitry Andric     Check(Op3->getBitWidth() <= 32,
5696cb14a3feSDimitry Andric           "third operand of [us][mul|div]_fix[_sat] must fit within 32 bits");
56970b57cec5SDimitry Andric 
5698480093f4SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
56995ffd83dbSDimitry Andric         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
570081ad6265SDimitry Andric       Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5701480093f4SDimitry Andric             "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5702480093f4SDimitry Andric             "the operands");
57030b57cec5SDimitry Andric     } else {
570481ad6265SDimitry Andric       Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5705480093f4SDimitry Andric             "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5706480093f4SDimitry Andric             "to the width of the operands");
57070b57cec5SDimitry Andric     }
57080b57cec5SDimitry Andric     break;
57090b57cec5SDimitry Andric   }
57100b57cec5SDimitry Andric   case Intrinsic::lrint:
57110b57cec5SDimitry Andric   case Intrinsic::llrint: {
57120b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
57130b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
57145f757f3fSDimitry Andric     Check(
57155f757f3fSDimitry Andric         ValTy->isFPOrFPVectorTy() && ResultTy->isIntOrIntVectorTy(),
57165f757f3fSDimitry Andric         "llvm.lrint, llvm.llrint: argument must be floating-point or vector "
57175f757f3fSDimitry Andric         "of floating-points, and result must be integer or vector of integers",
57185f757f3fSDimitry Andric         &Call);
57195f757f3fSDimitry Andric     Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
57205f757f3fSDimitry Andric           "llvm.lrint, llvm.llrint: argument and result disagree on vector use",
57215f757f3fSDimitry Andric           &Call);
57225f757f3fSDimitry Andric     if (ValTy->isVectorTy()) {
57235f757f3fSDimitry Andric       Check(cast<VectorType>(ValTy)->getElementCount() ==
57245f757f3fSDimitry Andric                 cast<VectorType>(ResultTy)->getElementCount(),
57255f757f3fSDimitry Andric             "llvm.lrint, llvm.llrint: argument must be same length as result",
57265f757f3fSDimitry Andric             &Call);
57275f757f3fSDimitry Andric     }
57285f757f3fSDimitry Andric     break;
57295f757f3fSDimitry Andric   }
57305f757f3fSDimitry Andric   case Intrinsic::lround:
57315f757f3fSDimitry Andric   case Intrinsic::llround: {
57325f757f3fSDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
57335f757f3fSDimitry Andric     Type *ResultTy = Call.getType();
573481ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
57350b57cec5SDimitry Andric           "Intrinsic does not support vectors", &Call);
57360b57cec5SDimitry Andric     break;
57370b57cec5SDimitry Andric   }
57385ffd83dbSDimitry Andric   case Intrinsic::bswap: {
57395ffd83dbSDimitry Andric     Type *Ty = Call.getType();
57405ffd83dbSDimitry Andric     unsigned Size = Ty->getScalarSizeInBits();
574181ad6265SDimitry Andric     Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
57425ffd83dbSDimitry Andric     break;
57435ffd83dbSDimitry Andric   }
5744e8d8bef9SDimitry Andric   case Intrinsic::invariant_start: {
5745e8d8bef9SDimitry Andric     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
574681ad6265SDimitry Andric     Check(InvariantSize &&
5747e8d8bef9SDimitry Andric               (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5748e8d8bef9SDimitry Andric           "invariant_start parameter must be -1, 0 or a positive number",
5749e8d8bef9SDimitry Andric           &Call);
5750e8d8bef9SDimitry Andric     break;
5751e8d8bef9SDimitry Andric   }
57525ffd83dbSDimitry Andric   case Intrinsic::matrix_multiply:
57535ffd83dbSDimitry Andric   case Intrinsic::matrix_transpose:
57545ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_load:
57555ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_store: {
57565ffd83dbSDimitry Andric     Function *IF = Call.getCalledFunction();
57575ffd83dbSDimitry Andric     ConstantInt *Stride = nullptr;
57585ffd83dbSDimitry Andric     ConstantInt *NumRows;
57595ffd83dbSDimitry Andric     ConstantInt *NumColumns;
57605ffd83dbSDimitry Andric     VectorType *ResultTy;
57615ffd83dbSDimitry Andric     Type *Op0ElemTy = nullptr;
57625ffd83dbSDimitry Andric     Type *Op1ElemTy = nullptr;
57635ffd83dbSDimitry Andric     switch (ID) {
576406c3fb27SDimitry Andric     case Intrinsic::matrix_multiply: {
57655ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
576606c3fb27SDimitry Andric       ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
57675ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
576806c3fb27SDimitry Andric       Check(cast<FixedVectorType>(Call.getArgOperand(0)->getType())
576906c3fb27SDimitry Andric                     ->getNumElements() ==
577006c3fb27SDimitry Andric                 NumRows->getZExtValue() * N->getZExtValue(),
577106c3fb27SDimitry Andric             "First argument of a matrix operation does not match specified "
577206c3fb27SDimitry Andric             "shape!");
577306c3fb27SDimitry Andric       Check(cast<FixedVectorType>(Call.getArgOperand(1)->getType())
577406c3fb27SDimitry Andric                     ->getNumElements() ==
577506c3fb27SDimitry Andric                 N->getZExtValue() * NumColumns->getZExtValue(),
577606c3fb27SDimitry Andric             "Second argument of a matrix operation does not match specified "
577706c3fb27SDimitry Andric             "shape!");
577806c3fb27SDimitry Andric 
57795ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
57805ffd83dbSDimitry Andric       Op0ElemTy =
57815ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
57825ffd83dbSDimitry Andric       Op1ElemTy =
57835ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
57845ffd83dbSDimitry Andric       break;
578506c3fb27SDimitry Andric     }
57865ffd83dbSDimitry Andric     case Intrinsic::matrix_transpose:
57875ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
57885ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
57895ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
57905ffd83dbSDimitry Andric       Op0ElemTy =
57915ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
57925ffd83dbSDimitry Andric       break;
57934824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_load: {
57945ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
57955ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
57965ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
57975ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
57985ffd83dbSDimitry Andric       break;
57994824e7fdSDimitry Andric     }
58004824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_store: {
58015ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
58025ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
58035ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
58045ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
58055ffd83dbSDimitry Andric       Op0ElemTy =
58065ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
58075ffd83dbSDimitry Andric       break;
58084824e7fdSDimitry Andric     }
58095ffd83dbSDimitry Andric     default:
58105ffd83dbSDimitry Andric       llvm_unreachable("unexpected intrinsic");
58115ffd83dbSDimitry Andric     }
58125ffd83dbSDimitry Andric 
581381ad6265SDimitry Andric     Check(ResultTy->getElementType()->isIntegerTy() ||
58145ffd83dbSDimitry Andric               ResultTy->getElementType()->isFloatingPointTy(),
58155ffd83dbSDimitry Andric           "Result type must be an integer or floating-point type!", IF);
58165ffd83dbSDimitry Andric 
58174824e7fdSDimitry Andric     if (Op0ElemTy)
581881ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op0ElemTy,
58195ffd83dbSDimitry Andric             "Vector element type mismatch of the result and first operand "
582081ad6265SDimitry Andric             "vector!",
582181ad6265SDimitry Andric             IF);
58225ffd83dbSDimitry Andric 
58235ffd83dbSDimitry Andric     if (Op1ElemTy)
582481ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op1ElemTy,
58255ffd83dbSDimitry Andric             "Vector element type mismatch of the result and second operand "
582681ad6265SDimitry Andric             "vector!",
582781ad6265SDimitry Andric             IF);
58285ffd83dbSDimitry Andric 
582981ad6265SDimitry Andric     Check(cast<FixedVectorType>(ResultTy)->getNumElements() ==
58305ffd83dbSDimitry Andric               NumRows->getZExtValue() * NumColumns->getZExtValue(),
58315ffd83dbSDimitry Andric           "Result of a matrix operation does not fit in the returned vector!");
58325ffd83dbSDimitry Andric 
58335ffd83dbSDimitry Andric     if (Stride)
583481ad6265SDimitry Andric       Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
58355ffd83dbSDimitry Andric             "Stride must be greater or equal than the number of rows!", IF);
58365ffd83dbSDimitry Andric 
58375ffd83dbSDimitry Andric     break;
58385ffd83dbSDimitry Andric   }
583904eeddc0SDimitry Andric   case Intrinsic::experimental_vector_splice: {
584004eeddc0SDimitry Andric     VectorType *VecTy = cast<VectorType>(Call.getType());
584104eeddc0SDimitry Andric     int64_t Idx = cast<ConstantInt>(Call.getArgOperand(2))->getSExtValue();
584204eeddc0SDimitry Andric     int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
584304eeddc0SDimitry Andric     if (Call.getParent() && Call.getParent()->getParent()) {
584404eeddc0SDimitry Andric       AttributeList Attrs = Call.getParent()->getParent()->getAttributes();
584504eeddc0SDimitry Andric       if (Attrs.hasFnAttr(Attribute::VScaleRange))
584604eeddc0SDimitry Andric         KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
584704eeddc0SDimitry Andric     }
584881ad6265SDimitry Andric     Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
584904eeddc0SDimitry Andric               (Idx >= 0 && Idx < KnownMinNumElements),
585004eeddc0SDimitry Andric           "The splice index exceeds the range [-VL, VL-1] where VL is the "
585104eeddc0SDimitry Andric           "known minimum number of elements in the vector. For scalable "
585204eeddc0SDimitry Andric           "vectors the minimum number of elements is determined from "
585304eeddc0SDimitry Andric           "vscale_range.",
585404eeddc0SDimitry Andric           &Call);
585504eeddc0SDimitry Andric     break;
585604eeddc0SDimitry Andric   }
5857fe6060f1SDimitry Andric   case Intrinsic::experimental_stepvector: {
5858fe6060f1SDimitry Andric     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
585981ad6265SDimitry Andric     Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5860fe6060f1SDimitry Andric               VecTy->getScalarSizeInBits() >= 8,
5861fe6060f1SDimitry Andric           "experimental_stepvector only supported for vectors of integers "
5862fe6060f1SDimitry Andric           "with a bitwidth of at least 8.",
5863fe6060f1SDimitry Andric           &Call);
5864fe6060f1SDimitry Andric     break;
5865fe6060f1SDimitry Andric   }
586681ad6265SDimitry Andric   case Intrinsic::vector_insert: {
5867fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5868fe6060f1SDimitry Andric     Value *SubVec = Call.getArgOperand(1);
5869fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(2);
5870fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5871e8d8bef9SDimitry Andric 
5872fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5873fe6060f1SDimitry Andric     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5874fe6060f1SDimitry Andric 
5875fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5876fe6060f1SDimitry Andric     ElementCount SubVecEC = SubVecTy->getElementCount();
587781ad6265SDimitry Andric     Check(VecTy->getElementType() == SubVecTy->getElementType(),
587881ad6265SDimitry Andric           "vector_insert parameters must have the same element "
5879e8d8bef9SDimitry Andric           "type.",
5880e8d8bef9SDimitry Andric           &Call);
588181ad6265SDimitry Andric     Check(IdxN % SubVecEC.getKnownMinValue() == 0,
588281ad6265SDimitry Andric           "vector_insert index must be a constant multiple of "
5883fe6060f1SDimitry Andric           "the subvector's known minimum vector length.");
5884fe6060f1SDimitry Andric 
5885fe6060f1SDimitry Andric     // If this insertion is not the 'mixed' case where a fixed vector is
5886fe6060f1SDimitry Andric     // inserted into a scalable vector, ensure that the insertion of the
5887fe6060f1SDimitry Andric     // subvector does not overrun the parent vector.
5888fe6060f1SDimitry Andric     if (VecEC.isScalable() == SubVecEC.isScalable()) {
588981ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
5890fe6060f1SDimitry Andric                 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
589181ad6265SDimitry Andric             "subvector operand of vector_insert would overrun the "
5892fe6060f1SDimitry Andric             "vector being inserted into.");
5893fe6060f1SDimitry Andric     }
5894e8d8bef9SDimitry Andric     break;
5895e8d8bef9SDimitry Andric   }
589681ad6265SDimitry Andric   case Intrinsic::vector_extract: {
5897fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5898fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(1);
5899fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5900fe6060f1SDimitry Andric 
5901e8d8bef9SDimitry Andric     VectorType *ResultTy = cast<VectorType>(Call.getType());
5902fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5903fe6060f1SDimitry Andric 
5904fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5905fe6060f1SDimitry Andric     ElementCount ResultEC = ResultTy->getElementCount();
5906e8d8bef9SDimitry Andric 
590781ad6265SDimitry Andric     Check(ResultTy->getElementType() == VecTy->getElementType(),
590881ad6265SDimitry Andric           "vector_extract result must have the same element "
5909e8d8bef9SDimitry Andric           "type as the input vector.",
5910e8d8bef9SDimitry Andric           &Call);
591181ad6265SDimitry Andric     Check(IdxN % ResultEC.getKnownMinValue() == 0,
591281ad6265SDimitry Andric           "vector_extract index must be a constant multiple of "
5913fe6060f1SDimitry Andric           "the result type's known minimum vector length.");
5914fe6060f1SDimitry Andric 
59155f757f3fSDimitry Andric     // If this extraction is not the 'mixed' case where a fixed vector is
5916fe6060f1SDimitry Andric     // extracted from a scalable vector, ensure that the extraction does not
5917fe6060f1SDimitry Andric     // overrun the parent vector.
5918fe6060f1SDimitry Andric     if (VecEC.isScalable() == ResultEC.isScalable()) {
591981ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
5920fe6060f1SDimitry Andric                 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
592181ad6265SDimitry Andric             "vector_extract would overrun.");
5922fe6060f1SDimitry Andric     }
5923e8d8bef9SDimitry Andric     break;
5924e8d8bef9SDimitry Andric   }
5925e8d8bef9SDimitry Andric   case Intrinsic::experimental_noalias_scope_decl: {
5926e8d8bef9SDimitry Andric     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5927e8d8bef9SDimitry Andric     break;
5928e8d8bef9SDimitry Andric   }
5929fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
593081ad6265SDimitry Andric   case Intrinsic::preserve_struct_access_index:
593181ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
593281ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
593381ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
593481ad6265SDimitry Andric   case Intrinsic::arm_ldrex: {
593581ad6265SDimitry Andric     Type *ElemTy = Call.getParamElementType(0);
593681ad6265SDimitry Andric     Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
593781ad6265SDimitry Andric           &Call);
593881ad6265SDimitry Andric     break;
593981ad6265SDimitry Andric   }
594081ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
594181ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
594281ad6265SDimitry Andric   case Intrinsic::arm_stlex:
594381ad6265SDimitry Andric   case Intrinsic::arm_strex: {
594481ad6265SDimitry Andric     Type *ElemTy = Call.getAttributes().getParamElementType(1);
594581ad6265SDimitry Andric     Check(ElemTy,
594681ad6265SDimitry Andric           "Intrinsic requires elementtype attribute on second argument.",
5947fe6060f1SDimitry Andric           &Call);
5948fe6060f1SDimitry Andric     break;
5949fe6060f1SDimitry Andric   }
5950bdd1243dSDimitry Andric   case Intrinsic::aarch64_prefetch: {
5951bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5952bdd1243dSDimitry Andric           "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5953bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
5954bdd1243dSDimitry Andric           "target argument to llvm.aarch64.prefetch must be 0-3", Call);
5955bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5956bdd1243dSDimitry Andric           "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5957bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
5958bdd1243dSDimitry Andric           "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5959bdd1243dSDimitry Andric     break;
5960bdd1243dSDimitry Andric   }
596106c3fb27SDimitry Andric   case Intrinsic::callbr_landingpad: {
596206c3fb27SDimitry Andric     const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
596306c3fb27SDimitry Andric     Check(CBR, "intrinstic requires callbr operand", &Call);
596406c3fb27SDimitry Andric     if (!CBR)
596506c3fb27SDimitry Andric       break;
596606c3fb27SDimitry Andric 
596706c3fb27SDimitry Andric     const BasicBlock *LandingPadBB = Call.getParent();
596806c3fb27SDimitry Andric     const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
596906c3fb27SDimitry Andric     if (!PredBB) {
597006c3fb27SDimitry Andric       CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
597106c3fb27SDimitry Andric       break;
597206c3fb27SDimitry Andric     }
597306c3fb27SDimitry Andric     if (!isa<CallBrInst>(PredBB->getTerminator())) {
597406c3fb27SDimitry Andric       CheckFailed("Intrinsic must have corresponding callbr in predecessor",
597506c3fb27SDimitry Andric                   &Call);
597606c3fb27SDimitry Andric       break;
597706c3fb27SDimitry Andric     }
597806c3fb27SDimitry Andric     Check(llvm::any_of(CBR->getIndirectDests(),
597906c3fb27SDimitry Andric                        [LandingPadBB](const BasicBlock *IndDest) {
598006c3fb27SDimitry Andric                          return IndDest == LandingPadBB;
598106c3fb27SDimitry Andric                        }),
598206c3fb27SDimitry Andric           "Intrinsic's corresponding callbr must have intrinsic's parent basic "
598306c3fb27SDimitry Andric           "block in indirect destination list",
598406c3fb27SDimitry Andric           &Call);
598506c3fb27SDimitry Andric     const Instruction &First = *LandingPadBB->begin();
598606c3fb27SDimitry Andric     Check(&First == &Call, "No other instructions may proceed intrinsic",
598706c3fb27SDimitry Andric           &Call);
598806c3fb27SDimitry Andric     break;
598906c3fb27SDimitry Andric   }
599006c3fb27SDimitry Andric   case Intrinsic::amdgcn_cs_chain: {
599106c3fb27SDimitry Andric     auto CallerCC = Call.getCaller()->getCallingConv();
599206c3fb27SDimitry Andric     switch (CallerCC) {
599306c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS:
599406c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS_Chain:
599506c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS_ChainPreserve:
599606c3fb27SDimitry Andric       break;
599706c3fb27SDimitry Andric     default:
599806c3fb27SDimitry Andric       CheckFailed("Intrinsic can only be used from functions with the "
599906c3fb27SDimitry Andric                   "amdgpu_cs, amdgpu_cs_chain or amdgpu_cs_chain_preserve "
600006c3fb27SDimitry Andric                   "calling conventions",
600106c3fb27SDimitry Andric                   &Call);
600206c3fb27SDimitry Andric       break;
600306c3fb27SDimitry Andric     }
60045f757f3fSDimitry Andric 
60055f757f3fSDimitry Andric     Check(Call.paramHasAttr(2, Attribute::InReg),
60065f757f3fSDimitry Andric           "SGPR arguments must have the `inreg` attribute", &Call);
60075f757f3fSDimitry Andric     Check(!Call.paramHasAttr(3, Attribute::InReg),
60085f757f3fSDimitry Andric           "VGPR arguments must not have the `inreg` attribute", &Call);
60095f757f3fSDimitry Andric     break;
60105f757f3fSDimitry Andric   }
60115f757f3fSDimitry Andric   case Intrinsic::amdgcn_set_inactive_chain_arg: {
60125f757f3fSDimitry Andric     auto CallerCC = Call.getCaller()->getCallingConv();
60135f757f3fSDimitry Andric     switch (CallerCC) {
60145f757f3fSDimitry Andric     case CallingConv::AMDGPU_CS_Chain:
60155f757f3fSDimitry Andric     case CallingConv::AMDGPU_CS_ChainPreserve:
60165f757f3fSDimitry Andric       break;
60175f757f3fSDimitry Andric     default:
60185f757f3fSDimitry Andric       CheckFailed("Intrinsic can only be used from functions with the "
60195f757f3fSDimitry Andric                   "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
60205f757f3fSDimitry Andric                   "calling conventions",
60215f757f3fSDimitry Andric                   &Call);
60225f757f3fSDimitry Andric       break;
60235f757f3fSDimitry Andric     }
60245f757f3fSDimitry Andric 
60255f757f3fSDimitry Andric     unsigned InactiveIdx = 1;
60265f757f3fSDimitry Andric     Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
60275f757f3fSDimitry Andric           "Value for inactive lanes must not have the `inreg` attribute",
60285f757f3fSDimitry Andric           &Call);
60295f757f3fSDimitry Andric     Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
60305f757f3fSDimitry Andric           "Value for inactive lanes must be a function argument", &Call);
60315f757f3fSDimitry Andric     Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
60325f757f3fSDimitry Andric           "Value for inactive lanes must be a VGPR function argument", &Call);
603306c3fb27SDimitry Andric     break;
603406c3fb27SDimitry Andric   }
6035*297eecfbSDimitry Andric   case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
6036*297eecfbSDimitry Andric   case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
6037*297eecfbSDimitry Andric     Value *V = Call.getArgOperand(0);
6038*297eecfbSDimitry Andric     unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
6039*297eecfbSDimitry Andric     Check(RegCount % 8 == 0,
6040*297eecfbSDimitry Andric           "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
6041*297eecfbSDimitry Andric     Check((RegCount >= 24 && RegCount <= 256),
6042*297eecfbSDimitry Andric           "reg_count argument to nvvm.setmaxnreg must be within [24, 256]");
6043*297eecfbSDimitry Andric     break;
6044*297eecfbSDimitry Andric   }
604506c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_entry:
604606c3fb27SDimitry Andric     LLVM_FALLTHROUGH;
604706c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_anchor:
604806c3fb27SDimitry Andric     break;
604906c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_loop:
605006c3fb27SDimitry Andric     break;
60515f757f3fSDimitry Andric   case Intrinsic::ptrmask: {
60525f757f3fSDimitry Andric     Type *Ty0 = Call.getArgOperand(0)->getType();
60535f757f3fSDimitry Andric     Type *Ty1 = Call.getArgOperand(1)->getType();
60545f757f3fSDimitry Andric     Check(Ty0->isPtrOrPtrVectorTy(),
60555f757f3fSDimitry Andric           "llvm.ptrmask intrinsic first argument must be pointer or vector "
60565f757f3fSDimitry Andric           "of pointers",
60575f757f3fSDimitry Andric           &Call);
60585f757f3fSDimitry Andric     Check(
60595f757f3fSDimitry Andric         Ty0->isVectorTy() == Ty1->isVectorTy(),
60605f757f3fSDimitry Andric         "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
60615f757f3fSDimitry Andric         &Call);
60625f757f3fSDimitry Andric     if (Ty0->isVectorTy())
60635f757f3fSDimitry Andric       Check(cast<VectorType>(Ty0)->getElementCount() ==
60645f757f3fSDimitry Andric                 cast<VectorType>(Ty1)->getElementCount(),
60655f757f3fSDimitry Andric             "llvm.ptrmask intrinsic arguments must have the same number of "
60665f757f3fSDimitry Andric             "elements",
60675f757f3fSDimitry Andric             &Call);
60685f757f3fSDimitry Andric     Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
60695f757f3fSDimitry Andric           "llvm.ptrmask intrinsic second argument bitwidth must match "
60705f757f3fSDimitry Andric           "pointer index type size of first argument",
60715f757f3fSDimitry Andric           &Call);
60725f757f3fSDimitry Andric     break;
60735f757f3fSDimitry Andric   }
60740b57cec5SDimitry Andric   };
607506c3fb27SDimitry Andric 
607606c3fb27SDimitry Andric   // Verify that there aren't any unmediated control transfers between funclets.
607706c3fb27SDimitry Andric   if (IntrinsicInst::mayLowerToFunctionCall(ID)) {
607806c3fb27SDimitry Andric     Function *F = Call.getParent()->getParent();
607906c3fb27SDimitry Andric     if (F->hasPersonalityFn() &&
608006c3fb27SDimitry Andric         isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
608106c3fb27SDimitry Andric       // Run EH funclet coloring on-demand and cache results for other intrinsic
608206c3fb27SDimitry Andric       // calls in this function
608306c3fb27SDimitry Andric       if (BlockEHFuncletColors.empty())
608406c3fb27SDimitry Andric         BlockEHFuncletColors = colorEHFunclets(*F);
608506c3fb27SDimitry Andric 
608606c3fb27SDimitry Andric       // Check for catch-/cleanup-pad in first funclet block
608706c3fb27SDimitry Andric       bool InEHFunclet = false;
608806c3fb27SDimitry Andric       BasicBlock *CallBB = Call.getParent();
608906c3fb27SDimitry Andric       const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
609006c3fb27SDimitry Andric       assert(CV.size() > 0 && "Uncolored block");
609106c3fb27SDimitry Andric       for (BasicBlock *ColorFirstBB : CV)
609206c3fb27SDimitry Andric         if (dyn_cast_or_null<FuncletPadInst>(ColorFirstBB->getFirstNonPHI()))
609306c3fb27SDimitry Andric           InEHFunclet = true;
609406c3fb27SDimitry Andric 
609506c3fb27SDimitry Andric       // Check for funclet operand bundle
609606c3fb27SDimitry Andric       bool HasToken = false;
609706c3fb27SDimitry Andric       for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
609806c3fb27SDimitry Andric         if (Call.getOperandBundleAt(I).getTagID() == LLVMContext::OB_funclet)
609906c3fb27SDimitry Andric           HasToken = true;
610006c3fb27SDimitry Andric 
610106c3fb27SDimitry Andric       // This would cause silent code truncation in WinEHPrepare
610206c3fb27SDimitry Andric       if (InEHFunclet)
610306c3fb27SDimitry Andric         Check(HasToken, "Missing funclet token on intrinsic call", &Call);
610406c3fb27SDimitry Andric     }
610506c3fb27SDimitry Andric   }
61060b57cec5SDimitry Andric }
61070b57cec5SDimitry Andric 
61080b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
61090b57cec5SDimitry Andric ///
61100b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
61110b57cec5SDimitry Andric /// built-in assertions that would typically fire.
61120b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
61130b57cec5SDimitry Andric   if (!LocalScope)
61140b57cec5SDimitry Andric     return nullptr;
61150b57cec5SDimitry Andric 
61160b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
61170b57cec5SDimitry Andric     return SP;
61180b57cec5SDimitry Andric 
61190b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
61200b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
61210b57cec5SDimitry Andric 
61220b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
61230b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
61240b57cec5SDimitry Andric   return nullptr;
61250b57cec5SDimitry Andric }
61260b57cec5SDimitry Andric 
612781ad6265SDimitry Andric void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
612881ad6265SDimitry Andric   if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
612981ad6265SDimitry Andric     auto *RetTy = cast<VectorType>(VPCast->getType());
613081ad6265SDimitry Andric     auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
613181ad6265SDimitry Andric     Check(RetTy->getElementCount() == ValTy->getElementCount(),
613281ad6265SDimitry Andric           "VP cast intrinsic first argument and result vector lengths must be "
613381ad6265SDimitry Andric           "equal",
613481ad6265SDimitry Andric           *VPCast);
613581ad6265SDimitry Andric 
613681ad6265SDimitry Andric     switch (VPCast->getIntrinsicID()) {
613781ad6265SDimitry Andric     default:
613881ad6265SDimitry Andric       llvm_unreachable("Unknown VP cast intrinsic");
613981ad6265SDimitry Andric     case Intrinsic::vp_trunc:
614081ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
614181ad6265SDimitry Andric             "llvm.vp.trunc intrinsic first argument and result element type "
614281ad6265SDimitry Andric             "must be integer",
614381ad6265SDimitry Andric             *VPCast);
614481ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
614581ad6265SDimitry Andric             "llvm.vp.trunc intrinsic the bit size of first argument must be "
614681ad6265SDimitry Andric             "larger than the bit size of the return type",
614781ad6265SDimitry Andric             *VPCast);
614881ad6265SDimitry Andric       break;
614981ad6265SDimitry Andric     case Intrinsic::vp_zext:
615081ad6265SDimitry Andric     case Intrinsic::vp_sext:
615181ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
615281ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
615381ad6265SDimitry Andric             "element type must be integer",
615481ad6265SDimitry Andric             *VPCast);
615581ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
615681ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
615781ad6265SDimitry Andric             "argument must be smaller than the bit size of the return type",
615881ad6265SDimitry Andric             *VPCast);
615981ad6265SDimitry Andric       break;
616081ad6265SDimitry Andric     case Intrinsic::vp_fptoui:
616181ad6265SDimitry Andric     case Intrinsic::vp_fptosi:
616281ad6265SDimitry Andric       Check(
616381ad6265SDimitry Andric           RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
616481ad6265SDimitry Andric           "llvm.vp.fptoui or llvm.vp.fptosi intrinsic first argument element "
616581ad6265SDimitry Andric           "type must be floating-point and result element type must be integer",
616681ad6265SDimitry Andric           *VPCast);
616781ad6265SDimitry Andric       break;
616881ad6265SDimitry Andric     case Intrinsic::vp_uitofp:
616981ad6265SDimitry Andric     case Intrinsic::vp_sitofp:
617081ad6265SDimitry Andric       Check(
617181ad6265SDimitry Andric           RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
617281ad6265SDimitry Andric           "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
617381ad6265SDimitry Andric           "type must be integer and result element type must be floating-point",
617481ad6265SDimitry Andric           *VPCast);
617581ad6265SDimitry Andric       break;
617681ad6265SDimitry Andric     case Intrinsic::vp_fptrunc:
617781ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
617881ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic first argument and result element type "
617981ad6265SDimitry Andric             "must be floating-point",
618081ad6265SDimitry Andric             *VPCast);
618181ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
618281ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
618381ad6265SDimitry Andric             "larger than the bit size of the return type",
618481ad6265SDimitry Andric             *VPCast);
618581ad6265SDimitry Andric       break;
618681ad6265SDimitry Andric     case Intrinsic::vp_fpext:
618781ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
618881ad6265SDimitry Andric             "llvm.vp.fpext intrinsic first argument and result element type "
618981ad6265SDimitry Andric             "must be floating-point",
619081ad6265SDimitry Andric             *VPCast);
619181ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
619281ad6265SDimitry Andric             "llvm.vp.fpext intrinsic the bit size of first argument must be "
619381ad6265SDimitry Andric             "smaller than the bit size of the return type",
619481ad6265SDimitry Andric             *VPCast);
619581ad6265SDimitry Andric       break;
619681ad6265SDimitry Andric     case Intrinsic::vp_ptrtoint:
619781ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
619881ad6265SDimitry Andric             "llvm.vp.ptrtoint intrinsic first argument element type must be "
619981ad6265SDimitry Andric             "pointer and result element type must be integer",
620081ad6265SDimitry Andric             *VPCast);
620181ad6265SDimitry Andric       break;
620281ad6265SDimitry Andric     case Intrinsic::vp_inttoptr:
620381ad6265SDimitry Andric       Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
620481ad6265SDimitry Andric             "llvm.vp.inttoptr intrinsic first argument element type must be "
620581ad6265SDimitry Andric             "integer and result element type must be pointer",
620681ad6265SDimitry Andric             *VPCast);
620781ad6265SDimitry Andric       break;
620881ad6265SDimitry Andric     }
620981ad6265SDimitry Andric   }
621081ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_fcmp) {
621181ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
621281ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
621381ad6265SDimitry Andric           "invalid predicate for VP FP comparison intrinsic", &VPI);
621481ad6265SDimitry Andric   }
621581ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_icmp) {
621681ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
621781ad6265SDimitry Andric     Check(CmpInst::isIntPredicate(Pred),
621881ad6265SDimitry Andric           "invalid predicate for VP integer comparison intrinsic", &VPI);
621981ad6265SDimitry Andric   }
62205f757f3fSDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_is_fpclass) {
62215f757f3fSDimitry Andric     auto TestMask = cast<ConstantInt>(VPI.getOperand(1));
62225f757f3fSDimitry Andric     Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
62235f757f3fSDimitry Andric           "unsupported bits for llvm.vp.is.fpclass test mask");
62245f757f3fSDimitry Andric   }
622581ad6265SDimitry Andric }
622681ad6265SDimitry Andric 
62270b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
6228480093f4SDimitry Andric   unsigned NumOperands;
6229480093f4SDimitry Andric   bool HasRoundingMD;
62300b57cec5SDimitry Andric   switch (FPI.getIntrinsicID()) {
62315ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6232480093f4SDimitry Andric   case Intrinsic::INTRINSIC:                                                   \
6233480093f4SDimitry Andric     NumOperands = NARG;                                                        \
6234480093f4SDimitry Andric     HasRoundingMD = ROUND_MODE;                                                \
62350b57cec5SDimitry Andric     break;
6236480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
6237480093f4SDimitry Andric   default:
6238480093f4SDimitry Andric     llvm_unreachable("Invalid constrained FP intrinsic!");
6239480093f4SDimitry Andric   }
6240480093f4SDimitry Andric   NumOperands += (1 + HasRoundingMD);
6241480093f4SDimitry Andric   // Compare intrinsics carry an extra predicate metadata operand.
6242480093f4SDimitry Andric   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
6243480093f4SDimitry Andric     NumOperands += 1;
624481ad6265SDimitry Andric   Check((FPI.arg_size() == NumOperands),
6245480093f4SDimitry Andric         "invalid arguments for constrained FP intrinsic", &FPI);
62460b57cec5SDimitry Andric 
6247480093f4SDimitry Andric   switch (FPI.getIntrinsicID()) {
62488bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
62498bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
62508bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
62518bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
625281ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
62538bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
62548bcb0991SDimitry Andric   }
62558bcb0991SDimitry Andric     break;
62568bcb0991SDimitry Andric 
62578bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
62588bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
62598bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
62608bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
626181ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
62628bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
62638bcb0991SDimitry Andric     break;
62648bcb0991SDimitry Andric   }
62658bcb0991SDimitry Andric 
6266480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmp:
6267480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmps: {
6268480093f4SDimitry Andric     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
626981ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
6270480093f4SDimitry Andric           "invalid predicate for constrained FP comparison intrinsic", &FPI);
62710b57cec5SDimitry Andric     break;
6272480093f4SDimitry Andric   }
62730b57cec5SDimitry Andric 
62748bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
62758bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
62768bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
627706c3fb27SDimitry Andric     ElementCount SrcEC;
627881ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
62798bcb0991SDimitry Andric           "Intrinsic first argument must be floating point", &FPI);
62808bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
628106c3fb27SDimitry Andric       SrcEC = cast<VectorType>(OperandT)->getElementCount();
62828bcb0991SDimitry Andric     }
62838bcb0991SDimitry Andric 
62848bcb0991SDimitry Andric     Operand = &FPI;
628506c3fb27SDimitry Andric     Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
62868bcb0991SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
628781ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
62888bcb0991SDimitry Andric           "Intrinsic result must be an integer", &FPI);
62898bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
629006c3fb27SDimitry Andric       Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
62918bcb0991SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
62928bcb0991SDimitry Andric             &FPI);
62938bcb0991SDimitry Andric     }
62948bcb0991SDimitry Andric   }
62958bcb0991SDimitry Andric     break;
62968bcb0991SDimitry Andric 
6297480093f4SDimitry Andric   case Intrinsic::experimental_constrained_sitofp:
6298480093f4SDimitry Andric   case Intrinsic::experimental_constrained_uitofp: {
6299480093f4SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
630006c3fb27SDimitry Andric     ElementCount SrcEC;
630181ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
6302480093f4SDimitry Andric           "Intrinsic first argument must be integer", &FPI);
6303480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
630406c3fb27SDimitry Andric       SrcEC = cast<VectorType>(OperandT)->getElementCount();
6305480093f4SDimitry Andric     }
6306480093f4SDimitry Andric 
6307480093f4SDimitry Andric     Operand = &FPI;
630806c3fb27SDimitry Andric     Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
6309480093f4SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
631081ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
6311480093f4SDimitry Andric           "Intrinsic result must be a floating point", &FPI);
6312480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
631306c3fb27SDimitry Andric       Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
6314480093f4SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
6315480093f4SDimitry Andric             &FPI);
6316480093f4SDimitry Andric     }
6317480093f4SDimitry Andric   } break;
6318480093f4SDimitry Andric 
63190b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
63200b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
63210b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
63220b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
63230b57cec5SDimitry Andric     Value *Result = &FPI;
63240b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
632581ad6265SDimitry Andric     Check(OperandTy->isFPOrFPVectorTy(),
63260b57cec5SDimitry Andric           "Intrinsic first argument must be FP or FP vector", &FPI);
632781ad6265SDimitry Andric     Check(ResultTy->isFPOrFPVectorTy(),
63280b57cec5SDimitry Andric           "Intrinsic result must be FP or FP vector", &FPI);
632981ad6265SDimitry Andric     Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
63300b57cec5SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
63310b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
633206c3fb27SDimitry Andric       Check(cast<VectorType>(OperandTy)->getElementCount() ==
633306c3fb27SDimitry Andric                 cast<VectorType>(ResultTy)->getElementCount(),
63340b57cec5SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
63350b57cec5SDimitry Andric             &FPI);
63360b57cec5SDimitry Andric     }
63370b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
633881ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
63390b57cec5SDimitry Andric             "Intrinsic first argument's type must be larger than result type",
63400b57cec5SDimitry Andric             &FPI);
63410b57cec5SDimitry Andric     } else {
634281ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
63430b57cec5SDimitry Andric             "Intrinsic first argument's type must be smaller than result type",
63440b57cec5SDimitry Andric             &FPI);
63450b57cec5SDimitry Andric     }
63460b57cec5SDimitry Andric   }
63470b57cec5SDimitry Andric     break;
63480b57cec5SDimitry Andric 
63490b57cec5SDimitry Andric   default:
6350480093f4SDimitry Andric     break;
63510b57cec5SDimitry Andric   }
63520b57cec5SDimitry Andric 
63530b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
63540b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
63550b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
63560b57cec5SDimitry Andric   // argument type check is needed here.
63570b57cec5SDimitry Andric 
635881ad6265SDimitry Andric   Check(FPI.getExceptionBehavior().has_value(),
63590b57cec5SDimitry Andric         "invalid exception behavior argument", &FPI);
63600b57cec5SDimitry Andric   if (HasRoundingMD) {
636181ad6265SDimitry Andric     Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
636281ad6265SDimitry Andric           &FPI);
63630b57cec5SDimitry Andric   }
63640b57cec5SDimitry Andric }
63650b57cec5SDimitry Andric 
63660b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
6367fe6060f1SDimitry Andric   auto *MD = DII.getRawLocation();
636881ad6265SDimitry Andric   CheckDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
63690b57cec5SDimitry Andric               (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
63700b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
637181ad6265SDimitry Andric   CheckDI(isa<DILocalVariable>(DII.getRawVariable()),
63720b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
63730b57cec5SDimitry Andric           DII.getRawVariable());
637481ad6265SDimitry Andric   CheckDI(isa<DIExpression>(DII.getRawExpression()),
63750b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
63760b57cec5SDimitry Andric           DII.getRawExpression());
63770b57cec5SDimitry Andric 
6378bdd1243dSDimitry Andric   if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&DII)) {
6379bdd1243dSDimitry Andric     CheckDI(isa<DIAssignID>(DAI->getRawAssignID()),
6380bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic DIAssignID", &DII,
6381bdd1243dSDimitry Andric             DAI->getRawAssignID());
6382bdd1243dSDimitry Andric     const auto *RawAddr = DAI->getRawAddress();
6383bdd1243dSDimitry Andric     CheckDI(
6384bdd1243dSDimitry Andric         isa<ValueAsMetadata>(RawAddr) ||
6385bdd1243dSDimitry Andric             (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
6386bdd1243dSDimitry Andric         "invalid llvm.dbg.assign intrinsic address", &DII,
6387bdd1243dSDimitry Andric         DAI->getRawAddress());
6388bdd1243dSDimitry Andric     CheckDI(isa<DIExpression>(DAI->getRawAddressExpression()),
6389bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic address expression", &DII,
6390bdd1243dSDimitry Andric             DAI->getRawAddressExpression());
6391bdd1243dSDimitry Andric     // All of the linked instructions should be in the same function as DII.
6392bdd1243dSDimitry Andric     for (Instruction *I : at::getAssignmentInsts(DAI))
6393bdd1243dSDimitry Andric       CheckDI(DAI->getFunction() == I->getFunction(),
6394bdd1243dSDimitry Andric               "inst not in same function as dbg.assign", I, DAI);
6395bdd1243dSDimitry Andric   }
6396bdd1243dSDimitry Andric 
63970b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
63980b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
63990b57cec5SDimitry Andric     if (!isa<DILocation>(N))
64000b57cec5SDimitry Andric       return;
64010b57cec5SDimitry Andric 
64020b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
64030b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
64040b57cec5SDimitry Andric 
64050b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
64060b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
64070b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
640881ad6265SDimitry Andric   CheckDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
64090b57cec5SDimitry Andric           &DII, BB, F);
64100b57cec5SDimitry Andric 
64110b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
64120b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
64130b57cec5SDimitry Andric   if (!VarSP || !LocSP)
64140b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
64150b57cec5SDimitry Andric 
641681ad6265SDimitry Andric   CheckDI(VarSP == LocSP,
641781ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
64180b57cec5SDimitry Andric               " variable and !dbg attachment",
64190b57cec5SDimitry Andric           &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
64200b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
64210b57cec5SDimitry Andric 
64220b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
642381ad6265SDimitry Andric   CheckDI(isType(Var->getRawType()), "invalid type ref", Var,
64240b57cec5SDimitry Andric           Var->getRawType());
64250b57cec5SDimitry Andric   verifyFnArgs(DII);
64260b57cec5SDimitry Andric }
64270b57cec5SDimitry Andric 
64280b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
642981ad6265SDimitry Andric   CheckDI(isa<DILabel>(DLI.getRawLabel()),
64300b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
64310b57cec5SDimitry Andric           DLI.getRawLabel());
64320b57cec5SDimitry Andric 
64330b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
64340b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
64350b57cec5SDimitry Andric     if (!isa<DILocation>(N))
64360b57cec5SDimitry Andric       return;
64370b57cec5SDimitry Andric 
64380b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
64390b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
64400b57cec5SDimitry Andric 
64410b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
64420b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
64430b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
644481ad6265SDimitry Andric   Check(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", &DLI,
644581ad6265SDimitry Andric         BB, F);
64460b57cec5SDimitry Andric 
64470b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
64480b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
64490b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
64500b57cec5SDimitry Andric     return;
64510b57cec5SDimitry Andric 
645281ad6265SDimitry Andric   CheckDI(LabelSP == LocSP,
645381ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
64540b57cec5SDimitry Andric               " label and !dbg attachment",
64550b57cec5SDimitry Andric           &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
64560b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
64570b57cec5SDimitry Andric }
64580b57cec5SDimitry Andric 
64590b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
64600b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
64610b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
64620b57cec5SDimitry Andric 
64630b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
64640b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
64650b57cec5SDimitry Andric     return;
64660b57cec5SDimitry Andric 
64670b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
64680b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
64690b57cec5SDimitry Andric   if (!Fragment)
64700b57cec5SDimitry Andric     return;
64710b57cec5SDimitry Andric 
64720b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
64730b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
64740b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
64750b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
64760b57cec5SDimitry Andric   // variable and this check fails.
64770b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
64780b57cec5SDimitry Andric   if (V->isArtificial())
64790b57cec5SDimitry Andric     return;
64800b57cec5SDimitry Andric 
64810b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
64820b57cec5SDimitry Andric }
64830b57cec5SDimitry Andric 
64840b57cec5SDimitry Andric template <typename ValueOrMetadata>
64850b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
64860b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
64870b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
64880b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
64890b57cec5SDimitry Andric   // elsewhere.
64900b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
64910b57cec5SDimitry Andric   if (!VarSize)
64920b57cec5SDimitry Andric     return;
64930b57cec5SDimitry Andric 
64940b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
64950b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
649681ad6265SDimitry Andric   CheckDI(FragSize + FragOffset <= *VarSize,
64970b57cec5SDimitry Andric           "fragment is larger than or outside of variable", Desc, &V);
649881ad6265SDimitry Andric   CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
64990b57cec5SDimitry Andric }
65000b57cec5SDimitry Andric 
65010b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
65020b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
65030b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
65040b57cec5SDimitry Andric   // contain inlined debug intrinsics.
65050b57cec5SDimitry Andric   if (!HasDebugInfo)
65060b57cec5SDimitry Andric     return;
65070b57cec5SDimitry Andric 
65080b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
65090b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
65100b57cec5SDimitry Andric     return;
65110b57cec5SDimitry Andric 
65120b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
651381ad6265SDimitry Andric   CheckDI(Var, "dbg intrinsic without variable");
65140b57cec5SDimitry Andric 
65150b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
65160b57cec5SDimitry Andric   if (!ArgNo)
65170b57cec5SDimitry Andric     return;
65180b57cec5SDimitry Andric 
65190b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
65200b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
65210b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
65220b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
65230b57cec5SDimitry Andric 
65240b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
65250b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
652681ad6265SDimitry Andric   CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
65270b57cec5SDimitry Andric           Prev, Var);
65280b57cec5SDimitry Andric }
65290b57cec5SDimitry Andric 
65308bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
65318bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
65328bcb0991SDimitry Andric 
65338bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
65348bcb0991SDimitry Andric   if (!E || !E->isValid())
65358bcb0991SDimitry Andric     return;
65368bcb0991SDimitry Andric 
65375f757f3fSDimitry Andric   if (isa<ValueAsMetadata>(I.getRawLocation())) {
65385f757f3fSDimitry Andric     Value *VarValue = I.getVariableLocationOp(0);
65395f757f3fSDimitry Andric     if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
65405f757f3fSDimitry Andric       return;
654106c3fb27SDimitry Andric     // We allow EntryValues for swift async arguments, as they have an
654206c3fb27SDimitry Andric     // ABI-guarantee to be turned into a specific register.
65435f757f3fSDimitry Andric     if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
654406c3fb27SDimitry Andric         ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
654506c3fb27SDimitry Andric       return;
65465f757f3fSDimitry Andric   }
654706c3fb27SDimitry Andric 
654806c3fb27SDimitry Andric   CheckDI(!E->isEntryValue(),
654906c3fb27SDimitry Andric           "Entry values are only allowed in MIR unless they target a "
655006c3fb27SDimitry Andric           "swiftasync Argument",
655106c3fb27SDimitry Andric           &I);
65528bcb0991SDimitry Andric }
65538bcb0991SDimitry Andric 
65540b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
65550b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
65560b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
65570b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
65580b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
65590b57cec5SDimitry Andric     return;
65600b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
65610b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
65620b57cec5SDimitry Andric   if (CUs)
65630b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
6564bdd1243dSDimitry Andric   for (const auto *CU : CUVisited)
656581ad6265SDimitry Andric     CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
65660b57cec5SDimitry Andric   CUVisited.clear();
65670b57cec5SDimitry Andric }
65680b57cec5SDimitry Andric 
65690b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
65700b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
65710b57cec5SDimitry Andric     return;
65720b57cec5SDimitry Andric 
65730b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
6574bdd1243dSDimitry Andric   for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
657581ad6265SDimitry Andric     Check(First->getCallingConv() == F->getCallingConv(),
65760b57cec5SDimitry Andric           "All llvm.experimental.deoptimize declarations must have the same "
65770b57cec5SDimitry Andric           "calling convention",
65780b57cec5SDimitry Andric           First, F);
65790b57cec5SDimitry Andric   }
65800b57cec5SDimitry Andric }
65810b57cec5SDimitry Andric 
6582349cc55cSDimitry Andric void Verifier::verifyAttachedCallBundle(const CallBase &Call,
6583349cc55cSDimitry Andric                                         const OperandBundleUse &BU) {
6584349cc55cSDimitry Andric   FunctionType *FTy = Call.getFunctionType();
6585349cc55cSDimitry Andric 
658681ad6265SDimitry Andric   Check((FTy->getReturnType()->isPointerTy() ||
6587349cc55cSDimitry Andric          (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
6588349cc55cSDimitry Andric         "a call with operand bundle \"clang.arc.attachedcall\" must call a "
6589349cc55cSDimitry Andric         "function returning a pointer or a non-returning function that has a "
6590349cc55cSDimitry Andric         "void return type",
6591349cc55cSDimitry Andric         Call);
6592349cc55cSDimitry Andric 
659381ad6265SDimitry Andric   Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
65941fd87a68SDimitry Andric         "operand bundle \"clang.arc.attachedcall\" requires one function as "
65951fd87a68SDimitry Andric         "an argument",
6596349cc55cSDimitry Andric         Call);
6597349cc55cSDimitry Andric 
6598349cc55cSDimitry Andric   auto *Fn = cast<Function>(BU.Inputs.front());
6599349cc55cSDimitry Andric   Intrinsic::ID IID = Fn->getIntrinsicID();
6600349cc55cSDimitry Andric 
6601349cc55cSDimitry Andric   if (IID) {
660281ad6265SDimitry Andric     Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
6603349cc55cSDimitry Andric            IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
6604349cc55cSDimitry Andric           "invalid function argument", Call);
6605349cc55cSDimitry Andric   } else {
6606349cc55cSDimitry Andric     StringRef FnName = Fn->getName();
660781ad6265SDimitry Andric     Check((FnName == "objc_retainAutoreleasedReturnValue" ||
6608349cc55cSDimitry Andric            FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
6609349cc55cSDimitry Andric           "invalid function argument", Call);
6610349cc55cSDimitry Andric   }
6611349cc55cSDimitry Andric }
6612349cc55cSDimitry Andric 
6613e8d8bef9SDimitry Andric void Verifier::verifyNoAliasScopeDecl() {
6614e8d8bef9SDimitry Andric   if (NoAliasScopeDecls.empty())
6615e8d8bef9SDimitry Andric     return;
6616e8d8bef9SDimitry Andric 
6617e8d8bef9SDimitry Andric   // only a single scope must be declared at a time.
6618e8d8bef9SDimitry Andric   for (auto *II : NoAliasScopeDecls) {
6619e8d8bef9SDimitry Andric     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
6620e8d8bef9SDimitry Andric            "Not a llvm.experimental.noalias.scope.decl ?");
6621e8d8bef9SDimitry Andric     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
6622e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
662381ad6265SDimitry Andric     Check(ScopeListMV != nullptr,
6624e8d8bef9SDimitry Andric           "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
6625e8d8bef9SDimitry Andric           "argument",
6626e8d8bef9SDimitry Andric           II);
6627e8d8bef9SDimitry Andric 
6628e8d8bef9SDimitry Andric     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
662981ad6265SDimitry Andric     Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
663081ad6265SDimitry Andric     Check(ScopeListMD->getNumOperands() == 1,
6631e8d8bef9SDimitry Andric           "!id.scope.list must point to a list with a single scope", II);
6632349cc55cSDimitry Andric     visitAliasScopeListMetadata(ScopeListMD);
6633e8d8bef9SDimitry Andric   }
6634e8d8bef9SDimitry Andric 
6635e8d8bef9SDimitry Andric   // Only check the domination rule when requested. Once all passes have been
6636e8d8bef9SDimitry Andric   // adapted this option can go away.
6637e8d8bef9SDimitry Andric   if (!VerifyNoAliasScopeDomination)
6638e8d8bef9SDimitry Andric     return;
6639e8d8bef9SDimitry Andric 
6640e8d8bef9SDimitry Andric   // Now sort the intrinsics based on the scope MDNode so that declarations of
6641e8d8bef9SDimitry Andric   // the same scopes are next to each other.
6642e8d8bef9SDimitry Andric   auto GetScope = [](IntrinsicInst *II) {
6643e8d8bef9SDimitry Andric     const auto *ScopeListMV = cast<MetadataAsValue>(
6644e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
6645e8d8bef9SDimitry Andric     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
6646e8d8bef9SDimitry Andric   };
6647e8d8bef9SDimitry Andric 
6648e8d8bef9SDimitry Andric   // We are sorting on MDNode pointers here. For valid input IR this is ok.
6649e8d8bef9SDimitry Andric   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
6650e8d8bef9SDimitry Andric   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
6651e8d8bef9SDimitry Andric     return GetScope(Lhs) < GetScope(Rhs);
6652e8d8bef9SDimitry Andric   };
6653e8d8bef9SDimitry Andric 
6654e8d8bef9SDimitry Andric   llvm::sort(NoAliasScopeDecls, Compare);
6655e8d8bef9SDimitry Andric 
6656e8d8bef9SDimitry Andric   // Go over the intrinsics and check that for the same scope, they are not
6657e8d8bef9SDimitry Andric   // dominating each other.
6658e8d8bef9SDimitry Andric   auto ItCurrent = NoAliasScopeDecls.begin();
6659e8d8bef9SDimitry Andric   while (ItCurrent != NoAliasScopeDecls.end()) {
6660e8d8bef9SDimitry Andric     auto CurScope = GetScope(*ItCurrent);
6661e8d8bef9SDimitry Andric     auto ItNext = ItCurrent;
6662e8d8bef9SDimitry Andric     do {
6663e8d8bef9SDimitry Andric       ++ItNext;
6664e8d8bef9SDimitry Andric     } while (ItNext != NoAliasScopeDecls.end() &&
6665e8d8bef9SDimitry Andric              GetScope(*ItNext) == CurScope);
6666e8d8bef9SDimitry Andric 
6667e8d8bef9SDimitry Andric     // [ItCurrent, ItNext) represents the declarations for the same scope.
6668e8d8bef9SDimitry Andric     // Ensure they are not dominating each other.. but only if it is not too
6669e8d8bef9SDimitry Andric     // expensive.
6670e8d8bef9SDimitry Andric     if (ItNext - ItCurrent < 32)
6671e8d8bef9SDimitry Andric       for (auto *I : llvm::make_range(ItCurrent, ItNext))
6672e8d8bef9SDimitry Andric         for (auto *J : llvm::make_range(ItCurrent, ItNext))
6673e8d8bef9SDimitry Andric           if (I != J)
667481ad6265SDimitry Andric             Check(!DT.dominates(I, J),
6675e8d8bef9SDimitry Andric                   "llvm.experimental.noalias.scope.decl dominates another one "
6676e8d8bef9SDimitry Andric                   "with the same scope",
6677e8d8bef9SDimitry Andric                   I);
6678e8d8bef9SDimitry Andric     ItCurrent = ItNext;
6679e8d8bef9SDimitry Andric   }
6680e8d8bef9SDimitry Andric }
6681e8d8bef9SDimitry Andric 
66820b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66830b57cec5SDimitry Andric //  Implement the public interfaces to this file...
66840b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66850b57cec5SDimitry Andric 
66860b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
66870b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
66880b57cec5SDimitry Andric 
66890b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
66900b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
66910b57cec5SDimitry Andric 
66920b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
66930b57cec5SDimitry Andric   // expect of a function called "verify".
66940b57cec5SDimitry Andric   return !V.verify(F);
66950b57cec5SDimitry Andric }
66960b57cec5SDimitry Andric 
66970b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
66980b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
66990b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
67000b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
67010b57cec5SDimitry Andric 
67020b57cec5SDimitry Andric   bool Broken = false;
67030b57cec5SDimitry Andric   for (const Function &F : M)
67040b57cec5SDimitry Andric     Broken |= !V.verify(F);
67050b57cec5SDimitry Andric 
67060b57cec5SDimitry Andric   Broken |= !V.verify();
67070b57cec5SDimitry Andric   if (BrokenDebugInfo)
67080b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
67090b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
67100b57cec5SDimitry Andric   // expect of a function called "verify".
67110b57cec5SDimitry Andric   return Broken;
67120b57cec5SDimitry Andric }
67130b57cec5SDimitry Andric 
67140b57cec5SDimitry Andric namespace {
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
67170b57cec5SDimitry Andric   static char ID;
67180b57cec5SDimitry Andric 
67190b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
67200b57cec5SDimitry Andric   bool FatalErrors = true;
67210b57cec5SDimitry Andric 
67220b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
67230b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
67240b57cec5SDimitry Andric   }
67250b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
67260b57cec5SDimitry Andric       : FunctionPass(ID),
67270b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
67280b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
67290b57cec5SDimitry Andric   }
67300b57cec5SDimitry Andric 
67310b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
67328bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
67330b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
67340b57cec5SDimitry Andric     return false;
67350b57cec5SDimitry Andric   }
67360b57cec5SDimitry Andric 
67370b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
67380b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
67390b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
67400b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
67410b57cec5SDimitry Andric     }
67420b57cec5SDimitry Andric     return false;
67430b57cec5SDimitry Andric   }
67440b57cec5SDimitry Andric 
67450b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
67460b57cec5SDimitry Andric     bool HasErrors = false;
67470b57cec5SDimitry Andric     for (Function &F : M)
67480b57cec5SDimitry Andric       if (F.isDeclaration())
67490b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
67500b57cec5SDimitry Andric 
67510b57cec5SDimitry Andric     HasErrors |= !V->verify();
67520b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
67530b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
67540b57cec5SDimitry Andric     return false;
67550b57cec5SDimitry Andric   }
67560b57cec5SDimitry Andric 
67570b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
67580b57cec5SDimitry Andric     AU.setPreservesAll();
67590b57cec5SDimitry Andric   }
67600b57cec5SDimitry Andric };
67610b57cec5SDimitry Andric 
67620b57cec5SDimitry Andric } // end anonymous namespace
67630b57cec5SDimitry Andric 
67640b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
67650b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
67660b57cec5SDimitry Andric   if (Diagnostic)
67670b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
67680b57cec5SDimitry Andric }
67690b57cec5SDimitry Andric 
677081ad6265SDimitry Andric #define CheckTBAA(C, ...)                                                      \
67710b57cec5SDimitry Andric   do {                                                                         \
67720b57cec5SDimitry Andric     if (!(C)) {                                                                \
67730b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
67740b57cec5SDimitry Andric       return false;                                                            \
67750b57cec5SDimitry Andric     }                                                                          \
67760b57cec5SDimitry Andric   } while (false)
67770b57cec5SDimitry Andric 
67780b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
67790b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
67800b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
67810b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
67820b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
67830b57cec5SDimitry Andric                                  bool IsNewFormat) {
67840b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
67850b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
67860b57cec5SDimitry Andric     return {true, ~0u};
67870b57cec5SDimitry Andric   }
67880b57cec5SDimitry Andric 
67890b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
67900b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
67910b57cec5SDimitry Andric     return Itr->second;
67920b57cec5SDimitry Andric 
67930b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
67940b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
67950b57cec5SDimitry Andric   (void)InsertResult;
67960b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
67970b57cec5SDimitry Andric   return Result;
67980b57cec5SDimitry Andric }
67990b57cec5SDimitry Andric 
68000b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
68010b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
68020b57cec5SDimitry Andric                                      bool IsNewFormat) {
68030b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
68040b57cec5SDimitry Andric 
68050b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
68060b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
68070b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
68080b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
68090b57cec5SDimitry Andric                : InvalidNode;
68100b57cec5SDimitry Andric   }
68110b57cec5SDimitry Andric 
68120b57cec5SDimitry Andric   if (IsNewFormat) {
68130b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
68140b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
68150b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
68160b57cec5SDimitry Andric       return InvalidNode;
68170b57cec5SDimitry Andric     }
68180b57cec5SDimitry Andric   } else {
68190b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
68200b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
68210b57cec5SDimitry Andric                   BaseNode);
68220b57cec5SDimitry Andric       return InvalidNode;
68230b57cec5SDimitry Andric     }
68240b57cec5SDimitry Andric   }
68250b57cec5SDimitry Andric 
68260b57cec5SDimitry Andric   // Check the type size field.
68270b57cec5SDimitry Andric   if (IsNewFormat) {
68280b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
68290b57cec5SDimitry Andric         BaseNode->getOperand(1));
68300b57cec5SDimitry Andric     if (!TypeSizeNode) {
68310b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
68320b57cec5SDimitry Andric       return InvalidNode;
68330b57cec5SDimitry Andric     }
68340b57cec5SDimitry Andric   }
68350b57cec5SDimitry Andric 
68360b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
68370b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
68380b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
68390b57cec5SDimitry Andric                 BaseNode);
68400b57cec5SDimitry Andric     return InvalidNode;
68410b57cec5SDimitry Andric   }
68420b57cec5SDimitry Andric 
68430b57cec5SDimitry Andric   bool Failed = false;
68440b57cec5SDimitry Andric 
6845bdd1243dSDimitry Andric   std::optional<APInt> PrevOffset;
68460b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
68470b57cec5SDimitry Andric 
68480b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
68490b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
68500b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
68510b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
68520b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
68530b57cec5SDimitry Andric            Idx += NumOpsPerField) {
68540b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
68550b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
68560b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
68570b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
68580b57cec5SDimitry Andric       Failed = true;
68590b57cec5SDimitry Andric       continue;
68600b57cec5SDimitry Andric     }
68610b57cec5SDimitry Andric 
68620b57cec5SDimitry Andric     auto *OffsetEntryCI =
68630b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
68640b57cec5SDimitry Andric     if (!OffsetEntryCI) {
68650b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
68660b57cec5SDimitry Andric       Failed = true;
68670b57cec5SDimitry Andric       continue;
68680b57cec5SDimitry Andric     }
68690b57cec5SDimitry Andric 
68700b57cec5SDimitry Andric     if (BitWidth == ~0u)
68710b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
68720b57cec5SDimitry Andric 
68730b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
68740b57cec5SDimitry Andric       CheckFailed(
68750b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
68760b57cec5SDimitry Andric           BaseNode);
68770b57cec5SDimitry Andric       Failed = true;
68780b57cec5SDimitry Andric       continue;
68790b57cec5SDimitry Andric     }
68800b57cec5SDimitry Andric 
68810b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
68820b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
68830b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
68840b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
68850b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
68860b57cec5SDimitry Andric     bool IsAscending =
68870b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
68880b57cec5SDimitry Andric 
68890b57cec5SDimitry Andric     if (!IsAscending) {
68900b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
68910b57cec5SDimitry Andric       Failed = true;
68920b57cec5SDimitry Andric     }
68930b57cec5SDimitry Andric 
68940b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
68950b57cec5SDimitry Andric 
68960b57cec5SDimitry Andric     if (IsNewFormat) {
68970b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
68980b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
68990b57cec5SDimitry Andric       if (!MemberSizeNode) {
69000b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
69010b57cec5SDimitry Andric         Failed = true;
69020b57cec5SDimitry Andric         continue;
69030b57cec5SDimitry Andric       }
69040b57cec5SDimitry Andric     }
69050b57cec5SDimitry Andric   }
69060b57cec5SDimitry Andric 
69070b57cec5SDimitry Andric   return Failed ? InvalidNode
69080b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
69090b57cec5SDimitry Andric }
69100b57cec5SDimitry Andric 
69110b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
69120b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
69130b57cec5SDimitry Andric }
69140b57cec5SDimitry Andric 
69150b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
69160b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
69170b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
69180b57cec5SDimitry Andric     return false;
69190b57cec5SDimitry Andric 
69200b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
69210b57cec5SDimitry Andric     return false;
69220b57cec5SDimitry Andric 
69230b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
69240b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
69250b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
69260b57cec5SDimitry Andric       return false;
69270b57cec5SDimitry Andric   }
69280b57cec5SDimitry Andric 
69290b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
69300b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
69310b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
69320b57cec5SDimitry Andric }
69330b57cec5SDimitry Andric 
69340b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
69350b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
69360b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
69370b57cec5SDimitry Andric     return ResultIt->second;
69380b57cec5SDimitry Andric 
69390b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
69400b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
69410b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
69420b57cec5SDimitry Andric   (void)InsertResult;
69430b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
69440b57cec5SDimitry Andric 
69450b57cec5SDimitry Andric   return Result;
69460b57cec5SDimitry Andric }
69470b57cec5SDimitry Andric 
69480b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
69490b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
69500b57cec5SDimitry Andric ///
69510b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
69520b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
69530b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
69540b57cec5SDimitry Andric                                                    APInt &Offset,
69550b57cec5SDimitry Andric                                                    bool IsNewFormat) {
69560b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
69570b57cec5SDimitry Andric 
69580b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
69590b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
696081ad6265SDimitry Andric   // to check that.
69610b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
69620b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
69630b57cec5SDimitry Andric 
69640b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
69650b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
69660b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
69670b57cec5SDimitry Andric            Idx += NumOpsPerField) {
69680b57cec5SDimitry Andric     auto *OffsetEntryCI =
69690b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
69700b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
69710b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
69720b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
69730b57cec5SDimitry Andric                     BaseNode, &Offset);
69740b57cec5SDimitry Andric         return nullptr;
69750b57cec5SDimitry Andric       }
69760b57cec5SDimitry Andric 
69770b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
69780b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
69790b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
69800b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
69810b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
69820b57cec5SDimitry Andric     }
69830b57cec5SDimitry Andric   }
69840b57cec5SDimitry Andric 
69850b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
69860b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
69870b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
69880b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
69890b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
69900b57cec5SDimitry Andric }
69910b57cec5SDimitry Andric 
69920b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
69930b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
69940b57cec5SDimitry Andric     return false;
69950b57cec5SDimitry Andric 
69960b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
69970b57cec5SDimitry Andric   // its first operand.
6998349cc55cSDimitry Andric   return isa_and_nonnull<MDNode>(Type->getOperand(0));
69990b57cec5SDimitry Andric }
70000b57cec5SDimitry Andric 
70010b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
700206c3fb27SDimitry Andric   CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands",
700306c3fb27SDimitry Andric             &I, MD);
700406c3fb27SDimitry Andric 
700581ad6265SDimitry Andric   CheckTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
70060b57cec5SDimitry Andric                 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
70070b57cec5SDimitry Andric                 isa<AtomicCmpXchgInst>(I),
70080b57cec5SDimitry Andric             "This instruction shall not have a TBAA access tag!", &I);
70090b57cec5SDimitry Andric 
70100b57cec5SDimitry Andric   bool IsStructPathTBAA =
70110b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
70120b57cec5SDimitry Andric 
701381ad6265SDimitry Andric   CheckTBAA(IsStructPathTBAA,
701481ad6265SDimitry Andric             "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
701581ad6265SDimitry Andric             &I);
70160b57cec5SDimitry Andric 
70170b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
70180b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
70190b57cec5SDimitry Andric 
70200b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
70210b57cec5SDimitry Andric 
70220b57cec5SDimitry Andric   if (IsNewFormat) {
702381ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
70240b57cec5SDimitry Andric               "Access tag metadata must have either 4 or 5 operands", &I, MD);
70250b57cec5SDimitry Andric   } else {
702681ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() < 5,
70270b57cec5SDimitry Andric               "Struct tag metadata must have either 3 or 4 operands", &I, MD);
70280b57cec5SDimitry Andric   }
70290b57cec5SDimitry Andric 
70300b57cec5SDimitry Andric   // Check the access size field.
70310b57cec5SDimitry Andric   if (IsNewFormat) {
70320b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
70330b57cec5SDimitry Andric         MD->getOperand(3));
703481ad6265SDimitry Andric     CheckTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
70350b57cec5SDimitry Andric   }
70360b57cec5SDimitry Andric 
70370b57cec5SDimitry Andric   // Check the immutability flag.
70380b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
70390b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
70400b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
70410b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
704281ad6265SDimitry Andric     CheckTBAA(IsImmutableCI,
704381ad6265SDimitry Andric               "Immutability tag on struct tag metadata must be a constant", &I,
704481ad6265SDimitry Andric               MD);
704581ad6265SDimitry Andric     CheckTBAA(
70460b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
70470b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
70480b57cec5SDimitry Andric         &I, MD);
70490b57cec5SDimitry Andric   }
70500b57cec5SDimitry Andric 
705181ad6265SDimitry Andric   CheckTBAA(BaseNode && AccessType,
70520b57cec5SDimitry Andric             "Malformed struct tag metadata: base and access-type "
70530b57cec5SDimitry Andric             "should be non-null and point to Metadata nodes",
70540b57cec5SDimitry Andric             &I, MD, BaseNode, AccessType);
70550b57cec5SDimitry Andric 
70560b57cec5SDimitry Andric   if (!IsNewFormat) {
705781ad6265SDimitry Andric     CheckTBAA(isValidScalarTBAANode(AccessType),
70580b57cec5SDimitry Andric               "Access type node must be a valid scalar type", &I, MD,
70590b57cec5SDimitry Andric               AccessType);
70600b57cec5SDimitry Andric   }
70610b57cec5SDimitry Andric 
70620b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
706381ad6265SDimitry Andric   CheckTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
70640b57cec5SDimitry Andric 
70650b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
70660b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
70670b57cec5SDimitry Andric 
70680b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
70690b57cec5SDimitry Andric 
70700b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
70710b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
70720b57cec5SDimitry Andric                                                IsNewFormat)) {
70730b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
70740b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
70750b57cec5SDimitry Andric       return false;
70760b57cec5SDimitry Andric     }
70770b57cec5SDimitry Andric 
70780b57cec5SDimitry Andric     bool Invalid;
70790b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
70800b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
70810b57cec5SDimitry Andric                                                              IsNewFormat);
70820b57cec5SDimitry Andric 
70830b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
70840b57cec5SDimitry Andric     // errors we wanted to print.
70850b57cec5SDimitry Andric     if (Invalid)
70860b57cec5SDimitry Andric       return false;
70870b57cec5SDimitry Andric 
70880b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
70890b57cec5SDimitry Andric 
70900b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
709181ad6265SDimitry Andric       CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access",
70920b57cec5SDimitry Andric                 &I, MD, &Offset);
70930b57cec5SDimitry Andric 
709481ad6265SDimitry Andric     CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
70950b57cec5SDimitry Andric                   (BaseNodeBitWidth == 0 && Offset == 0) ||
70960b57cec5SDimitry Andric                   (IsNewFormat && BaseNodeBitWidth == ~0u),
70970b57cec5SDimitry Andric               "Access bit-width not the same as description bit-width", &I, MD,
70980b57cec5SDimitry Andric               BaseNodeBitWidth, Offset.getBitWidth());
70990b57cec5SDimitry Andric 
71000b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
71010b57cec5SDimitry Andric       break;
71020b57cec5SDimitry Andric   }
71030b57cec5SDimitry Andric 
710481ad6265SDimitry Andric   CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", &I,
710581ad6265SDimitry Andric             MD);
71060b57cec5SDimitry Andric   return true;
71070b57cec5SDimitry Andric }
71080b57cec5SDimitry Andric 
71090b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
71100b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
71110b57cec5SDimitry Andric 
71120b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
71130b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
71140b57cec5SDimitry Andric }
71150b57cec5SDimitry Andric 
71160b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
71170b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
71180b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
71190b57cec5SDimitry Andric   Result Res;
71200b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
71210b57cec5SDimitry Andric   return Res;
71220b57cec5SDimitry Andric }
71230b57cec5SDimitry Andric 
71240b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
71250b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
71260b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
71270b57cec5SDimitry Andric }
71280b57cec5SDimitry Andric 
71290b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
71300b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
71310b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
71320b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
71330b57cec5SDimitry Andric 
71340b57cec5SDimitry Andric   return PreservedAnalyses::all();
71350b57cec5SDimitry Andric }
71360b57cec5SDimitry Andric 
71370b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
71380b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
71390b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
71400b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
71410b57cec5SDimitry Andric 
71420b57cec5SDimitry Andric   return PreservedAnalyses::all();
71430b57cec5SDimitry Andric }
7144