xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision cb14a3fe5122c879eae1fb480ed7ce82a699ddb6)
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"
99480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
1000b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
1010b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
1020b57cec5SDimitry Andric #include "llvm/IR/Module.h"
1030b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
1040b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
1050b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
1060b57cec5SDimitry Andric #include "llvm/IR/Type.h"
1070b57cec5SDimitry Andric #include "llvm/IR/Use.h"
1080b57cec5SDimitry Andric #include "llvm/IR/User.h"
1090b57cec5SDimitry Andric #include "llvm/IR/Value.h"
110480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1110b57cec5SDimitry Andric #include "llvm/Pass.h"
1120b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1130b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1140b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1150b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1160b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
1170b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1180b57cec5SDimitry Andric #include <algorithm>
1190b57cec5SDimitry Andric #include <cassert>
1200b57cec5SDimitry Andric #include <cstdint>
1210b57cec5SDimitry Andric #include <memory>
122bdd1243dSDimitry Andric #include <optional>
1230b57cec5SDimitry Andric #include <string>
1240b57cec5SDimitry Andric #include <utility>
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric using namespace llvm;
1270b57cec5SDimitry Andric 
128e8d8bef9SDimitry Andric static cl::opt<bool> VerifyNoAliasScopeDomination(
129e8d8bef9SDimitry Andric     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
130e8d8bef9SDimitry Andric     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
131e8d8bef9SDimitry Andric              "scopes are not dominating"));
132e8d8bef9SDimitry Andric 
1330b57cec5SDimitry Andric namespace llvm {
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric struct VerifierSupport {
1360b57cec5SDimitry Andric   raw_ostream *OS;
1370b57cec5SDimitry Andric   const Module &M;
1380b57cec5SDimitry Andric   ModuleSlotTracker MST;
1398bcb0991SDimitry Andric   Triple TT;
1400b57cec5SDimitry Andric   const DataLayout &DL;
1410b57cec5SDimitry Andric   LLVMContext &Context;
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1440b57cec5SDimitry Andric   bool Broken = false;
1450b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1460b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1470b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1480b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
1518bcb0991SDimitry Andric       : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
1528bcb0991SDimitry Andric         Context(M.getContext()) {}
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric private:
1550b57cec5SDimitry Andric   void Write(const Module *M) {
1560b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   void Write(const Value *V) {
1600b57cec5SDimitry Andric     if (V)
1610b57cec5SDimitry Andric       Write(*V);
1620b57cec5SDimitry Andric   }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   void Write(const Value &V) {
1650b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1660b57cec5SDimitry Andric       V.print(*OS, MST);
1670b57cec5SDimitry Andric       *OS << '\n';
1680b57cec5SDimitry Andric     } else {
1690b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1700b57cec5SDimitry Andric       *OS << '\n';
1710b57cec5SDimitry Andric     }
1720b57cec5SDimitry Andric   }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   void Write(const Metadata *MD) {
1750b57cec5SDimitry Andric     if (!MD)
1760b57cec5SDimitry Andric       return;
1770b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
1780b57cec5SDimitry Andric     *OS << '\n';
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
1820b57cec5SDimitry Andric     Write(MD.get());
1830b57cec5SDimitry Andric   }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
1860b57cec5SDimitry Andric     if (!NMD)
1870b57cec5SDimitry Andric       return;
1880b57cec5SDimitry Andric     NMD->print(*OS, MST);
1890b57cec5SDimitry Andric     *OS << '\n';
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   void Write(Type *T) {
1930b57cec5SDimitry Andric     if (!T)
1940b57cec5SDimitry Andric       return;
1950b57cec5SDimitry Andric     *OS << ' ' << *T;
1960b57cec5SDimitry Andric   }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   void Write(const Comdat *C) {
1990b57cec5SDimitry Andric     if (!C)
2000b57cec5SDimitry Andric       return;
2010b57cec5SDimitry Andric     *OS << *C;
2020b57cec5SDimitry Andric   }
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   void Write(const APInt *AI) {
2050b57cec5SDimitry Andric     if (!AI)
2060b57cec5SDimitry Andric       return;
2070b57cec5SDimitry Andric     *OS << *AI << '\n';
2080b57cec5SDimitry Andric   }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
2110b57cec5SDimitry Andric 
212fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
213fe6060f1SDimitry Andric   void Write(const Attribute *A) {
214fe6060f1SDimitry Andric     if (!A)
215fe6060f1SDimitry Andric       return;
216fe6060f1SDimitry Andric     *OS << A->getAsString() << '\n';
217fe6060f1SDimitry Andric   }
218fe6060f1SDimitry Andric 
219fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
220fe6060f1SDimitry Andric   void Write(const AttributeSet *AS) {
221fe6060f1SDimitry Andric     if (!AS)
222fe6060f1SDimitry Andric       return;
223fe6060f1SDimitry Andric     *OS << AS->getAsString() << '\n';
224fe6060f1SDimitry Andric   }
225fe6060f1SDimitry Andric 
226fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
227fe6060f1SDimitry Andric   void Write(const AttributeList *AL) {
228fe6060f1SDimitry Andric     if (!AL)
229fe6060f1SDimitry Andric       return;
230fe6060f1SDimitry Andric     AL->print(*OS);
231fe6060f1SDimitry Andric   }
232fe6060f1SDimitry Andric 
23306c3fb27SDimitry Andric   void Write(Printable P) { *OS << P << '\n'; }
23406c3fb27SDimitry Andric 
2350b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
2360b57cec5SDimitry Andric     for (const T &V : Vs)
2370b57cec5SDimitry Andric       Write(V);
2380b57cec5SDimitry Andric   }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2410b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2420b57cec5SDimitry Andric     Write(V1);
2430b57cec5SDimitry Andric     WriteTs(Vs...);
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric public:
2490b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2500b57cec5SDimitry Andric   ///
2510b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2520b57cec5SDimitry Andric   /// something is not correct.
2530b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2540b57cec5SDimitry Andric     if (OS)
2550b57cec5SDimitry Andric       *OS << Message << '\n';
2560b57cec5SDimitry Andric     Broken = true;
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   /// A check failed (with values to print).
2600b57cec5SDimitry Andric   ///
2610b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2620b57cec5SDimitry Andric   /// breakpoint on.
2630b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2640b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2650b57cec5SDimitry Andric     CheckFailed(Message);
2660b57cec5SDimitry Andric     if (OS)
2670b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2680b57cec5SDimitry Andric   }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   /// A debug info check failed.
2710b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
2720b57cec5SDimitry Andric     if (OS)
2730b57cec5SDimitry Andric       *OS << Message << '\n';
2740b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
2750b57cec5SDimitry Andric     BrokenDebugInfo = true;
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
2790b57cec5SDimitry Andric   template <typename T1, typename... Ts>
2800b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
2810b57cec5SDimitry Andric                             const Ts &... Vs) {
2820b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
2830b57cec5SDimitry Andric     if (OS)
2840b57cec5SDimitry Andric       WriteTs(V1, Vs...);
2850b57cec5SDimitry Andric   }
2860b57cec5SDimitry Andric };
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric } // namespace llvm
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric namespace {
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
2930b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
2940b57cec5SDimitry Andric 
29581ad6265SDimitry Andric   // ISD::ArgFlagsTy::MemAlign only have 4 bits for alignment, so
29681ad6265SDimitry Andric   // the alignment size should not exceed 2^15. Since encode(Align)
29781ad6265SDimitry Andric   // would plus the shift value by 1, the alignment size should
29881ad6265SDimitry Andric   // not exceed 2^14, otherwise it can NOT be properly lowered
29981ad6265SDimitry Andric   // in backend.
30081ad6265SDimitry Andric   static constexpr unsigned ParamMaxAlignment = 1 << 14;
3010b57cec5SDimitry Andric   DominatorTree DT;
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
3040b57cec5SDimitry Andric   /// instructions we have seen so far.
3050b57cec5SDimitry Andric   ///
3060b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
3070b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
3080b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
3110b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
3140b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
3170b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   /// The result type for a landingpad.
3200b57cec5SDimitry Andric   Type *LandingPadResultTy;
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
3230b57cec5SDimitry Andric   /// already.
3240b57cec5SDimitry Andric   bool SawFrameEscape;
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
3270b57cec5SDimitry Andric   bool HasDebugInfo = false;
3280b57cec5SDimitry Andric 
329e8d8bef9SDimitry Andric   /// The current source language.
330e8d8bef9SDimitry Andric   dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user;
331e8d8bef9SDimitry Andric 
3320b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
3330b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
3340b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
3370b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
3380b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
3390b57cec5SDimitry Andric 
34006c3fb27SDimitry Andric   /// Cache which blocks are in which funclet, if an EH funclet personality is
34106c3fb27SDimitry Andric   /// in use. Otherwise empty.
34206c3fb27SDimitry Andric   DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
34306c3fb27SDimitry Andric 
3440b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
3450b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
3480b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
3490b57cec5SDimitry Andric 
350fe6060f1SDimitry Andric   /// Cache of attribute lists verified.
351fe6060f1SDimitry Andric   SmallPtrSet<const void *, 32> AttributeListsVisited;
352fe6060f1SDimitry Andric 
3530b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3540b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3550b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3560b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3570b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3600b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3635f757f3fSDimitry Andric   ConvergenceVerifier ConvergenceVerifyHelper;
3640b57cec5SDimitry Andric 
365e8d8bef9SDimitry Andric   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
366e8d8bef9SDimitry Andric 
3670b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric public:
3700b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3710b57cec5SDimitry Andric                     const Module &M)
3720b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3730b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3740b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   bool verify(const Function &F) {
3800b57cec5SDimitry Andric     assert(F.getParent() == &M &&
3810b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
3840b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
3850b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
3860b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
3870b57cec5SDimitry Andric     // this code outside of a pass manager.
3880b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
3890b57cec5SDimitry Andric     if (!F.empty())
3900b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
3930b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
3940b57cec5SDimitry Andric         continue;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric       if (OS) {
3970b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
3980b57cec5SDimitry Andric             << "' does not have terminator!\n";
3990b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
4000b57cec5SDimitry Andric         *OS << "\n";
4010b57cec5SDimitry Andric       }
4020b57cec5SDimitry Andric       return false;
4030b57cec5SDimitry Andric     }
4040b57cec5SDimitry Andric 
4055f757f3fSDimitry Andric     auto FailureCB = [this](const Twine &Message) {
4065f757f3fSDimitry Andric       this->CheckFailed(Message);
4075f757f3fSDimitry Andric     };
4085f757f3fSDimitry Andric     ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
4095f757f3fSDimitry Andric 
4100b57cec5SDimitry Andric     Broken = false;
4110b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
4120b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
4130b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
4145f757f3fSDimitry Andric 
4155f757f3fSDimitry Andric     if (ConvergenceVerifyHelper.sawTokens())
4165f757f3fSDimitry Andric       ConvergenceVerifyHelper.verify(DT);
4175f757f3fSDimitry Andric 
4180b57cec5SDimitry Andric     InstsInThisBlock.clear();
4190b57cec5SDimitry Andric     DebugFnArgs.clear();
4200b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
4210b57cec5SDimitry Andric     SawFrameEscape = false;
4220b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
423e8d8bef9SDimitry Andric     verifyNoAliasScopeDecl();
424e8d8bef9SDimitry Andric     NoAliasScopeDecls.clear();
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric     return !Broken;
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
4300b57cec5SDimitry Andric   bool verify() {
4310b57cec5SDimitry Andric     Broken = false;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
4340b57cec5SDimitry Andric     for (const Function &F : M)
4350b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
4360b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
4390b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
4400b57cec5SDimitry Andric     verifyFrameRecoverIndices();
4410b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
4420b57cec5SDimitry Andric       visitGlobalVariable(GV);
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
4450b57cec5SDimitry Andric       visitGlobalAlias(GA);
4460b57cec5SDimitry Andric 
447349cc55cSDimitry Andric     for (const GlobalIFunc &GI : M.ifuncs())
448349cc55cSDimitry Andric       visitGlobalIFunc(GI);
449349cc55cSDimitry Andric 
4500b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
4510b57cec5SDimitry Andric       visitNamedMDNode(NMD);
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
4540b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
4550b57cec5SDimitry Andric 
456349cc55cSDimitry Andric     visitModuleFlags();
457349cc55cSDimitry Andric     visitModuleIdents();
458349cc55cSDimitry Andric     visitModuleCommandLines();
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric     verifyCompileUnits();
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
4630b57cec5SDimitry Andric     DISubprogramAttachments.clear();
4640b57cec5SDimitry Andric     return !Broken;
4650b57cec5SDimitry Andric   }
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric private:
4685ffd83dbSDimitry Andric   /// Whether a metadata node is allowed to be, or contain, a DILocation.
4695ffd83dbSDimitry Andric   enum class AreDebugLocsAllowed { No, Yes };
4705ffd83dbSDimitry Andric 
4710b57cec5SDimitry Andric   // Verification methods...
4720b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4730b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4740b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
475349cc55cSDimitry Andric   void visitGlobalIFunc(const GlobalIFunc &GI);
4760b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
4770b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
4780b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
4790b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
4805ffd83dbSDimitry Andric   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
4810b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
4820b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
4835f757f3fSDimitry Andric   void visitDIArgList(const DIArgList &AL, Function *F);
4840b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
485349cc55cSDimitry Andric   void visitModuleIdents();
486349cc55cSDimitry Andric   void visitModuleCommandLines();
487349cc55cSDimitry Andric   void visitModuleFlags();
4880b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
4890b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
4900b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
4910b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
4920b57cec5SDimitry Andric   void visitFunction(const Function &F);
4930b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
49406c3fb27SDimitry Andric   void verifyRangeMetadata(const Value &V, const MDNode *Range, Type *Ty,
49506c3fb27SDimitry Andric                            bool IsAbsoluteSymbol);
4960b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
4970b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
4988bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
499fcaf7f86SDimitry Andric   void visitCallStackMetadata(MDNode *MD);
500fcaf7f86SDimitry Andric   void visitMemProfMetadata(Instruction &I, MDNode *MD);
501fcaf7f86SDimitry Andric   void visitCallsiteMetadata(Instruction &I, MDNode *MD);
502bdd1243dSDimitry Andric   void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
503e8d8bef9SDimitry Andric   void visitAnnotationMetadata(MDNode *Annotation);
504349cc55cSDimitry Andric   void visitAliasScopeMetadata(const MDNode *MD);
505349cc55cSDimitry Andric   void visitAliasScopeListMetadata(const MDNode *MD);
50681ad6265SDimitry Andric   void visitAccessGroupMetadata(const MDNode *MD);
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
5090b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
5100b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
5110b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
5120b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
5130b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
5140b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // InstVisitor overrides...
5190b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
5200b57cec5SDimitry Andric   void visit(Instruction &I);
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
5230b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
5240b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
5250b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
5260b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
5270b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
5280b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
5290b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
5300b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
5310b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
5320b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
5330b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
5340b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
5350b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
5360b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
5370b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
5380b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
5390b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
5400b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
5410b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
5420b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
5430b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
5440b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
5450b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
5460b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
5470b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
5480b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
5490b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
5500b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
5510b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
5520b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
5530b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
5540b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
5550b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
5560b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
5570b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
5580b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
5590b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
5600b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
5610b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
5620b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
56381ad6265SDimitry Andric   void visitVPIntrinsic(VPIntrinsic &VPI);
5640b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
5650b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
5660b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
5670b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
5680b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
5690b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
5700b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
5710b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
5720b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
5730b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
5740b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
5750b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
5760b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
5770b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
5780b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
5790b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
5800b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
5830b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
5840eae32dcSDimitry Andric   void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
5850b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
5860b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
587fe6060f1SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
5880b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
589fe6060f1SDimitry Andric   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
590fe6060f1SDimitry Andric                                     const Value *V);
5910b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
59204eeddc0SDimitry Andric                            const Value *V, bool IsIntrinsic, bool IsInlineAsm);
5930b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
5960b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
59704eeddc0SDimitry Andric   void verifyInlineAsmCall(const CallBase &Call);
5980b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
5990b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
6000b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
6030b57cec5SDimitry Andric   template <typename ValueOrMetadata>
6040b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
6050b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
6060b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
6070b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
6088bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric   /// Module-level debug info verification...
6110b57cec5SDimitry Andric   void verifyCompileUnits();
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
6140b57cec5SDimitry Andric   /// declarations share the same calling convention.
6150b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
6160b57cec5SDimitry Andric 
617349cc55cSDimitry Andric   void verifyAttachedCallBundle(const CallBase &Call,
618349cc55cSDimitry Andric                                 const OperandBundleUse &BU);
619349cc55cSDimitry Andric 
620e8d8bef9SDimitry Andric   /// Verify the llvm.experimental.noalias.scope.decl declarations
621e8d8bef9SDimitry Andric   void verifyNoAliasScopeDecl();
6220b57cec5SDimitry Andric };
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric } // end anonymous namespace
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
62781ad6265SDimitry Andric #define Check(C, ...)                                                          \
62881ad6265SDimitry Andric   do {                                                                         \
62981ad6265SDimitry Andric     if (!(C)) {                                                                \
63081ad6265SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
63181ad6265SDimitry Andric       return;                                                                  \
63281ad6265SDimitry Andric     }                                                                          \
63381ad6265SDimitry Andric   } while (false)
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
6360b57cec5SDimitry Andric /// an error message.
63781ad6265SDimitry Andric #define CheckDI(C, ...)                                                        \
63881ad6265SDimitry Andric   do {                                                                         \
63981ad6265SDimitry Andric     if (!(C)) {                                                                \
64081ad6265SDimitry Andric       DebugInfoCheckFailed(__VA_ARGS__);                                       \
64181ad6265SDimitry Andric       return;                                                                  \
64281ad6265SDimitry Andric     }                                                                          \
64381ad6265SDimitry Andric   } while (false)
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
6460b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
64781ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Operand is null", &I);
6480b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510eae32dcSDimitry Andric // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
6520b57cec5SDimitry Andric static void forEachUser(const Value *User,
6530b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
6540b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
6550b57cec5SDimitry Andric   if (!Visited.insert(User).second)
6560b57cec5SDimitry Andric     return;
6570eae32dcSDimitry Andric 
6580eae32dcSDimitry Andric   SmallVector<const Value *> WorkList;
6590eae32dcSDimitry Andric   append_range(WorkList, User->materialized_users());
6600eae32dcSDimitry Andric   while (!WorkList.empty()) {
6610eae32dcSDimitry Andric    const Value *Cur = WorkList.pop_back_val();
6620eae32dcSDimitry Andric     if (!Visited.insert(Cur).second)
6630eae32dcSDimitry Andric       continue;
6640eae32dcSDimitry Andric     if (Callback(Cur))
6650eae32dcSDimitry Andric       append_range(WorkList, Cur->materialized_users());
6660eae32dcSDimitry Andric   }
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
67081ad6265SDimitry Andric   Check(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
6710b57cec5SDimitry Andric         "Global is external, but doesn't have external or weak linkage!", &GV);
6720b57cec5SDimitry Andric 
6730eae32dcSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
6740eae32dcSDimitry Andric 
6750eae32dcSDimitry Andric     if (MaybeAlign A = GO->getAlign()) {
67681ad6265SDimitry Andric       Check(A->value() <= Value::MaximumAlignment,
6775ffd83dbSDimitry Andric             "huge alignment values are unsupported", GO);
6780eae32dcSDimitry Andric     }
67906c3fb27SDimitry Andric 
68006c3fb27SDimitry Andric     if (const MDNode *Associated =
68106c3fb27SDimitry Andric             GO->getMetadata(LLVMContext::MD_associated)) {
68206c3fb27SDimitry Andric       Check(Associated->getNumOperands() == 1,
68306c3fb27SDimitry Andric             "associated metadata must have one operand", &GV, Associated);
68406c3fb27SDimitry Andric       const Metadata *Op = Associated->getOperand(0).get();
68506c3fb27SDimitry Andric       Check(Op, "associated metadata must have a global value", GO, Associated);
68606c3fb27SDimitry Andric 
68706c3fb27SDimitry Andric       const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
68806c3fb27SDimitry Andric       Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
68906c3fb27SDimitry Andric       if (VM) {
69006c3fb27SDimitry Andric         Check(isa<PointerType>(VM->getValue()->getType()),
69106c3fb27SDimitry Andric               "associated value must be pointer typed", GV, Associated);
69206c3fb27SDimitry Andric 
69306c3fb27SDimitry Andric         const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
69406c3fb27SDimitry Andric         Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
69506c3fb27SDimitry Andric               "associated metadata must point to a GlobalObject", GO, Stripped);
69606c3fb27SDimitry Andric         Check(Stripped != GO,
69706c3fb27SDimitry Andric               "global values should not associate to themselves", GO,
69806c3fb27SDimitry Andric               Associated);
6990eae32dcSDimitry Andric       }
70006c3fb27SDimitry Andric     }
70106c3fb27SDimitry Andric 
70206c3fb27SDimitry Andric     // FIXME: Why is getMetadata on GlobalValue protected?
70306c3fb27SDimitry Andric     if (const MDNode *AbsoluteSymbol =
70406c3fb27SDimitry Andric             GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
70506c3fb27SDimitry Andric       verifyRangeMetadata(*GO, AbsoluteSymbol, DL.getIntPtrType(GO->getType()),
70606c3fb27SDimitry Andric                           true);
70706c3fb27SDimitry Andric     }
70806c3fb27SDimitry Andric   }
70906c3fb27SDimitry Andric 
71081ad6265SDimitry Andric   Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
7110b57cec5SDimitry Andric         "Only global variables can have appending linkage!", &GV);
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
7140b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
71581ad6265SDimitry Andric     Check(GVar && GVar->getValueType()->isArrayTy(),
7160b57cec5SDimitry Andric           "Only global arrays can have appending linkage!", GVar);
7170b57cec5SDimitry Andric   }
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
72081ad6265SDimitry Andric     Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
7210b57cec5SDimitry Andric 
722bdd1243dSDimitry Andric   if (GV.hasDLLExportStorageClass()) {
723bdd1243dSDimitry Andric     Check(!GV.hasHiddenVisibility(),
724bdd1243dSDimitry Andric           "dllexport GlobalValue must have default or protected visibility",
725bdd1243dSDimitry Andric           &GV);
726bdd1243dSDimitry Andric   }
7270b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
728bdd1243dSDimitry Andric     Check(GV.hasDefaultVisibility(),
729bdd1243dSDimitry Andric           "dllimport GlobalValue must have default visibility", &GV);
73081ad6265SDimitry Andric     Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
73181ad6265SDimitry Andric           &GV);
7320b57cec5SDimitry Andric 
73381ad6265SDimitry Andric     Check((GV.isDeclaration() &&
734e8d8bef9SDimitry Andric            (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
7350b57cec5SDimitry Andric               GV.hasAvailableExternallyLinkage(),
7360b57cec5SDimitry Andric           "Global is marked as dllimport, but not external", &GV);
7370b57cec5SDimitry Andric   }
7380b57cec5SDimitry Andric 
7395ffd83dbSDimitry Andric   if (GV.isImplicitDSOLocal())
74081ad6265SDimitry Andric     Check(GV.isDSOLocal(),
7415ffd83dbSDimitry Andric           "GlobalValue with local linkage or non-default "
7425ffd83dbSDimitry Andric           "visibility must be dso_local!",
7430b57cec5SDimitry Andric           &GV);
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
7460b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
7470b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
7480b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
7490b57cec5SDimitry Andric                     I);
7500b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
7510b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
7520b57cec5SDimitry Andric                     I->getParent()->getParent(),
7530b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
7540b57cec5SDimitry Andric       return false;
7550b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
7560b57cec5SDimitry Andric       if (F->getParent() != &M)
7570b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
7580b57cec5SDimitry Andric                     F, F->getParent());
7590b57cec5SDimitry Andric       return false;
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric     return true;
7620b57cec5SDimitry Andric   });
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
7660b57cec5SDimitry Andric   if (GV.hasInitializer()) {
76781ad6265SDimitry Andric     Check(GV.getInitializer()->getType() == GV.getValueType(),
7680b57cec5SDimitry Andric           "Global variable initializer type does not match global "
7690b57cec5SDimitry Andric           "variable type!",
7700b57cec5SDimitry Andric           &GV);
7710b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
7720b57cec5SDimitry Andric     // cannot be constant.
7730b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
77481ad6265SDimitry Andric       Check(GV.getInitializer()->isNullValue(),
7750b57cec5SDimitry Andric             "'common' global must have a zero initializer!", &GV);
77681ad6265SDimitry Andric       Check(!GV.isConstant(), "'common' global may not be marked constant!",
7770b57cec5SDimitry Andric             &GV);
77881ad6265SDimitry Andric       Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
7790b57cec5SDimitry Andric     }
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
7830b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
78481ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
7850b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
78606c3fb27SDimitry Andric     Check(GV.materialized_use_empty(),
78706c3fb27SDimitry Andric           "invalid uses of intrinsic global variable", &GV);
78806c3fb27SDimitry Andric 
7890b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
7900b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
7910b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
7920b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
7930b57cec5SDimitry Andric       PointerType *FuncPtrTy =
7945f757f3fSDimitry Andric           PointerType::get(Context, DL.getProgramAddressSpace());
79581ad6265SDimitry Andric       Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
7960b57cec5SDimitry Andric                 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
7970b57cec5SDimitry Andric                 STy->getTypeAtIndex(1) == FuncPtrTy,
7980b57cec5SDimitry Andric             "wrong type for intrinsic global variable", &GV);
79981ad6265SDimitry Andric       Check(STy->getNumElements() == 3,
8000b57cec5SDimitry Andric             "the third field of the element type is mandatory, "
801bdd1243dSDimitry Andric             "specify ptr null to migrate from the obsoleted 2-field form");
8020b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
80306c3fb27SDimitry Andric       Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
80406c3fb27SDimitry Andric             &GV);
8050b57cec5SDimitry Andric     }
8060b57cec5SDimitry Andric   }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
8090b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
81081ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
8110b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
81206c3fb27SDimitry Andric     Check(GV.materialized_use_empty(),
81306c3fb27SDimitry Andric           "invalid uses of intrinsic global variable", &GV);
81406c3fb27SDimitry Andric 
8150b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
8160b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
8170b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
81881ad6265SDimitry Andric       Check(PTy, "wrong type for intrinsic global variable", &GV);
8190b57cec5SDimitry Andric       if (GV.hasInitializer()) {
8200b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
8210b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
82281ad6265SDimitry Andric         Check(InitArray, "wrong initalizer for intrinsic global variable",
8230b57cec5SDimitry Andric               Init);
8240b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
8258bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
82681ad6265SDimitry Andric           Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
8270b57cec5SDimitry Andric                     isa<GlobalAlias>(V),
8280eae32dcSDimitry Andric                 Twine("invalid ") + GV.getName() + " member", V);
82981ad6265SDimitry Andric           Check(V->hasName(),
8300eae32dcSDimitry Andric                 Twine("members of ") + GV.getName() + " must be named", V);
8310b57cec5SDimitry Andric         }
8320b57cec5SDimitry Andric       }
8330b57cec5SDimitry Andric     }
8340b57cec5SDimitry Andric   }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   // Visit any debug info attachments.
8370b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
8380b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
8390b57cec5SDimitry Andric   for (auto *MD : MDs) {
8400b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
8410b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
8420b57cec5SDimitry Andric     else
84381ad6265SDimitry Andric       CheckDI(false, "!dbg attachment of global variable must be a "
8440b57cec5SDimitry Andric                      "DIGlobalVariableExpression");
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
8485f757f3fSDimitry Andric   // the runtime size.
8495f757f3fSDimitry Andric   Check(!GV.getValueType()->isScalableTy(),
8505f757f3fSDimitry Andric         "Globals cannot contain scalable types", &GV);
851e8d8bef9SDimitry Andric 
852bdd1243dSDimitry Andric   // Check if it's a target extension type that disallows being used as a
853bdd1243dSDimitry Andric   // global.
854bdd1243dSDimitry Andric   if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
855bdd1243dSDimitry Andric     Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
856bdd1243dSDimitry Andric           "Global @" + GV.getName() + " has illegal target extension type",
857bdd1243dSDimitry Andric           TTy);
858bdd1243dSDimitry Andric 
8590b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
8600b57cec5SDimitry Andric     visitGlobalValue(GV);
8610b57cec5SDimitry Andric     return;
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
8650b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   visitGlobalValue(GV);
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
8710b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
8720b57cec5SDimitry Andric   Visited.insert(&GA);
8730b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
8770b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
878bdd1243dSDimitry Andric   if (GA.hasAvailableExternallyLinkage()) {
879bdd1243dSDimitry Andric     Check(isa<GlobalValue>(C) &&
880bdd1243dSDimitry Andric               cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
881bdd1243dSDimitry Andric           "available_externally alias must point to available_externally "
882bdd1243dSDimitry Andric           "global value",
883bdd1243dSDimitry Andric           &GA);
884bdd1243dSDimitry Andric   }
8850b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
886bdd1243dSDimitry Andric     if (!GA.hasAvailableExternallyLinkage()) {
88781ad6265SDimitry Andric       Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
8880b57cec5SDimitry Andric             &GA);
889bdd1243dSDimitry Andric     }
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
89281ad6265SDimitry Andric       Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
8930b57cec5SDimitry Andric 
89481ad6265SDimitry Andric       Check(!GA2->isInterposable(),
89581ad6265SDimitry Andric             "Alias cannot point to an interposable alias", &GA);
8960b57cec5SDimitry Andric     } else {
8970b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
8980b57cec5SDimitry Andric       // Do not recurse into global initializers.
8990b57cec5SDimitry Andric       return;
9000b57cec5SDimitry Andric     }
9010b57cec5SDimitry Andric   }
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
9040b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
9070b57cec5SDimitry Andric     Value *V = &*U;
9080b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
9090b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
9100b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
9110b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
9120b57cec5SDimitry Andric   }
9130b57cec5SDimitry Andric }
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
91681ad6265SDimitry Andric   Check(GlobalAlias::isValidLinkage(GA.getLinkage()),
9170b57cec5SDimitry Andric         "Alias should have private, internal, linkonce, weak, linkonce_odr, "
918bdd1243dSDimitry Andric         "weak_odr, external, or available_externally linkage!",
9190b57cec5SDimitry Andric         &GA);
9200b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
92181ad6265SDimitry Andric   Check(Aliasee, "Aliasee cannot be NULL!", &GA);
92281ad6265SDimitry Andric   Check(GA.getType() == Aliasee->getType(),
9230b57cec5SDimitry Andric         "Alias and aliasee types should match!", &GA);
9240b57cec5SDimitry Andric 
92581ad6265SDimitry Andric   Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
9260b57cec5SDimitry Andric         "Aliasee should be either GlobalValue or ConstantExpr", &GA);
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   visitGlobalValue(GA);
9310b57cec5SDimitry Andric }
9320b57cec5SDimitry Andric 
933349cc55cSDimitry Andric void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
93481ad6265SDimitry Andric   Check(GlobalIFunc::isValidLinkage(GI.getLinkage()),
93581ad6265SDimitry Andric         "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
93681ad6265SDimitry Andric         "weak_odr, or external linkage!",
93781ad6265SDimitry Andric         &GI);
938349cc55cSDimitry Andric   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
93981ad6265SDimitry Andric   // is a Function definition.
940349cc55cSDimitry Andric   const Function *Resolver = GI.getResolverFunction();
94181ad6265SDimitry Andric   Check(Resolver, "IFunc must have a Function resolver", &GI);
94281ad6265SDimitry Andric   Check(!Resolver->isDeclarationForLinker(),
94381ad6265SDimitry Andric         "IFunc resolver must be a definition", &GI);
944349cc55cSDimitry Andric 
945349cc55cSDimitry Andric   // Check that the immediate resolver operand (prior to any bitcasts) has the
94681ad6265SDimitry Andric   // correct type.
947349cc55cSDimitry Andric   const Type *ResolverTy = GI.getResolver()->getType();
948bdd1243dSDimitry Andric 
949bdd1243dSDimitry Andric   Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
950bdd1243dSDimitry Andric         "IFunc resolver must return a pointer", &GI);
951bdd1243dSDimitry Andric 
952349cc55cSDimitry Andric   const Type *ResolverFuncTy =
953349cc55cSDimitry Andric       GlobalIFunc::getResolverFunctionType(GI.getValueType());
954bdd1243dSDimitry Andric   Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
955349cc55cSDimitry Andric         "IFunc resolver has incorrect type", &GI);
956349cc55cSDimitry Andric }
957349cc55cSDimitry Andric 
9580b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
9590b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
9600b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
9615f757f3fSDimitry Andric   if (NMD.getName().starts_with("llvm.dbg."))
96281ad6265SDimitry Andric     CheckDI(NMD.getName() == "llvm.dbg.cu",
96381ad6265SDimitry Andric             "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
9640b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
9650b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
96681ad6265SDimitry Andric       CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric     if (!MD)
9690b57cec5SDimitry Andric       continue;
9700b57cec5SDimitry Andric 
9715ffd83dbSDimitry Andric     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
9720b57cec5SDimitry Andric   }
9730b57cec5SDimitry Andric }
9740b57cec5SDimitry Andric 
9755ffd83dbSDimitry Andric void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
9760b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
9770b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
9780b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
9790b57cec5SDimitry Andric     return;
9800b57cec5SDimitry Andric 
98181ad6265SDimitry Andric   Check(&MD.getContext() == &Context,
982fe6060f1SDimitry Andric         "MDNode context does not match Module context!", &MD);
983fe6060f1SDimitry Andric 
9840b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
9850b57cec5SDimitry Andric   default:
9860b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
9870b57cec5SDimitry Andric   case Metadata::MDTupleKind:
9880b57cec5SDimitry Andric     break;
9890b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
9900b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
9910b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
9920b57cec5SDimitry Andric     break;
9930b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
9940b57cec5SDimitry Andric   }
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
9970b57cec5SDimitry Andric     if (!Op)
9980b57cec5SDimitry Andric       continue;
99981ad6265SDimitry Andric     Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
10000b57cec5SDimitry Andric           &MD, Op);
100181ad6265SDimitry Andric     CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
10025ffd83dbSDimitry Andric             "DILocation not allowed within this metadata node", &MD, Op);
10030b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
10045ffd83dbSDimitry Andric       visitMDNode(*N, AllowLocs);
10050b57cec5SDimitry Andric       continue;
10060b57cec5SDimitry Andric     }
10070b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
10080b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
10090b57cec5SDimitry Andric       continue;
10100b57cec5SDimitry Andric     }
10110b57cec5SDimitry Andric   }
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
101481ad6265SDimitry Andric   Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
101581ad6265SDimitry Andric   Check(MD.isResolved(), "All nodes should be resolved!", &MD);
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
101981ad6265SDimitry Andric   Check(MD.getValue(), "Expected valid value", &MD);
102081ad6265SDimitry Andric   Check(!MD.getValue()->getType()->isMetadataTy(),
10210b57cec5SDimitry Andric         "Unexpected metadata round-trip through values", &MD, MD.getValue());
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
10240b57cec5SDimitry Andric   if (!L)
10250b57cec5SDimitry Andric     return;
10260b57cec5SDimitry Andric 
102781ad6265SDimitry Andric   Check(F, "function-local metadata used outside a function", L);
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
10300b57cec5SDimitry Andric   // function that we expect.
10310b57cec5SDimitry Andric   Function *ActualF = nullptr;
10320b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
103381ad6265SDimitry Andric     Check(I->getParent(), "function-local metadata not in basic block", L, I);
10340b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
10350b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
10360b57cec5SDimitry Andric     ActualF = BB->getParent();
10370b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
10380b57cec5SDimitry Andric     ActualF = A->getParent();
10390b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
10400b57cec5SDimitry Andric 
104181ad6265SDimitry Andric   Check(ActualF == F, "function-local metadata used in wrong function", L);
10420b57cec5SDimitry Andric }
10430b57cec5SDimitry Andric 
10445f757f3fSDimitry Andric void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
10455f757f3fSDimitry Andric   for (const ValueAsMetadata *VAM : AL.getArgs())
10465f757f3fSDimitry Andric     visitValueAsMetadata(*VAM, F);
10475f757f3fSDimitry Andric }
10485f757f3fSDimitry Andric 
10490b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
10500b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
10510b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
10525ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::No);
10530b57cec5SDimitry Andric     return;
10540b57cec5SDimitry Andric   }
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
10570b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
10580b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
10590b57cec5SDimitry Andric     return;
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
10620b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
10635f757f3fSDimitry Andric 
10645f757f3fSDimitry Andric   if (auto *AL = dyn_cast<DIArgList>(MD))
10655f757f3fSDimitry Andric     visitDIArgList(*AL, F);
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
10690b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
10700b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
107381ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
10740b57cec5SDimitry Andric           "location requires a valid scope", &N, N.getRawScope());
10750b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
107681ad6265SDimitry Andric     CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
10770b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
107881ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
10790b57cec5SDimitry Andric }
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
108281ad6265SDimitry Andric   CheckDI(N.getTag(), "invalid tag", &N);
10830b57cec5SDimitry Andric }
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
10860b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
108781ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
10880b57cec5SDimitry Andric }
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
109181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1092e8d8bef9SDimitry Andric   bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang);
109381ad6265SDimitry Andric   CheckDI(HasAssumedSizedArraySupport || N.getRawCountNode() ||
1094e8d8bef9SDimitry Andric               N.getRawUpperBound(),
10955ffd83dbSDimitry Andric           "Subrange must contain count or upperBound", &N);
109681ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
10975ffd83dbSDimitry Andric           "Subrange can have any one of count or upperBound", &N);
1098fe6060f1SDimitry Andric   auto *CBound = N.getRawCountNode();
109981ad6265SDimitry Andric   CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1100fe6060f1SDimitry Andric               isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1101fe6060f1SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
11020b57cec5SDimitry Andric   auto Count = N.getCount();
110306c3fb27SDimitry Andric   CheckDI(!Count || !isa<ConstantInt *>(Count) ||
110406c3fb27SDimitry Andric               cast<ConstantInt *>(Count)->getSExtValue() >= -1,
11050b57cec5SDimitry Andric           "invalid subrange count", &N);
11065ffd83dbSDimitry Andric   auto *LBound = N.getRawLowerBound();
110781ad6265SDimitry Andric   CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
11085ffd83dbSDimitry Andric               isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
11095ffd83dbSDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
11105ffd83dbSDimitry Andric           &N);
11115ffd83dbSDimitry Andric   auto *UBound = N.getRawUpperBound();
111281ad6265SDimitry Andric   CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
11135ffd83dbSDimitry Andric               isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
11145ffd83dbSDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
11155ffd83dbSDimitry Andric           &N);
11165ffd83dbSDimitry Andric   auto *Stride = N.getRawStride();
111781ad6265SDimitry Andric   CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
11185ffd83dbSDimitry Andric               isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
11195ffd83dbSDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
11200b57cec5SDimitry Andric }
11210b57cec5SDimitry Andric 
1122e8d8bef9SDimitry Andric void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
112381ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
112481ad6265SDimitry Andric   CheckDI(N.getRawCountNode() || N.getRawUpperBound(),
1125e8d8bef9SDimitry Andric           "GenericSubrange must contain count or upperBound", &N);
112681ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1127e8d8bef9SDimitry Andric           "GenericSubrange can have any one of count or upperBound", &N);
1128e8d8bef9SDimitry Andric   auto *CBound = N.getRawCountNode();
112981ad6265SDimitry Andric   CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1130e8d8bef9SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
1131e8d8bef9SDimitry Andric   auto *LBound = N.getRawLowerBound();
113281ad6265SDimitry Andric   CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
113381ad6265SDimitry Andric   CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1134e8d8bef9SDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
1135e8d8bef9SDimitry Andric           &N);
1136e8d8bef9SDimitry Andric   auto *UBound = N.getRawUpperBound();
113781ad6265SDimitry Andric   CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1138e8d8bef9SDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
1139e8d8bef9SDimitry Andric           &N);
1140e8d8bef9SDimitry Andric   auto *Stride = N.getRawStride();
114181ad6265SDimitry Andric   CheckDI(Stride, "GenericSubrange must contain stride", &N);
114281ad6265SDimitry Andric   CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1143e8d8bef9SDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
1144e8d8bef9SDimitry Andric }
1145e8d8bef9SDimitry Andric 
11460b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
114781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
11480b57cec5SDimitry Andric }
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
115181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1152e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_unspecified_type ||
1153e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_string_type,
11540b57cec5SDimitry Andric           "invalid tag", &N);
1155e8d8bef9SDimitry Andric }
1156e8d8bef9SDimitry Andric 
1157e8d8bef9SDimitry Andric void Verifier::visitDIStringType(const DIStringType &N) {
115881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
115981ad6265SDimitry Andric   CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
116081ad6265SDimitry Andric           &N);
11610b57cec5SDimitry Andric }
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
11640b57cec5SDimitry Andric   // Common scope checks.
11650b57cec5SDimitry Andric   visitDIScope(N);
11660b57cec5SDimitry Andric 
116781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
11680b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_pointer_type ||
11690b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
11700b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_reference_type ||
11710b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
11720b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_const_type ||
117304eeddc0SDimitry Andric               N.getTag() == dwarf::DW_TAG_immutable_type ||
11740b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_volatile_type ||
11750b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_restrict_type ||
11760b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_atomic_type ||
11770b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_member ||
11785f757f3fSDimitry Andric               (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
11790b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_inheritance ||
1180fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_friend ||
1181fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_set_type,
11820b57cec5SDimitry Andric           "invalid tag", &N);
11830b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
118481ad6265SDimitry Andric     CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
11850b57cec5SDimitry Andric             N.getRawExtraData());
11860b57cec5SDimitry Andric   }
11870b57cec5SDimitry Andric 
1188fe6060f1SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_set_type) {
1189fe6060f1SDimitry Andric     if (auto *T = N.getRawBaseType()) {
1190fe6060f1SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1191fe6060f1SDimitry Andric       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
119281ad6265SDimitry Andric       CheckDI(
1193fe6060f1SDimitry Andric           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1194fe6060f1SDimitry Andric               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1195fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1196fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1197fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1198fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1199fe6060f1SDimitry Andric           "invalid set base type", &N, T);
1200fe6060f1SDimitry Andric     }
1201fe6060f1SDimitry Andric   }
1202fe6060f1SDimitry Andric 
120381ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
120481ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
12050b57cec5SDimitry Andric           N.getRawBaseType());
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
120881ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
12090b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_reference_type ||
12100b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
12110b57cec5SDimitry Andric             "DWARF address space only applies to pointer or reference types",
12120b57cec5SDimitry Andric             &N);
12130b57cec5SDimitry Andric   }
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric /// Detect mutually exclusive flags.
12170b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
12180b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
12190b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
12200b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
12210b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
12220b57cec5SDimitry Andric }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
12250b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
122681ad6265SDimitry Andric   CheckDI(Params, "invalid template params", &N, &RawParams);
12270b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
122881ad6265SDimitry Andric     CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
12290b57cec5SDimitry Andric             &N, Params, Op);
12300b57cec5SDimitry Andric   }
12310b57cec5SDimitry Andric }
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
12340b57cec5SDimitry Andric   // Common scope checks.
12350b57cec5SDimitry Andric   visitDIScope(N);
12360b57cec5SDimitry Andric 
123781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
12380b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_structure_type ||
12390b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_union_type ||
12400b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_enumeration_type ||
12410b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_class_type ||
1242349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_variant_part ||
1243349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_namelist,
12440b57cec5SDimitry Andric           "invalid tag", &N);
12450b57cec5SDimitry Andric 
124681ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
124781ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
12480b57cec5SDimitry Andric           N.getRawBaseType());
12490b57cec5SDimitry Andric 
125081ad6265SDimitry Andric   CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
12510b57cec5SDimitry Andric           "invalid composite elements", &N, N.getRawElements());
125281ad6265SDimitry Andric   CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
12530b57cec5SDimitry Andric           N.getRawVTableHolder());
125481ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
12550b57cec5SDimitry Andric           "invalid reference flags", &N);
12568bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
125781ad6265SDimitry Andric   CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
12588bcb0991SDimitry Andric           "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric   if (N.isVector()) {
12610b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
126281ad6265SDimitry Andric     CheckDI(Elements.size() == 1 &&
12630b57cec5SDimitry Andric                 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
12640b57cec5SDimitry Andric             "invalid vector, expected one element of type subrange", &N);
12650b57cec5SDimitry Andric   }
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
12680b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
127181ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
12720b57cec5SDimitry Andric             "discriminator can only appear on variant part");
12730b57cec5SDimitry Andric   }
12745ffd83dbSDimitry Andric 
12755ffd83dbSDimitry Andric   if (N.getRawDataLocation()) {
127681ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
12775ffd83dbSDimitry Andric             "dataLocation can only appear in array type");
12785ffd83dbSDimitry Andric   }
1279e8d8bef9SDimitry Andric 
1280e8d8bef9SDimitry Andric   if (N.getRawAssociated()) {
128181ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1282e8d8bef9SDimitry Andric             "associated can only appear in array type");
1283e8d8bef9SDimitry Andric   }
1284e8d8bef9SDimitry Andric 
1285e8d8bef9SDimitry Andric   if (N.getRawAllocated()) {
128681ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1287e8d8bef9SDimitry Andric             "allocated can only appear in array type");
1288e8d8bef9SDimitry Andric   }
1289e8d8bef9SDimitry Andric 
1290e8d8bef9SDimitry Andric   if (N.getRawRank()) {
129181ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1292e8d8bef9SDimitry Andric             "rank can only appear in array type");
1293e8d8bef9SDimitry Andric   }
12945f757f3fSDimitry Andric 
12955f757f3fSDimitry Andric   if (N.getTag() == dwarf::DW_TAG_array_type) {
12965f757f3fSDimitry Andric     CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
12975f757f3fSDimitry Andric   }
12980b57cec5SDimitry Andric }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
130181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
13020b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
130381ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
13040b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
130581ad6265SDimitry Andric       CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
13060b57cec5SDimitry Andric     }
13070b57cec5SDimitry Andric   }
130881ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
13090b57cec5SDimitry Andric           "invalid reference flags", &N);
13100b57cec5SDimitry Andric }
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
131381ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1314bdd1243dSDimitry Andric   std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
13150b57cec5SDimitry Andric   if (Checksum) {
131681ad6265SDimitry Andric     CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
13170b57cec5SDimitry Andric             "invalid checksum kind", &N);
13180b57cec5SDimitry Andric     size_t Size;
13190b57cec5SDimitry Andric     switch (Checksum->Kind) {
13200b57cec5SDimitry Andric     case DIFile::CSK_MD5:
13210b57cec5SDimitry Andric       Size = 32;
13220b57cec5SDimitry Andric       break;
13230b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
13240b57cec5SDimitry Andric       Size = 40;
13250b57cec5SDimitry Andric       break;
13265ffd83dbSDimitry Andric     case DIFile::CSK_SHA256:
13275ffd83dbSDimitry Andric       Size = 64;
13285ffd83dbSDimitry Andric       break;
13290b57cec5SDimitry Andric     }
133081ad6265SDimitry Andric     CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
133181ad6265SDimitry Andric     CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
13320b57cec5SDimitry Andric             "invalid checksum", &N);
13330b57cec5SDimitry Andric   }
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
133781ad6265SDimitry Andric   CheckDI(N.isDistinct(), "compile units must be distinct", &N);
133881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
13410b57cec5SDimitry Andric   // as those could be empty.
134281ad6265SDimitry Andric   CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
13430b57cec5SDimitry Andric           N.getRawFile());
134481ad6265SDimitry Andric   CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
13450b57cec5SDimitry Andric           N.getFile());
13460b57cec5SDimitry Andric 
1347e8d8bef9SDimitry Andric   CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage();
1348e8d8bef9SDimitry Andric 
134981ad6265SDimitry Andric   CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
13500b57cec5SDimitry Andric           "invalid emission kind", &N);
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
135381ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
13540b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
13550b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
135681ad6265SDimitry Andric       CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
13570b57cec5SDimitry Andric               "invalid enum type", &N, N.getEnumTypes(), Op);
13580b57cec5SDimitry Andric     }
13590b57cec5SDimitry Andric   }
13600b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
136181ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
13620b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
136381ad6265SDimitry Andric       CheckDI(
136481ad6265SDimitry Andric           Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
13650b57cec5SDimitry Andric                                      !cast<DISubprogram>(Op)->isDefinition())),
13660b57cec5SDimitry Andric           "invalid retained type", &N, Op);
13670b57cec5SDimitry Andric     }
13680b57cec5SDimitry Andric   }
13690b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
137081ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
13710b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
137281ad6265SDimitry Andric       CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
13730b57cec5SDimitry Andric               "invalid global variable ref", &N, Op);
13740b57cec5SDimitry Andric     }
13750b57cec5SDimitry Andric   }
13760b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
137781ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
13780b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
137981ad6265SDimitry Andric       CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
13800b57cec5SDimitry Andric               &N, Op);
13810b57cec5SDimitry Andric     }
13820b57cec5SDimitry Andric   }
13830b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
138481ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
13850b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
138681ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
13870b57cec5SDimitry Andric     }
13880b57cec5SDimitry Andric   }
13890b57cec5SDimitry Andric   CUVisited.insert(&N);
13900b57cec5SDimitry Andric }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
139381ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
139481ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
13950b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
139681ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
13970b57cec5SDimitry Andric   else
139881ad6265SDimitry Andric     CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
13990b57cec5SDimitry Andric   if (auto *T = N.getRawType())
140081ad6265SDimitry Andric     CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
140181ad6265SDimitry Andric   CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
14020b57cec5SDimitry Andric           N.getRawContainingType());
14030b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
14040b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
14050b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
140681ad6265SDimitry Andric     CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
14070b57cec5SDimitry Andric             "invalid subprogram declaration", &N, S);
14080b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
14090b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
141081ad6265SDimitry Andric     CheckDI(Node, "invalid retained nodes list", &N, RawNode);
14110b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
141206c3fb27SDimitry Andric       CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op) ||
141306c3fb27SDimitry Andric                      isa<DIImportedEntity>(Op)),
141406c3fb27SDimitry Andric               "invalid retained nodes, expected DILocalVariable, DILabel or "
141506c3fb27SDimitry Andric               "DIImportedEntity",
141606c3fb27SDimitry Andric               &N, Node, Op);
14170b57cec5SDimitry Andric     }
14180b57cec5SDimitry Andric   }
141981ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
14200b57cec5SDimitry Andric           "invalid reference flags", &N);
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
14230b57cec5SDimitry Andric   if (N.isDefinition()) {
14240b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
142581ad6265SDimitry Andric     CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
142681ad6265SDimitry Andric     CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
142781ad6265SDimitry Andric     CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
14285f757f3fSDimitry Andric     // There's no good way to cross the CU boundary to insert a nested
14295f757f3fSDimitry Andric     // DISubprogram definition in one CU into a type defined in another CU.
14305f757f3fSDimitry Andric     auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
14315f757f3fSDimitry Andric     if (CT && CT->getRawIdentifier() &&
14325f757f3fSDimitry Andric         M.getContext().isODRUniquingDebugTypes())
14335f757f3fSDimitry Andric       CheckDI(N.getDeclaration(),
14345f757f3fSDimitry Andric               "definition subprograms cannot be nested within DICompositeType "
14355f757f3fSDimitry Andric               "when enabling ODR",
14365f757f3fSDimitry Andric               &N);
14370b57cec5SDimitry Andric   } else {
14380b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
143981ad6265SDimitry Andric     CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
144006c3fb27SDimitry Andric     CheckDI(!N.getRawDeclaration(),
144106c3fb27SDimitry Andric             "subprogram declaration must not have a declaration field");
14420b57cec5SDimitry Andric   }
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
14450b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
144681ad6265SDimitry Andric     CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
14470b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
144881ad6265SDimitry Andric       CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
14490b57cec5SDimitry Andric               Op);
14500b57cec5SDimitry Andric   }
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
145381ad6265SDimitry Andric     CheckDI(N.isDefinition(),
14540b57cec5SDimitry Andric             "DIFlagAllCallsDescribed must be attached to a definition");
14550b57cec5SDimitry Andric }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
145881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
145981ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
14600b57cec5SDimitry Andric           "invalid local scope", &N, N.getRawScope());
14610b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
146281ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
14630b57cec5SDimitry Andric }
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
14660b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
14670b57cec5SDimitry Andric 
146881ad6265SDimitry Andric   CheckDI(N.getLine() || !N.getColumn(),
14690b57cec5SDimitry Andric           "cannot have column info without line info", &N);
14700b57cec5SDimitry Andric }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
14730b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
14740b57cec5SDimitry Andric }
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
147781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
14780b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
147981ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
14800b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
148181ad6265SDimitry Andric     CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
14820b57cec5SDimitry Andric }
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
148581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
14860b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
148781ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
14880b57cec5SDimitry Andric }
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
149181ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
14920b57cec5SDimitry Andric               N.getMacinfoType() == dwarf::DW_MACINFO_undef,
14930b57cec5SDimitry Andric           "invalid macinfo type", &N);
149481ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous macro", &N);
14950b57cec5SDimitry Andric   if (!N.getValue().empty()) {
14960b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
14970b57cec5SDimitry Andric   }
14980b57cec5SDimitry Andric }
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
150181ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
15020b57cec5SDimitry Andric           "invalid macinfo type", &N);
15030b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
150481ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
150781ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
15080b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
150981ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
15100b57cec5SDimitry Andric     }
15110b57cec5SDimitry Andric   }
15120b57cec5SDimitry Andric }
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
151581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
151681ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous module", &N);
15170b57cec5SDimitry Andric }
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
152081ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
15210b57cec5SDimitry Andric }
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
15240b57cec5SDimitry Andric   visitDITemplateParameter(N);
15250b57cec5SDimitry Andric 
152681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
15270b57cec5SDimitry Andric           &N);
15280b57cec5SDimitry Andric }
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
15310b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
15320b57cec5SDimitry Andric   visitDITemplateParameter(N);
15330b57cec5SDimitry Andric 
153481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
15350b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
15360b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
15370b57cec5SDimitry Andric           "invalid tag", &N);
15380b57cec5SDimitry Andric }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
15410b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
154281ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
15430b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
154481ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
15480b57cec5SDimitry Andric   // Checks common to all variables.
15490b57cec5SDimitry Andric   visitDIVariable(N);
15500b57cec5SDimitry Andric 
155181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
155281ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
155381ad6265SDimitry Andric   // Check only if the global variable is not an extern
15545ffd83dbSDimitry Andric   if (N.isDefinition())
155581ad6265SDimitry Andric     CheckDI(N.getType(), "missing global variable type", &N);
15560b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
155781ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(Member),
15580b57cec5SDimitry Andric             "invalid static data member declaration", &N, Member);
15590b57cec5SDimitry Andric   }
15600b57cec5SDimitry Andric }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
15630b57cec5SDimitry Andric   // Checks common to all variables.
15640b57cec5SDimitry Andric   visitDIVariable(N);
15650b57cec5SDimitry Andric 
156681ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
156781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
156881ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15690b57cec5SDimitry Andric           "local variable requires a valid scope", &N, N.getRawScope());
15700b57cec5SDimitry Andric   if (auto Ty = N.getType())
157181ad6265SDimitry Andric     CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
1574bdd1243dSDimitry Andric void Verifier::visitDIAssignID(const DIAssignID &N) {
1575bdd1243dSDimitry Andric   CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1576bdd1243dSDimitry Andric   CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1577bdd1243dSDimitry Andric }
1578bdd1243dSDimitry Andric 
15790b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
15800b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
158181ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
15820b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
158381ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15840b57cec5SDimitry Andric 
158581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
158681ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15870b57cec5SDimitry Andric           "label requires a valid scope", &N, N.getRawScope());
15880b57cec5SDimitry Andric }
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
159181ad6265SDimitry Andric   CheckDI(N.isValid(), "invalid expression", &N);
15920b57cec5SDimitry Andric }
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
15950b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
159681ad6265SDimitry Andric   CheckDI(GVE.getVariable(), "missing variable");
15970b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
15980b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
15990b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
16000b57cec5SDimitry Andric     visitDIExpression(*Expr);
16010b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
16020b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
16030b57cec5SDimitry Andric   }
16040b57cec5SDimitry Andric }
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
160781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
16080b57cec5SDimitry Andric   if (auto *T = N.getRawType())
160981ad6265SDimitry Andric     CheckDI(isType(T), "invalid type ref", &N, T);
16100b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
161181ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
16120b57cec5SDimitry Andric }
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
161581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
16160b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_imported_declaration,
16170b57cec5SDimitry Andric           "invalid tag", &N);
16180b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
161981ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
162081ad6265SDimitry Andric   CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
16210b57cec5SDimitry Andric           N.getRawEntity());
16220b57cec5SDimitry Andric }
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
16258bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
16268bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
16278bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
16280b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
162981ad6265SDimitry Andric       Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
163081ad6265SDimitry Andric             GV);
16310b57cec5SDimitry Andric }
16320b57cec5SDimitry Andric 
1633349cc55cSDimitry Andric void Verifier::visitModuleIdents() {
16340b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
16350b57cec5SDimitry Andric   if (!Idents)
16360b57cec5SDimitry Andric     return;
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
16390b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
16400b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
164181ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
16420b57cec5SDimitry Andric           "incorrect number of operands in llvm.ident metadata", N);
164381ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
16440b57cec5SDimitry Andric           ("invalid value for llvm.ident metadata entry operand"
16450b57cec5SDimitry Andric            "(the operand should be a string)"),
16460b57cec5SDimitry Andric           N->getOperand(0));
16470b57cec5SDimitry Andric   }
16480b57cec5SDimitry Andric }
16490b57cec5SDimitry Andric 
1650349cc55cSDimitry Andric void Verifier::visitModuleCommandLines() {
16510b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
16520b57cec5SDimitry Andric   if (!CommandLines)
16530b57cec5SDimitry Andric     return;
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
16560b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
16570b57cec5SDimitry Andric   // requirement is met.
16580b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
165981ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
16600b57cec5SDimitry Andric           "incorrect number of operands in llvm.commandline metadata", N);
166181ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
16620b57cec5SDimitry Andric           ("invalid value for llvm.commandline metadata entry operand"
16630b57cec5SDimitry Andric            "(the operand should be a string)"),
16640b57cec5SDimitry Andric           N->getOperand(0));
16650b57cec5SDimitry Andric   }
16660b57cec5SDimitry Andric }
16670b57cec5SDimitry Andric 
1668349cc55cSDimitry Andric void Verifier::visitModuleFlags() {
16690b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
16700b57cec5SDimitry Andric   if (!Flags) return;
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
16730b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
16740b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
16750b57cec5SDimitry Andric   for (const MDNode *MDN : Flags->operands())
16760b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
16790b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
16800b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
16810b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
16840b57cec5SDimitry Andric     if (!Op) {
16850b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
16860b57cec5SDimitry Andric                   Flag);
16870b57cec5SDimitry Andric       continue;
16880b57cec5SDimitry Andric     }
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
16910b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
16920b57cec5SDimitry Andric                    "flag does not have the required value"),
16930b57cec5SDimitry Andric                   Flag);
16940b57cec5SDimitry Andric       continue;
16950b57cec5SDimitry Andric     }
16960b57cec5SDimitry Andric   }
16970b57cec5SDimitry Andric }
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric void
17000b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
17010b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
17020b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
17030b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
17040b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
170581ad6265SDimitry Andric   Check(Op->getNumOperands() == 3,
17060b57cec5SDimitry Andric         "incorrect number of operands in module flag", Op);
17070b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
17080b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
170981ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
17100b57cec5SDimitry Andric           "invalid behavior operand in module flag (expected constant integer)",
17110b57cec5SDimitry Andric           Op->getOperand(0));
171281ad6265SDimitry Andric     Check(false,
17130b57cec5SDimitry Andric           "invalid behavior operand in module flag (unexpected constant)",
17140b57cec5SDimitry Andric           Op->getOperand(0));
17150b57cec5SDimitry Andric   }
17160b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
171781ad6265SDimitry Andric   Check(ID, "invalid ID operand in module flag (expected metadata string)",
17180b57cec5SDimitry Andric         Op->getOperand(1));
17190b57cec5SDimitry Andric 
17204824e7fdSDimitry Andric   // Check the values for behaviors with additional requirements.
17210b57cec5SDimitry Andric   switch (MFB) {
17220b57cec5SDimitry Andric   case Module::Error:
17230b57cec5SDimitry Andric   case Module::Warning:
17240b57cec5SDimitry Andric   case Module::Override:
17250b57cec5SDimitry Andric     // These behavior types accept any value.
17260b57cec5SDimitry Andric     break;
17270b57cec5SDimitry Andric 
172881ad6265SDimitry Andric   case Module::Min: {
1729fcaf7f86SDimitry Andric     auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1730fcaf7f86SDimitry Andric     Check(V && V->getValue().isNonNegative(),
1731fcaf7f86SDimitry Andric           "invalid value for 'min' module flag (expected constant non-negative "
1732fcaf7f86SDimitry Andric           "integer)",
173381ad6265SDimitry Andric           Op->getOperand(2));
173481ad6265SDimitry Andric     break;
173581ad6265SDimitry Andric   }
173681ad6265SDimitry Andric 
17370b57cec5SDimitry Andric   case Module::Max: {
173881ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
17390b57cec5SDimitry Andric           "invalid value for 'max' module flag (expected constant integer)",
17400b57cec5SDimitry Andric           Op->getOperand(2));
17410b57cec5SDimitry Andric     break;
17420b57cec5SDimitry Andric   }
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric   case Module::Require: {
17450b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
17460b57cec5SDimitry Andric     // MDString), and a value.
17470b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
174881ad6265SDimitry Andric     Check(Value && Value->getNumOperands() == 2,
17490b57cec5SDimitry Andric           "invalid value for 'require' module flag (expected metadata pair)",
17500b57cec5SDimitry Andric           Op->getOperand(2));
175181ad6265SDimitry Andric     Check(isa<MDString>(Value->getOperand(0)),
17520b57cec5SDimitry Andric           ("invalid value for 'require' module flag "
17530b57cec5SDimitry Andric            "(first value operand should be a string)"),
17540b57cec5SDimitry Andric           Value->getOperand(0));
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
17570b57cec5SDimitry Andric     // scanned.
17580b57cec5SDimitry Andric     Requirements.push_back(Value);
17590b57cec5SDimitry Andric     break;
17600b57cec5SDimitry Andric   }
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   case Module::Append:
17630b57cec5SDimitry Andric   case Module::AppendUnique: {
17640b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
176581ad6265SDimitry Andric     Check(isa<MDNode>(Op->getOperand(2)),
17660b57cec5SDimitry Andric           "invalid value for 'append'-type module flag "
17670b57cec5SDimitry Andric           "(expected a metadata node)",
17680b57cec5SDimitry Andric           Op->getOperand(2));
17690b57cec5SDimitry Andric     break;
17700b57cec5SDimitry Andric   }
17710b57cec5SDimitry Andric   }
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
17740b57cec5SDimitry Andric   if (MFB != Module::Require) {
17750b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
177681ad6265SDimitry Andric     Check(Inserted,
17770b57cec5SDimitry Andric           "module flag identifiers must be unique (or of 'require' type)", ID);
17780b57cec5SDimitry Andric   }
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
17810b57cec5SDimitry Andric     ConstantInt *Value
17820b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
178381ad6265SDimitry Andric     Check(Value, "wchar_size metadata requires constant integer argument");
17840b57cec5SDimitry Andric   }
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
17870b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
17880b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
17890b57cec5SDimitry Andric     // have been created by a client directly.
179081ad6265SDimitry Andric     Check(M.getNamedMetadata("llvm.linker.options"),
17910b57cec5SDimitry Andric           "'Linker Options' named metadata no longer supported");
17920b57cec5SDimitry Andric   }
17930b57cec5SDimitry Andric 
17945ffd83dbSDimitry Andric   if (ID->getString() == "SemanticInterposition") {
17955ffd83dbSDimitry Andric     ConstantInt *Value =
17965ffd83dbSDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
179781ad6265SDimitry Andric     Check(Value,
17985ffd83dbSDimitry Andric           "SemanticInterposition metadata requires constant integer argument");
17995ffd83dbSDimitry Andric   }
18005ffd83dbSDimitry Andric 
18010b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
18020b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
18030b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
18040b57cec5SDimitry Andric   }
18050b57cec5SDimitry Andric }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
18080b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
18090b57cec5SDimitry Andric     if (!FuncMDO)
18100b57cec5SDimitry Andric       return;
18110b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
181281ad6265SDimitry Andric     Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
1813e8d8bef9SDimitry Andric           "expected a Function or null", FuncMDO);
18140b57cec5SDimitry Andric   };
18150b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
181681ad6265SDimitry Andric   Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
18170b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
18180b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
18190b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
182081ad6265SDimitry Andric   Check(Count && Count->getType()->isIntegerTy(),
18210b57cec5SDimitry Andric         "expected an integer constant", Node->getOperand(2));
18220b57cec5SDimitry Andric }
18230b57cec5SDimitry Andric 
1824fe6060f1SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
18250b57cec5SDimitry Andric   for (Attribute A : Attrs) {
1826fe6060f1SDimitry Andric 
1827fe6060f1SDimitry Andric     if (A.isStringAttribute()) {
1828fe6060f1SDimitry Andric #define GET_ATTR_NAMES
1829fe6060f1SDimitry Andric #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1830fe6060f1SDimitry Andric #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1831fe6060f1SDimitry Andric   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1832fe6060f1SDimitry Andric     auto V = A.getValueAsString();                                             \
1833fe6060f1SDimitry Andric     if (!(V.empty() || V == "true" || V == "false"))                           \
1834fe6060f1SDimitry Andric       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1835fe6060f1SDimitry Andric                   "");                                                         \
1836fe6060f1SDimitry Andric   }
1837fe6060f1SDimitry Andric 
1838fe6060f1SDimitry Andric #include "llvm/IR/Attributes.inc"
18390b57cec5SDimitry Andric       continue;
1840fe6060f1SDimitry Andric     }
18410b57cec5SDimitry Andric 
1842fe6060f1SDimitry Andric     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
18435ffd83dbSDimitry Andric       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
18445ffd83dbSDimitry Andric                   V);
18455ffd83dbSDimitry Andric       return;
18465ffd83dbSDimitry Andric     }
18470b57cec5SDimitry Andric   }
18480b57cec5SDimitry Andric }
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
18510b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
18520b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
18530b57cec5SDimitry Andric                                     const Value *V) {
18540b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
18550b57cec5SDimitry Andric     return;
18560b57cec5SDimitry Andric 
1857fe6060f1SDimitry Andric   verifyAttributeTypes(Attrs, V);
1858fe6060f1SDimitry Andric 
1859fe6060f1SDimitry Andric   for (Attribute Attr : Attrs)
186081ad6265SDimitry Andric     Check(Attr.isStringAttribute() ||
1861fe6060f1SDimitry Andric               Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
186281ad6265SDimitry Andric           "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
1863fe6060f1SDimitry Andric           V);
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
186681ad6265SDimitry Andric     Check(Attrs.getNumAttributes() == 1,
18670b57cec5SDimitry Andric           "Attribute 'immarg' is incompatible with other attributes", V);
18680b57cec5SDimitry Andric   }
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
18710b57cec5SDimitry Andric   // sret.
18720b57cec5SDimitry Andric   unsigned AttrCount = 0;
18730b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
18740b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
18755ffd83dbSDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
18760b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
18770b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
18780b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1879e8d8bef9SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
188081ad6265SDimitry Andric   Check(AttrCount <= 1,
18815ffd83dbSDimitry Andric         "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1882e8d8bef9SDimitry Andric         "'byref', and 'sret' are incompatible!",
18830b57cec5SDimitry Andric         V);
18840b57cec5SDimitry Andric 
188581ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
18860b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
18870b57cec5SDimitry Andric         "Attributes "
18880b57cec5SDimitry Andric         "'inalloca and readonly' are incompatible!",
18890b57cec5SDimitry Andric         V);
18900b57cec5SDimitry Andric 
189181ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
18920b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::Returned)),
18930b57cec5SDimitry Andric         "Attributes "
18940b57cec5SDimitry Andric         "'sret and returned' are incompatible!",
18950b57cec5SDimitry Andric         V);
18960b57cec5SDimitry Andric 
189781ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
18980b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::SExt)),
18990b57cec5SDimitry Andric         "Attributes "
19000b57cec5SDimitry Andric         "'zeroext and signext' are incompatible!",
19010b57cec5SDimitry Andric         V);
19020b57cec5SDimitry Andric 
190381ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
19040b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
19050b57cec5SDimitry Andric         "Attributes "
19060b57cec5SDimitry Andric         "'readnone and readonly' are incompatible!",
19070b57cec5SDimitry Andric         V);
19080b57cec5SDimitry Andric 
190981ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
19100b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
19110b57cec5SDimitry Andric         "Attributes "
19120b57cec5SDimitry Andric         "'readnone and writeonly' are incompatible!",
19130b57cec5SDimitry Andric         V);
19140b57cec5SDimitry Andric 
191581ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
19160b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
19170b57cec5SDimitry Andric         "Attributes "
19180b57cec5SDimitry Andric         "'readonly and writeonly' are incompatible!",
19190b57cec5SDimitry Andric         V);
19200b57cec5SDimitry Andric 
192181ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
19220b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::AlwaysInline)),
19230b57cec5SDimitry Andric         "Attributes "
19240b57cec5SDimitry Andric         "'noinline and alwaysinline' are incompatible!",
19250b57cec5SDimitry Andric         V);
19260b57cec5SDimitry Andric 
19275f757f3fSDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::Writable) &&
19285f757f3fSDimitry Andric           Attrs.hasAttribute(Attribute::ReadNone)),
19295f757f3fSDimitry Andric         "Attributes writable and readnone are incompatible!", V);
19305f757f3fSDimitry Andric 
19315f757f3fSDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::Writable) &&
19325f757f3fSDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
19335f757f3fSDimitry Andric         "Attributes writable and readonly are incompatible!", V);
19345f757f3fSDimitry Andric 
193504eeddc0SDimitry Andric   AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1936fe6060f1SDimitry Andric   for (Attribute Attr : Attrs) {
1937fe6060f1SDimitry Andric     if (!Attr.isStringAttribute() &&
1938fe6060f1SDimitry Andric         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
1939fe6060f1SDimitry Andric       CheckFailed("Attribute '" + Attr.getAsString() +
1940fe6060f1SDimitry Andric                   "' applied to incompatible type!", V);
1941fe6060f1SDimitry Andric       return;
1942fe6060f1SDimitry Andric     }
1943fe6060f1SDimitry Andric   }
19440b57cec5SDimitry Andric 
194506c3fb27SDimitry Andric   if (isa<PointerType>(Ty)) {
1946fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByVal)) {
194781ad6265SDimitry Andric       if (Attrs.hasAttribute(Attribute::Alignment)) {
194881ad6265SDimitry Andric         Align AttrAlign = Attrs.getAlignment().valueOrOne();
194981ad6265SDimitry Andric         Align MaxAlign(ParamMaxAlignment);
195081ad6265SDimitry Andric         Check(AttrAlign <= MaxAlign,
195181ad6265SDimitry Andric               "Attribute 'align' exceed the max size 2^14", V);
195281ad6265SDimitry Andric       }
19530b57cec5SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
195481ad6265SDimitry Andric       Check(Attrs.getByValType()->isSized(&Visited),
1955fe6060f1SDimitry Andric             "Attribute 'byval' does not support unsized types!", V);
19560b57cec5SDimitry Andric     }
1957fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByRef)) {
1958fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
195981ad6265SDimitry Andric       Check(Attrs.getByRefType()->isSized(&Visited),
1960fe6060f1SDimitry Andric             "Attribute 'byref' does not support unsized types!", V);
1961fe6060f1SDimitry Andric     }
1962fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::InAlloca)) {
1963fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
196481ad6265SDimitry Andric       Check(Attrs.getInAllocaType()->isSized(&Visited),
1965fe6060f1SDimitry Andric             "Attribute 'inalloca' does not support unsized types!", V);
1966fe6060f1SDimitry Andric     }
1967fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::Preallocated)) {
1968fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
196981ad6265SDimitry Andric       Check(Attrs.getPreallocatedType()->isSized(&Visited),
1970fe6060f1SDimitry Andric             "Attribute 'preallocated' does not support unsized types!", V);
1971fe6060f1SDimitry Andric     }
197206c3fb27SDimitry Andric   }
197306c3fb27SDimitry Andric 
197406c3fb27SDimitry Andric   if (Attrs.hasAttribute(Attribute::NoFPClass)) {
197506c3fb27SDimitry Andric     uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
197606c3fb27SDimitry Andric     Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
19770b57cec5SDimitry Andric           V);
197806c3fb27SDimitry Andric     Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
197906c3fb27SDimitry Andric           "Invalid value for 'nofpclass' test mask", V);
1980fe6060f1SDimitry Andric   }
1981fe6060f1SDimitry Andric }
1982fe6060f1SDimitry Andric 
1983fe6060f1SDimitry Andric void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
1984fe6060f1SDimitry Andric                                             const Value *V) {
1985349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attr)) {
1986349cc55cSDimitry Andric     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
1987fe6060f1SDimitry Andric     unsigned N;
1988fe6060f1SDimitry Andric     if (S.getAsInteger(10, N))
1989fe6060f1SDimitry Andric       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
19900b57cec5SDimitry Andric   }
19910b57cec5SDimitry Andric }
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric // Check parameter attributes against a function type.
19940b57cec5SDimitry Andric // The value V is printed in error messages.
19950b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
199604eeddc0SDimitry Andric                                    const Value *V, bool IsIntrinsic,
199704eeddc0SDimitry Andric                                    bool IsInlineAsm) {
19980b57cec5SDimitry Andric   if (Attrs.isEmpty())
19990b57cec5SDimitry Andric     return;
20000b57cec5SDimitry Andric 
2001fe6060f1SDimitry Andric   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
200281ad6265SDimitry Andric     Check(Attrs.hasParentContext(Context),
2003fe6060f1SDimitry Andric           "Attribute list does not match Module context!", &Attrs, V);
2004fe6060f1SDimitry Andric     for (const auto &AttrSet : Attrs) {
200581ad6265SDimitry Andric       Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2006fe6060f1SDimitry Andric             "Attribute set does not match Module context!", &AttrSet, V);
2007fe6060f1SDimitry Andric       for (const auto &A : AttrSet) {
200881ad6265SDimitry Andric         Check(A.hasParentContext(Context),
2009fe6060f1SDimitry Andric               "Attribute does not match Module context!", &A, V);
2010fe6060f1SDimitry Andric       }
2011fe6060f1SDimitry Andric     }
2012fe6060f1SDimitry Andric   }
2013fe6060f1SDimitry Andric 
20140b57cec5SDimitry Andric   bool SawNest = false;
20150b57cec5SDimitry Andric   bool SawReturned = false;
20160b57cec5SDimitry Andric   bool SawSRet = false;
20170b57cec5SDimitry Andric   bool SawSwiftSelf = false;
2018fe6060f1SDimitry Andric   bool SawSwiftAsync = false;
20190b57cec5SDimitry Andric   bool SawSwiftError = false;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   // Verify return value attributes.
2022349cc55cSDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttrs();
2023fe6060f1SDimitry Andric   for (Attribute RetAttr : RetAttrs)
202481ad6265SDimitry Andric     Check(RetAttr.isStringAttribute() ||
2025fe6060f1SDimitry Andric               Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2026fe6060f1SDimitry Andric           "Attribute '" + RetAttr.getAsString() +
2027fe6060f1SDimitry Andric               "' does not apply to function return values",
20280b57cec5SDimitry Andric           V);
2029fe6060f1SDimitry Andric 
20305f757f3fSDimitry Andric   unsigned MaxParameterWidth = 0;
20315f757f3fSDimitry Andric   auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
20325f757f3fSDimitry Andric     if (Ty->isVectorTy()) {
20335f757f3fSDimitry Andric       if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
20345f757f3fSDimitry Andric         unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
20355f757f3fSDimitry Andric         if (Size > MaxParameterWidth)
20365f757f3fSDimitry Andric           MaxParameterWidth = Size;
20375f757f3fSDimitry Andric       }
20385f757f3fSDimitry Andric     }
20395f757f3fSDimitry Andric   };
20405f757f3fSDimitry Andric   GetMaxParameterWidth(FT->getReturnType());
20410b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric   // Verify parameter attributes.
20440b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
20450b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
2046349cc55cSDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric     if (!IsIntrinsic) {
204981ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
20500b57cec5SDimitry Andric             "immarg attribute only applies to intrinsics", V);
205104eeddc0SDimitry Andric       if (!IsInlineAsm)
205281ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
205304eeddc0SDimitry Andric               "Attribute 'elementtype' can only be applied to intrinsics"
205481ad6265SDimitry Andric               " and inline asm.",
205581ad6265SDimitry Andric               V);
20560b57cec5SDimitry Andric     }
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
20595f757f3fSDimitry Andric     GetMaxParameterWidth(Ty);
20600b57cec5SDimitry Andric 
20610b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
206281ad6265SDimitry Andric       Check(!SawNest, "More than one parameter has attribute nest!", V);
20630b57cec5SDimitry Andric       SawNest = true;
20640b57cec5SDimitry Andric     }
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
206781ad6265SDimitry Andric       Check(!SawReturned, "More than one parameter has attribute returned!", V);
206881ad6265SDimitry Andric       Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
20690b57cec5SDimitry Andric             "Incompatible argument and return types for 'returned' attribute",
20700b57cec5SDimitry Andric             V);
20710b57cec5SDimitry Andric       SawReturned = true;
20720b57cec5SDimitry Andric     }
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
207581ad6265SDimitry Andric       Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
207681ad6265SDimitry Andric       Check(i == 0 || i == 1,
20770b57cec5SDimitry Andric             "Attribute 'sret' is not on first or second parameter!", V);
20780b57cec5SDimitry Andric       SawSRet = true;
20790b57cec5SDimitry Andric     }
20800b57cec5SDimitry Andric 
20810b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
208281ad6265SDimitry Andric       Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
20830b57cec5SDimitry Andric       SawSwiftSelf = true;
20840b57cec5SDimitry Andric     }
20850b57cec5SDimitry Andric 
2086fe6060f1SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
208781ad6265SDimitry Andric       Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2088fe6060f1SDimitry Andric       SawSwiftAsync = true;
2089fe6060f1SDimitry Andric     }
2090fe6060f1SDimitry Andric 
20910b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
209281ad6265SDimitry Andric       Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
20930b57cec5SDimitry Andric       SawSwiftError = true;
20940b57cec5SDimitry Andric     }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
209781ad6265SDimitry Andric       Check(i == FT->getNumParams() - 1,
20980b57cec5SDimitry Andric             "inalloca isn't on the last parameter!", V);
20990b57cec5SDimitry Andric     }
21000b57cec5SDimitry Andric   }
21010b57cec5SDimitry Andric 
2102349cc55cSDimitry Andric   if (!Attrs.hasFnAttrs())
21030b57cec5SDimitry Andric     return;
21040b57cec5SDimitry Andric 
2105349cc55cSDimitry Andric   verifyAttributeTypes(Attrs.getFnAttrs(), V);
2106349cc55cSDimitry Andric   for (Attribute FnAttr : Attrs.getFnAttrs())
210781ad6265SDimitry Andric     Check(FnAttr.isStringAttribute() ||
2108fe6060f1SDimitry Andric               Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2109fe6060f1SDimitry Andric           "Attribute '" + FnAttr.getAsString() +
2110fe6060f1SDimitry Andric               "' does not apply to functions!",
2111fe6060f1SDimitry Andric           V);
21120b57cec5SDimitry Andric 
211381ad6265SDimitry Andric   Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2114349cc55cSDimitry Andric           Attrs.hasFnAttr(Attribute::AlwaysInline)),
21150b57cec5SDimitry Andric         "Attributes 'noinline and alwaysinline' are incompatible!", V);
21160b57cec5SDimitry Andric 
2117349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
211881ad6265SDimitry Andric     Check(Attrs.hasFnAttr(Attribute::NoInline),
21190b57cec5SDimitry Andric           "Attribute 'optnone' requires 'noinline'!", V);
21200b57cec5SDimitry Andric 
212181ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
21220b57cec5SDimitry Andric           "Attributes 'optsize and optnone' are incompatible!", V);
21230b57cec5SDimitry Andric 
212481ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
21250b57cec5SDimitry Andric           "Attributes 'minsize and optnone' are incompatible!", V);
21265f757f3fSDimitry Andric 
21275f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
21285f757f3fSDimitry Andric           "Attributes 'optdebug and optnone' are incompatible!", V);
21290b57cec5SDimitry Andric   }
21300b57cec5SDimitry Andric 
21315f757f3fSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
21325f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
21335f757f3fSDimitry Andric           "Attributes 'optsize and optdebug' are incompatible!", V);
21345f757f3fSDimitry Andric 
21355f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
21365f757f3fSDimitry Andric           "Attributes 'minsize and optdebug' are incompatible!", V);
21375f757f3fSDimitry Andric   }
21385f757f3fSDimitry Andric 
21395f757f3fSDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
21405f757f3fSDimitry Andric         isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
21415f757f3fSDimitry Andric         "Attribute writable and memory without argmem: write are incompatible!",
21425f757f3fSDimitry Andric         V);
21435f757f3fSDimitry Andric 
2144bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2145bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2146bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_sm_enabled and "
2147bdd1243dSDimitry Andric            "aarch64_pstate_sm_compatible' are incompatible!",
2148bdd1243dSDimitry Andric            V);
2149bdd1243dSDimitry Andric   }
2150bdd1243dSDimitry Andric 
2151bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_za_new")) {
2152bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_za_preserved"),
2153bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2154bdd1243dSDimitry Andric            "are incompatible!",
2155bdd1243dSDimitry Andric            V);
2156bdd1243dSDimitry Andric 
2157bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_za_shared"),
2158bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2159bdd1243dSDimitry Andric            "are incompatible!",
2160bdd1243dSDimitry Andric            V);
2161bdd1243dSDimitry Andric   }
2162bdd1243dSDimitry Andric 
2163349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
21640b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
216581ad6265SDimitry Andric     Check(GV->hasGlobalUnnamedAddr(),
21660b57cec5SDimitry Andric           "Attribute 'jumptable' requires 'unnamed_addr'", V);
21670b57cec5SDimitry Andric   }
21680b57cec5SDimitry Andric 
2169bdd1243dSDimitry Andric   if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
21700b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
21710b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
21720b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
21730b57cec5SDimitry Andric         return false;
21740b57cec5SDimitry Andric       }
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
21770b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
21780b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
21790b57cec5SDimitry Andric                     V);
21800b57cec5SDimitry Andric         return false;
21810b57cec5SDimitry Andric       }
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric       return true;
21840b57cec5SDimitry Andric     };
21850b57cec5SDimitry Andric 
2186bdd1243dSDimitry Andric     if (!CheckParam("element size", Args->first))
21870b57cec5SDimitry Andric       return;
21880b57cec5SDimitry Andric 
2189bdd1243dSDimitry Andric     if (Args->second && !CheckParam("number of elements", *Args->second))
21900b57cec5SDimitry Andric       return;
21910b57cec5SDimitry Andric   }
2192480093f4SDimitry Andric 
219381ad6265SDimitry Andric   if (Attrs.hasFnAttr(Attribute::AllocKind)) {
219481ad6265SDimitry Andric     AllocFnKind K = Attrs.getAllocKind();
219581ad6265SDimitry Andric     AllocFnKind Type =
219681ad6265SDimitry Andric         K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
219781ad6265SDimitry Andric     if (!is_contained(
219881ad6265SDimitry Andric             {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
219981ad6265SDimitry Andric             Type))
220081ad6265SDimitry Andric       CheckFailed(
220181ad6265SDimitry Andric           "'allockind()' requires exactly one of alloc, realloc, and free");
220281ad6265SDimitry Andric     if ((Type == AllocFnKind::Free) &&
220381ad6265SDimitry Andric         ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
220481ad6265SDimitry Andric                AllocFnKind::Aligned)) != AllocFnKind::Unknown))
220581ad6265SDimitry Andric       CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
220681ad6265SDimitry Andric                   "or aligned modifiers.");
220781ad6265SDimitry Andric     AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
220881ad6265SDimitry Andric     if ((K & ZeroedUninit) == ZeroedUninit)
220981ad6265SDimitry Andric       CheckFailed("'allockind()' can't be both zeroed and uninitialized");
221081ad6265SDimitry Andric   }
221181ad6265SDimitry Andric 
2212349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
22130eae32dcSDimitry Andric     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
22140eae32dcSDimitry Andric     if (VScaleMin == 0)
22150eae32dcSDimitry Andric       CheckFailed("'vscale_range' minimum must be greater than 0", V);
221606c3fb27SDimitry Andric     else if (!isPowerOf2_32(VScaleMin))
221706c3fb27SDimitry Andric       CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2218bdd1243dSDimitry Andric     std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
22190eae32dcSDimitry Andric     if (VScaleMax && VScaleMin > VScaleMax)
2220fe6060f1SDimitry Andric       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
222106c3fb27SDimitry Andric     else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
222206c3fb27SDimitry Andric       CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2223fe6060f1SDimitry Andric   }
2224fe6060f1SDimitry Andric 
2225349cc55cSDimitry Andric   if (Attrs.hasFnAttr("frame-pointer")) {
2226349cc55cSDimitry Andric     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2227480093f4SDimitry Andric     if (FP != "all" && FP != "non-leaf" && FP != "none")
2228480093f4SDimitry Andric       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2229480093f4SDimitry Andric   }
2230480093f4SDimitry Andric 
22315f757f3fSDimitry Andric   // Check EVEX512 feature.
22325f757f3fSDimitry Andric   if (MaxParameterWidth >= 512 && Attrs.hasFnAttr("target-features") &&
22335f757f3fSDimitry Andric       TT.isX86()) {
22345f757f3fSDimitry Andric     StringRef TF = Attrs.getFnAttr("target-features").getValueAsString();
22355f757f3fSDimitry Andric     Check(!TF.contains("+avx512f") || !TF.contains("-evex512"),
22365f757f3fSDimitry Andric           "512-bit vector arguments require 'evex512' for AVX512", V);
22375f757f3fSDimitry Andric   }
22385f757f3fSDimitry Andric 
2239fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2240fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2241fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
22425f757f3fSDimitry Andric 
22435f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
22445f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
22455f757f3fSDimitry Andric     if (S != "none" && S != "all" && S != "non-leaf")
22465f757f3fSDimitry Andric       CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
22475f757f3fSDimitry Andric   }
22485f757f3fSDimitry Andric 
22495f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
22505f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
22515f757f3fSDimitry Andric     if (S != "a_key" && S != "b_key")
22525f757f3fSDimitry Andric       CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
22535f757f3fSDimitry Andric                   V);
22545f757f3fSDimitry Andric   }
22555f757f3fSDimitry Andric 
22565f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
22575f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
22585f757f3fSDimitry Andric     if (S != "true" && S != "false")
22595f757f3fSDimitry Andric       CheckFailed(
22605f757f3fSDimitry Andric           "invalid value for 'branch-target-enforcement' attribute: " + S, V);
22615f757f3fSDimitry Andric   }
22620b57cec5SDimitry Andric }
22630b57cec5SDimitry Andric 
22640b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
22650b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
22660b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
22670b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
22680b57cec5SDimitry Andric       MDNode *MD = Pair.second;
226981ad6265SDimitry Andric       Check(MD->getNumOperands() >= 2,
22700b57cec5SDimitry Andric             "!prof annotations should have no less than 2 operands", MD);
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric       // Check first operand.
227381ad6265SDimitry Andric       Check(MD->getOperand(0) != nullptr, "first operand should not be null",
22740b57cec5SDimitry Andric             MD);
227581ad6265SDimitry Andric       Check(isa<MDString>(MD->getOperand(0)),
22760b57cec5SDimitry Andric             "expected string with name of the !prof annotation", MD);
22770b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
22780b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
227981ad6265SDimitry Andric       Check(ProfName.equals("function_entry_count") ||
22800b57cec5SDimitry Andric                 ProfName.equals("synthetic_function_entry_count"),
22810b57cec5SDimitry Andric             "first operand should be 'function_entry_count'"
22820b57cec5SDimitry Andric             " or 'synthetic_function_entry_count'",
22830b57cec5SDimitry Andric             MD);
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric       // Check second operand.
228681ad6265SDimitry Andric       Check(MD->getOperand(1) != nullptr, "second operand should not be null",
22870b57cec5SDimitry Andric             MD);
228881ad6265SDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
22890b57cec5SDimitry Andric             "expected integer argument to function_entry_count", MD);
2290bdd1243dSDimitry Andric     } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2291bdd1243dSDimitry Andric       MDNode *MD = Pair.second;
2292bdd1243dSDimitry Andric       Check(MD->getNumOperands() == 1,
2293bdd1243dSDimitry Andric             "!kcfi_type must have exactly one operand", MD);
2294bdd1243dSDimitry Andric       Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2295bdd1243dSDimitry Andric             MD);
2296bdd1243dSDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
2297bdd1243dSDimitry Andric             "expected a constant operand for !kcfi_type", MD);
2298bdd1243dSDimitry Andric       Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2299*cb14a3feSDimitry Andric       Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2300bdd1243dSDimitry Andric             "expected a constant integer operand for !kcfi_type", MD);
2301*cb14a3feSDimitry Andric       Check(cast<ConstantInt>(C)->getBitWidth() == 32,
2302bdd1243dSDimitry Andric             "expected a 32-bit integer constant operand for !kcfi_type", MD);
23030b57cec5SDimitry Andric     }
23040b57cec5SDimitry Andric   }
23050b57cec5SDimitry Andric }
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
23080b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
23090b57cec5SDimitry Andric     return;
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
23120b57cec5SDimitry Andric   Stack.push_back(EntryC);
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric   while (!Stack.empty()) {
23150b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric     // Check this constant expression.
23180b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
23190b57cec5SDimitry Andric       visitConstantExpr(CE);
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
23220b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
23230b57cec5SDimitry Andric       // that the global value is in the correct module
232481ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!",
23250b57cec5SDimitry Andric             EntryC, &M, GV, GV->getParent());
23260b57cec5SDimitry Andric       continue;
23270b57cec5SDimitry Andric     }
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric     // Visit all sub-expressions.
23300b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
23310b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
23320b57cec5SDimitry Andric       if (!OpC)
23330b57cec5SDimitry Andric         continue;
23340b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
23350b57cec5SDimitry Andric         continue;
23360b57cec5SDimitry Andric       Stack.push_back(OpC);
23370b57cec5SDimitry Andric     }
23380b57cec5SDimitry Andric   }
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
23420b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
234381ad6265SDimitry Andric     Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
23440b57cec5SDimitry Andric                                 CE->getType()),
23450b57cec5SDimitry Andric           "Invalid bitcast", CE);
23460b57cec5SDimitry Andric }
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
23490b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
23500b57cec5SDimitry Andric   // function and return value.
23510b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
23520b57cec5SDimitry Andric }
23530b57cec5SDimitry Andric 
235404eeddc0SDimitry Andric void Verifier::verifyInlineAsmCall(const CallBase &Call) {
235504eeddc0SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
235604eeddc0SDimitry Andric   unsigned ArgNo = 0;
2357fcaf7f86SDimitry Andric   unsigned LabelNo = 0;
235804eeddc0SDimitry Andric   for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2359fcaf7f86SDimitry Andric     if (CI.Type == InlineAsm::isLabel) {
2360fcaf7f86SDimitry Andric       ++LabelNo;
2361fcaf7f86SDimitry Andric       continue;
2362fcaf7f86SDimitry Andric     }
2363fcaf7f86SDimitry Andric 
236404eeddc0SDimitry Andric     // Only deal with constraints that correspond to call arguments.
236504eeddc0SDimitry Andric     if (!CI.hasArg())
236604eeddc0SDimitry Andric       continue;
236704eeddc0SDimitry Andric 
236804eeddc0SDimitry Andric     if (CI.isIndirect) {
236904eeddc0SDimitry Andric       const Value *Arg = Call.getArgOperand(ArgNo);
237081ad6265SDimitry Andric       Check(Arg->getType()->isPointerTy(),
237181ad6265SDimitry Andric             "Operand for indirect constraint must have pointer type", &Call);
237204eeddc0SDimitry Andric 
237381ad6265SDimitry Andric       Check(Call.getParamElementType(ArgNo),
237404eeddc0SDimitry Andric             "Operand for indirect constraint must have elementtype attribute",
237504eeddc0SDimitry Andric             &Call);
237604eeddc0SDimitry Andric     } else {
237781ad6265SDimitry Andric       Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
237804eeddc0SDimitry Andric             "Elementtype attribute can only be applied for indirect "
237981ad6265SDimitry Andric             "constraints",
238081ad6265SDimitry Andric             &Call);
238104eeddc0SDimitry Andric     }
238204eeddc0SDimitry Andric 
238304eeddc0SDimitry Andric     ArgNo++;
238404eeddc0SDimitry Andric   }
2385fcaf7f86SDimitry Andric 
2386fcaf7f86SDimitry Andric   if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2387fcaf7f86SDimitry Andric     Check(LabelNo == CallBr->getNumIndirectDests(),
2388fcaf7f86SDimitry Andric           "Number of label constraints does not match number of callbr dests",
2389fcaf7f86SDimitry Andric           &Call);
2390fcaf7f86SDimitry Andric   } else {
2391fcaf7f86SDimitry Andric     Check(LabelNo == 0, "Label constraints can only be used with callbr",
2392fcaf7f86SDimitry Andric           &Call);
2393fcaf7f86SDimitry Andric   }
239404eeddc0SDimitry Andric }
239504eeddc0SDimitry Andric 
23960b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
23970b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
23980b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
23990b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
24000b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
24010b57cec5SDimitry Andric 
240281ad6265SDimitry Andric   Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
24030b57cec5SDimitry Andric             !Call.onlyAccessesArgMemory(),
24040b57cec5SDimitry Andric         "gc.statepoint must read and write all memory to preserve "
24050b57cec5SDimitry Andric         "reordering restrictions required by safepoint semantics",
24060b57cec5SDimitry Andric         Call);
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric   const int64_t NumPatchBytes =
24090b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
24100b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
241181ad6265SDimitry Andric   Check(NumPatchBytes >= 0,
24120b57cec5SDimitry Andric         "gc.statepoint number of patchable bytes must be "
24130b57cec5SDimitry Andric         "positive",
24140b57cec5SDimitry Andric         Call);
24150b57cec5SDimitry Andric 
241681ad6265SDimitry Andric   Type *TargetElemType = Call.getParamElementType(2);
241781ad6265SDimitry Andric   Check(TargetElemType,
241881ad6265SDimitry Andric         "gc.statepoint callee argument must have elementtype attribute", Call);
241981ad6265SDimitry Andric   FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
242081ad6265SDimitry Andric   Check(TargetFuncType,
242181ad6265SDimitry Andric         "gc.statepoint callee elementtype must be function type", Call);
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
242481ad6265SDimitry Andric   Check(NumCallArgs >= 0,
24250b57cec5SDimitry Andric         "gc.statepoint number of arguments to underlying call "
24260b57cec5SDimitry Andric         "must be positive",
24270b57cec5SDimitry Andric         Call);
24280b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
24290b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
243081ad6265SDimitry Andric     Check(NumCallArgs >= NumParams,
24310b57cec5SDimitry Andric           "gc.statepoint mismatch in number of vararg call args", Call);
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric     // TODO: Remove this limitation
243481ad6265SDimitry Andric     Check(TargetFuncType->getReturnType()->isVoidTy(),
24350b57cec5SDimitry Andric           "gc.statepoint doesn't support wrapping non-void "
24360b57cec5SDimitry Andric           "vararg functions yet",
24370b57cec5SDimitry Andric           Call);
24380b57cec5SDimitry Andric   } else
243981ad6265SDimitry Andric     Check(NumCallArgs == NumParams,
24400b57cec5SDimitry Andric           "gc.statepoint mismatch in number of call args", Call);
24410b57cec5SDimitry Andric 
24420b57cec5SDimitry Andric   const uint64_t Flags
24430b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
244481ad6265SDimitry Andric   Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
24450b57cec5SDimitry Andric         "unknown flag used in gc.statepoint flags argument", Call);
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
24480b57cec5SDimitry Andric   // the type of the wrapped callee.
24490b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
24500b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
24510b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
24520b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
245381ad6265SDimitry Andric     Check(ArgType == ParamType,
24540b57cec5SDimitry Andric           "gc.statepoint call argument does not match wrapped "
24550b57cec5SDimitry Andric           "function type",
24560b57cec5SDimitry Andric           Call);
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
2459349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
246081ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
246181ad6265SDimitry Andric             "Attribute 'sret' cannot be used for vararg call arguments!", Call);
24620b57cec5SDimitry Andric     }
24630b57cec5SDimitry Andric   }
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
246881ad6265SDimitry Andric   Check(isa<ConstantInt>(NumTransitionArgsV),
24690b57cec5SDimitry Andric         "gc.statepoint number of transition arguments "
24700b57cec5SDimitry Andric         "must be constant integer",
24710b57cec5SDimitry Andric         Call);
24720b57cec5SDimitry Andric   const int NumTransitionArgs =
24730b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
247481ad6265SDimitry Andric   Check(NumTransitionArgs == 0,
2475e8d8bef9SDimitry Andric         "gc.statepoint w/inline transition bundle is deprecated", Call);
2476e8d8bef9SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
24775ffd83dbSDimitry Andric 
24780b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
247981ad6265SDimitry Andric   Check(isa<ConstantInt>(NumDeoptArgsV),
24800b57cec5SDimitry Andric         "gc.statepoint number of deoptimization arguments "
24810b57cec5SDimitry Andric         "must be constant integer",
24820b57cec5SDimitry Andric         Call);
24830b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
248481ad6265SDimitry Andric   Check(NumDeoptArgs == 0,
2485e8d8bef9SDimitry Andric         "gc.statepoint w/inline deopt operands is deprecated", Call);
24865ffd83dbSDimitry Andric 
2487e8d8bef9SDimitry Andric   const int ExpectedNumArgs = 7 + NumCallArgs;
248881ad6265SDimitry Andric   Check(ExpectedNumArgs == (int)Call.arg_size(),
2489e8d8bef9SDimitry Andric         "gc.statepoint too many arguments", Call);
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
24920b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
24930b57cec5SDimitry Andric   // of the same statepoint sequence
24940b57cec5SDimitry Andric   for (const User *U : Call.users()) {
24950b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
249681ad6265SDimitry Andric     Check(UserCall, "illegal use of statepoint token", Call, U);
24970b57cec5SDimitry Andric     if (!UserCall)
24980b57cec5SDimitry Andric       continue;
249981ad6265SDimitry Andric     Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
25000b57cec5SDimitry Andric           "gc.result or gc.relocate are the only value uses "
25010b57cec5SDimitry Andric           "of a gc.statepoint",
25020b57cec5SDimitry Andric           Call, U);
25030b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
250481ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
25050b57cec5SDimitry Andric             "gc.result connected to wrong gc.statepoint", Call, UserCall);
25060b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
250781ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
25080b57cec5SDimitry Andric             "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
25090b57cec5SDimitry Andric     }
25100b57cec5SDimitry Andric   }
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
25130b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
25140b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
25150b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
25160b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
25170b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
25180b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
25190b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
25200b57cec5SDimitry Andric }
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
25230b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
25240b57cec5SDimitry Andric     Function *F = Counts.first;
25250b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
25260b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
252781ad6265SDimitry Andric     Check(MaxRecoveredIndex <= EscapedObjectCount,
25280b57cec5SDimitry Andric           "all indices passed to llvm.localrecover must be less than the "
25290b57cec5SDimitry Andric           "number of arguments passed to llvm.localescape in the parent "
25300b57cec5SDimitry Andric           "function",
25310b57cec5SDimitry Andric           F);
25320b57cec5SDimitry Andric   }
25330b57cec5SDimitry Andric }
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
25360b57cec5SDimitry Andric   BasicBlock *UnwindDest;
25370b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
25380b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
25390b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
25400b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
25410b57cec5SDimitry Andric   else
25420b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
25430b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
25440b57cec5SDimitry Andric }
25450b57cec5SDimitry Andric 
25460b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
25470b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
25480b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
25490b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
25500b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
25510b57cec5SDimitry Andric     if (Visited.count(PredPad))
25520b57cec5SDimitry Andric       continue;
25530b57cec5SDimitry Andric     Active.insert(PredPad);
25540b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
25550b57cec5SDimitry Andric     do {
25560b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
25570b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
25580b57cec5SDimitry Andric         // Found a cycle; report error
25590b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
25600b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
25610b57cec5SDimitry Andric         do {
25620b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
25630b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
25640b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
25650b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
25660b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
25670b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
256881ad6265SDimitry Andric         Check(false, "EH pads can't handle each other's exceptions",
25690b57cec5SDimitry Andric               ArrayRef<Instruction *>(CycleNodes));
25700b57cec5SDimitry Andric       }
25710b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
25720b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
25730b57cec5SDimitry Andric         break;
25740b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
25750b57cec5SDimitry Andric       PredPad = SuccPad;
25760b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
25770b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
25780b57cec5SDimitry Andric         break;
25790b57cec5SDimitry Andric       Terminator = TermI->second;
25800b57cec5SDimitry Andric       Active.insert(PredPad);
25810b57cec5SDimitry Andric     } while (true);
25820b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
25830b57cec5SDimitry Andric     // nodes' successors.
25840b57cec5SDimitry Andric     Active.clear();
25850b57cec5SDimitry Andric   }
25860b57cec5SDimitry Andric }
25870b57cec5SDimitry Andric 
25880b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
25890b57cec5SDimitry Andric //
25900b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
25910b57cec5SDimitry Andric   visitGlobalValue(F);
25920b57cec5SDimitry Andric 
25930b57cec5SDimitry Andric   // Check function arguments.
25940b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
25950b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
25960b57cec5SDimitry Andric 
259781ad6265SDimitry Andric   Check(&Context == &F.getContext(),
25980b57cec5SDimitry Andric         "Function context does not match Module context!", &F);
25990b57cec5SDimitry Andric 
260081ad6265SDimitry Andric   Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
260181ad6265SDimitry Andric   Check(FT->getNumParams() == NumArgs,
26020b57cec5SDimitry Andric         "# formal arguments must match # of arguments for function type!", &F,
26030b57cec5SDimitry Andric         FT);
260481ad6265SDimitry Andric   Check(F.getReturnType()->isFirstClassType() ||
26050b57cec5SDimitry Andric             F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
26060b57cec5SDimitry Andric         "Functions cannot return aggregate values!", &F);
26070b57cec5SDimitry Andric 
260881ad6265SDimitry Andric   Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
26090b57cec5SDimitry Andric         "Invalid struct return type!", &F);
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
26120b57cec5SDimitry Andric 
261381ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, FT->getNumParams()),
26140b57cec5SDimitry Andric         "Attribute after last parameter!", &F);
26150b57cec5SDimitry Andric 
2616fe6060f1SDimitry Andric   bool IsIntrinsic = F.isIntrinsic();
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric   // Check function attributes.
261904eeddc0SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
26220b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
26230b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
262481ad6265SDimitry Andric   Check(!Attrs.hasFnAttr(Attribute::Builtin),
26250b57cec5SDimitry Andric         "Attribute 'builtin' can only be applied to a callsite.", &F);
26260b57cec5SDimitry Andric 
262781ad6265SDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2628fe6060f1SDimitry Andric         "Attribute 'elementtype' can only be applied to a callsite.", &F);
2629fe6060f1SDimitry Andric 
26300b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
26310b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
26320b57cec5SDimitry Andric   // restrictions can be lifted.
26330b57cec5SDimitry Andric   switch (F.getCallingConv()) {
26340b57cec5SDimitry Andric   default:
26350b57cec5SDimitry Andric   case CallingConv::C:
26360b57cec5SDimitry Andric     break;
2637e8d8bef9SDimitry Andric   case CallingConv::X86_INTR: {
263881ad6265SDimitry Andric     Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2639e8d8bef9SDimitry Andric           "Calling convention parameter requires byval", &F);
2640e8d8bef9SDimitry Andric     break;
2641e8d8bef9SDimitry Andric   }
26420b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
26430b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
264406c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_Chain:
264506c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_ChainPreserve:
264681ad6265SDimitry Andric     Check(F.getReturnType()->isVoidTy(),
26470b57cec5SDimitry Andric           "Calling convention requires void return type", &F);
2648bdd1243dSDimitry Andric     [[fallthrough]];
26490b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
26500b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
26510b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
26520b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
26530b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
265481ad6265SDimitry Andric     Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
2655e8d8bef9SDimitry Andric     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2656e8d8bef9SDimitry Andric       const unsigned StackAS = DL.getAllocaAddrSpace();
2657e8d8bef9SDimitry Andric       unsigned i = 0;
2658e8d8bef9SDimitry Andric       for (const Argument &Arg : F.args()) {
265981ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
2660e8d8bef9SDimitry Andric               "Calling convention disallows byval", &F);
266181ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2662e8d8bef9SDimitry Andric               "Calling convention disallows preallocated", &F);
266381ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2664e8d8bef9SDimitry Andric               "Calling convention disallows inalloca", &F);
2665e8d8bef9SDimitry Andric 
2666349cc55cSDimitry Andric         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2667e8d8bef9SDimitry Andric           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2668e8d8bef9SDimitry Andric           // value here.
266981ad6265SDimitry Andric           Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2670e8d8bef9SDimitry Andric                 "Calling convention disallows stack byref", &F);
2671e8d8bef9SDimitry Andric         }
2672e8d8bef9SDimitry Andric 
2673e8d8bef9SDimitry Andric         ++i;
2674e8d8bef9SDimitry Andric       }
2675e8d8bef9SDimitry Andric     }
2676e8d8bef9SDimitry Andric 
2677bdd1243dSDimitry Andric     [[fallthrough]];
26780b57cec5SDimitry Andric   case CallingConv::Fast:
26790b57cec5SDimitry Andric   case CallingConv::Cold:
26800b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
26810b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
26820b57cec5SDimitry Andric   case CallingConv::PTX_Device:
268381ad6265SDimitry Andric     Check(!F.isVarArg(),
268481ad6265SDimitry Andric           "Calling convention does not support varargs or "
26850b57cec5SDimitry Andric           "perfect forwarding!",
26860b57cec5SDimitry Andric           &F);
26870b57cec5SDimitry Andric     break;
26880b57cec5SDimitry Andric   }
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
26910b57cec5SDimitry Andric   unsigned i = 0;
26920b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
269381ad6265SDimitry Andric     Check(Arg.getType() == FT->getParamType(i),
26940b57cec5SDimitry Andric           "Argument value does not match function argument type!", &Arg,
26950b57cec5SDimitry Andric           FT->getParamType(i));
269681ad6265SDimitry Andric     Check(Arg.getType()->isFirstClassType(),
26970b57cec5SDimitry Andric           "Function arguments must have first-class types!", &Arg);
2698fe6060f1SDimitry Andric     if (!IsIntrinsic) {
269981ad6265SDimitry Andric       Check(!Arg.getType()->isMetadataTy(),
27000b57cec5SDimitry Andric             "Function takes metadata but isn't an intrinsic", &Arg, &F);
270181ad6265SDimitry Andric       Check(!Arg.getType()->isTokenTy(),
27020b57cec5SDimitry Andric             "Function takes token but isn't an intrinsic", &Arg, &F);
270381ad6265SDimitry Andric       Check(!Arg.getType()->isX86_AMXTy(),
2704fe6060f1SDimitry Andric             "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
27050b57cec5SDimitry Andric     }
27060b57cec5SDimitry Andric 
27070b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
2708349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
27090b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
27100b57cec5SDimitry Andric     }
27110b57cec5SDimitry Andric     ++i;
27120b57cec5SDimitry Andric   }
27130b57cec5SDimitry Andric 
2714fe6060f1SDimitry Andric   if (!IsIntrinsic) {
271581ad6265SDimitry Andric     Check(!F.getReturnType()->isTokenTy(),
2716fe6060f1SDimitry Andric           "Function returns a token but isn't an intrinsic", &F);
271781ad6265SDimitry Andric     Check(!F.getReturnType()->isX86_AMXTy(),
2718fe6060f1SDimitry Andric           "Function returns a x86_amx but isn't an intrinsic", &F);
2719fe6060f1SDimitry Andric   }
27200b57cec5SDimitry Andric 
27210b57cec5SDimitry Andric   // Get the function metadata attachments.
27220b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
27230b57cec5SDimitry Andric   F.getAllMetadata(MDs);
27240b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
27250b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric   // Check validity of the personality function
27280b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
27290b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
27300b57cec5SDimitry Andric     if (Per)
273181ad6265SDimitry Andric       Check(Per->getParent() == F.getParent(),
273281ad6265SDimitry Andric             "Referencing personality function in another module!", &F,
273381ad6265SDimitry Andric             F.getParent(), Per, Per->getParent());
27340b57cec5SDimitry Andric   }
27350b57cec5SDimitry Andric 
273606c3fb27SDimitry Andric   // EH funclet coloring can be expensive, recompute on-demand
273706c3fb27SDimitry Andric   BlockEHFuncletColors.clear();
273806c3fb27SDimitry Andric 
27390b57cec5SDimitry Andric   if (F.isMaterializable()) {
27400b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
274181ad6265SDimitry Andric     Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
27420b57cec5SDimitry Andric           MDs.empty() ? nullptr : MDs.front().second);
27430b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
27440b57cec5SDimitry Andric     for (const auto &I : MDs) {
27450b57cec5SDimitry Andric       // This is used for call site debug information.
274681ad6265SDimitry Andric       CheckDI(I.first != LLVMContext::MD_dbg ||
27470b57cec5SDimitry Andric                   !cast<DISubprogram>(I.second)->isDistinct(),
27480b57cec5SDimitry Andric               "function declaration may only have a unique !dbg attachment",
27490b57cec5SDimitry Andric               &F);
275081ad6265SDimitry Andric       Check(I.first != LLVMContext::MD_prof,
27510b57cec5SDimitry Andric             "function declaration may not have a !prof attachment", &F);
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric       // Verify the metadata itself.
27545ffd83dbSDimitry Andric       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
27550b57cec5SDimitry Andric     }
275681ad6265SDimitry Andric     Check(!F.hasPersonalityFn(),
27570b57cec5SDimitry Andric           "Function declaration shouldn't have a personality routine", &F);
27580b57cec5SDimitry Andric   } else {
27590b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
27600b57cec5SDimitry Andric     // is not legal to define intrinsics.
276181ad6265SDimitry Andric     Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
27620b57cec5SDimitry Andric 
27630b57cec5SDimitry Andric     // Check the entry node
27640b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
276581ad6265SDimitry Andric     Check(pred_empty(Entry),
27660b57cec5SDimitry Andric           "Entry block to function must not have predecessors!", Entry);
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
27690b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
277081ad6265SDimitry Andric       Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
27710b57cec5SDimitry Andric             "blockaddress may not be used with the entry block!", Entry);
27720b57cec5SDimitry Andric     }
27730b57cec5SDimitry Andric 
2774bdd1243dSDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2775bdd1243dSDimitry Andric              NumKCFIAttachments = 0;
27760b57cec5SDimitry Andric     // Visit metadata attachments.
27770b57cec5SDimitry Andric     for (const auto &I : MDs) {
27780b57cec5SDimitry Andric       // Verify that the attachment is legal.
27795ffd83dbSDimitry Andric       auto AllowLocs = AreDebugLocsAllowed::No;
27800b57cec5SDimitry Andric       switch (I.first) {
27810b57cec5SDimitry Andric       default:
27820b57cec5SDimitry Andric         break;
27830b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
27840b57cec5SDimitry Andric         ++NumDebugAttachments;
278581ad6265SDimitry Andric         CheckDI(NumDebugAttachments == 1,
27860b57cec5SDimitry Andric                 "function must have a single !dbg attachment", &F, I.second);
278781ad6265SDimitry Andric         CheckDI(isa<DISubprogram>(I.second),
27880b57cec5SDimitry Andric                 "function !dbg attachment must be a subprogram", &F, I.second);
278981ad6265SDimitry Andric         CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
2790e8d8bef9SDimitry Andric                 "function definition may only have a distinct !dbg attachment",
2791e8d8bef9SDimitry Andric                 &F);
2792e8d8bef9SDimitry Andric 
27930b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
27940b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
279581ad6265SDimitry Andric         CheckDI(!AttachedTo || AttachedTo == &F,
27960b57cec5SDimitry Andric                 "DISubprogram attached to more than one function", SP, &F);
27970b57cec5SDimitry Andric         AttachedTo = &F;
27985ffd83dbSDimitry Andric         AllowLocs = AreDebugLocsAllowed::Yes;
27990b57cec5SDimitry Andric         break;
28000b57cec5SDimitry Andric       }
28010b57cec5SDimitry Andric       case LLVMContext::MD_prof:
28020b57cec5SDimitry Andric         ++NumProfAttachments;
280381ad6265SDimitry Andric         Check(NumProfAttachments == 1,
28040b57cec5SDimitry Andric               "function must have a single !prof attachment", &F, I.second);
28050b57cec5SDimitry Andric         break;
2806bdd1243dSDimitry Andric       case LLVMContext::MD_kcfi_type:
2807bdd1243dSDimitry Andric         ++NumKCFIAttachments;
2808bdd1243dSDimitry Andric         Check(NumKCFIAttachments == 1,
2809bdd1243dSDimitry Andric               "function must have a single !kcfi_type attachment", &F,
2810bdd1243dSDimitry Andric               I.second);
2811bdd1243dSDimitry Andric         break;
28120b57cec5SDimitry Andric       }
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric       // Verify the metadata itself.
28155ffd83dbSDimitry Andric       visitMDNode(*I.second, AllowLocs);
28160b57cec5SDimitry Andric     }
28170b57cec5SDimitry Andric   }
28180b57cec5SDimitry Andric 
28190b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
28200b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
28210b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
28220b57cec5SDimitry Andric   // uses.
2823fe6060f1SDimitry Andric   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
28240b57cec5SDimitry Andric     const User *U;
2825349cc55cSDimitry Andric     if (F.hasAddressTaken(&U, false, true, false,
2826349cc55cSDimitry Andric                           /*IgnoreARCAttachedCall=*/true))
282781ad6265SDimitry Andric       Check(false, "Invalid user of intrinsic instruction!", U);
28280b57cec5SDimitry Andric   }
28290b57cec5SDimitry Andric 
2830fe6060f1SDimitry Andric   // Check intrinsics' signatures.
2831fe6060f1SDimitry Andric   switch (F.getIntrinsicID()) {
2832fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_base: {
2833fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
283481ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
283581ad6265SDimitry Andric     Check(isa<PointerType>(F.getReturnType()),
2836fe6060f1SDimitry Andric           "gc.get.pointer.base must return a pointer", F);
283781ad6265SDimitry Andric     Check(FT->getParamType(0) == F.getReturnType(),
283881ad6265SDimitry Andric           "gc.get.pointer.base operand and result must be of the same type", F);
2839fe6060f1SDimitry Andric     break;
2840fe6060f1SDimitry Andric   }
2841fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_offset: {
2842fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
284381ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
284481ad6265SDimitry Andric     Check(isa<PointerType>(FT->getParamType(0)),
2845fe6060f1SDimitry Andric           "gc.get.pointer.offset operand must be a pointer", F);
284681ad6265SDimitry Andric     Check(F.getReturnType()->isIntegerTy(),
2847fe6060f1SDimitry Andric           "gc.get.pointer.offset must return integer", F);
2848fe6060f1SDimitry Andric     break;
2849fe6060f1SDimitry Andric   }
2850fe6060f1SDimitry Andric   }
2851fe6060f1SDimitry Andric 
28520b57cec5SDimitry Andric   auto *N = F.getSubprogram();
28530b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
28540b57cec5SDimitry Andric   if (!HasDebugInfo)
28550b57cec5SDimitry Andric     return;
28560b57cec5SDimitry Andric 
28575ffd83dbSDimitry Andric   // Check that all !dbg attachments lead to back to N.
28580b57cec5SDimitry Andric   //
28590b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
28600b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
28610b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
28620b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
28630b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
28640b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
28650b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
28660b57cec5SDimitry Andric     if (!DL)
28670b57cec5SDimitry Andric       return;
28680b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
28690b57cec5SDimitry Andric       return;
28700b57cec5SDimitry Andric 
28710b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
287281ad6265SDimitry Andric     CheckDI(Parent && isa<DILocalScope>(Parent),
287381ad6265SDimitry Andric             "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
28745ffd83dbSDimitry Andric 
28750b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
287681ad6265SDimitry Andric     Check(Scope, "Failed to find DILocalScope", DL);
28775ffd83dbSDimitry Andric 
28785ffd83dbSDimitry Andric     if (!Seen.insert(Scope).second)
28790b57cec5SDimitry Andric       return;
28800b57cec5SDimitry Andric 
28815ffd83dbSDimitry Andric     DISubprogram *SP = Scope->getSubprogram();
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
28840b57cec5SDimitry Andric     // validation in that case
28850b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
28860b57cec5SDimitry Andric       return;
28870b57cec5SDimitry Andric 
288881ad6265SDimitry Andric     CheckDI(SP->describes(&F),
28890b57cec5SDimitry Andric             "!dbg attachment points at wrong subprogram for function", N, &F,
28900b57cec5SDimitry Andric             &I, DL, Scope, SP);
28910b57cec5SDimitry Andric   };
28920b57cec5SDimitry Andric   for (auto &BB : F)
28930b57cec5SDimitry Andric     for (auto &I : BB) {
28940b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
28950b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
28960b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
28970b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
28980b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
28990b57cec5SDimitry Andric       if (BrokenDebugInfo)
29000b57cec5SDimitry Andric         return;
29010b57cec5SDimitry Andric     }
29020b57cec5SDimitry Andric }
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
29050b57cec5SDimitry Andric //
29060b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
29070b57cec5SDimitry Andric   InstsInThisBlock.clear();
29085f757f3fSDimitry Andric   ConvergenceVerifyHelper.visit(BB);
29090b57cec5SDimitry Andric 
29100b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
291181ad6265SDimitry Andric   Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
29120b57cec5SDimitry Andric 
29130b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
29140b57cec5SDimitry Andric   // it.
29150b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
2916e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
29170b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
29180b57cec5SDimitry Andric     llvm::sort(Preds);
29190b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
292081ad6265SDimitry Andric       Check(PN.getNumIncomingValues() == Preds.size(),
29210b57cec5SDimitry Andric             "PHINode should have one entry for each predecessor of its "
29220b57cec5SDimitry Andric             "parent basic block!",
29230b57cec5SDimitry Andric             &PN);
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
29260b57cec5SDimitry Andric       Values.clear();
29270b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
29280b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
29290b57cec5SDimitry Andric         Values.push_back(
29300b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
29310b57cec5SDimitry Andric       llvm::sort(Values);
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
29340b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
29350b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
29360b57cec5SDimitry Andric         // all identical.
29370b57cec5SDimitry Andric         //
293881ad6265SDimitry Andric         Check(i == 0 || Values[i].first != Values[i - 1].first ||
29390b57cec5SDimitry Andric                   Values[i].second == Values[i - 1].second,
29400b57cec5SDimitry Andric               "PHI node has multiple entries for the same basic block with "
29410b57cec5SDimitry Andric               "different incoming values!",
29420b57cec5SDimitry Andric               &PN, Values[i].first, Values[i].second, Values[i - 1].second);
29430b57cec5SDimitry Andric 
29440b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
29450b57cec5SDimitry Andric         // matched up.
294681ad6265SDimitry Andric         Check(Values[i].first == Preds[i],
29470b57cec5SDimitry Andric               "PHI node entries do not match predecessors!", &PN,
29480b57cec5SDimitry Andric               Values[i].first, Preds[i]);
29490b57cec5SDimitry Andric       }
29500b57cec5SDimitry Andric     }
29510b57cec5SDimitry Andric   }
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
29540b57cec5SDimitry Andric   for (auto &I : BB)
29550b57cec5SDimitry Andric   {
295681ad6265SDimitry Andric     Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
29570b57cec5SDimitry Andric   }
29585f757f3fSDimitry Andric 
29595f757f3fSDimitry Andric   // Confirm that no issues arise from the debug program.
29605f757f3fSDimitry Andric   if (BB.IsNewDbgInfoFormat) {
29615f757f3fSDimitry Andric     // Configure the validate function to not fire assertions, instead print
29625f757f3fSDimitry Andric     // errors and return true if there's a problem.
29635f757f3fSDimitry Andric     bool RetVal = BB.validateDbgValues(false, true, OS);
29645f757f3fSDimitry Andric     Check(!RetVal, "Invalid configuration of new-debug-info data found");
29655f757f3fSDimitry Andric   }
29660b57cec5SDimitry Andric }
29670b57cec5SDimitry Andric 
29680b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
29690b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
297081ad6265SDimitry Andric   Check(&I == I.getParent()->getTerminator(),
29710b57cec5SDimitry Andric         "Terminator found in the middle of a basic block!", I.getParent());
29720b57cec5SDimitry Andric   visitInstruction(I);
29730b57cec5SDimitry Andric }
29740b57cec5SDimitry Andric 
29750b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
29760b57cec5SDimitry Andric   if (BI.isConditional()) {
297781ad6265SDimitry Andric     Check(BI.getCondition()->getType()->isIntegerTy(1),
29780b57cec5SDimitry Andric           "Branch condition is not 'i1' type!", &BI, BI.getCondition());
29790b57cec5SDimitry Andric   }
29800b57cec5SDimitry Andric   visitTerminator(BI);
29810b57cec5SDimitry Andric }
29820b57cec5SDimitry Andric 
29830b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
29840b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
29850b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
29860b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
298781ad6265SDimitry Andric     Check(N == 0,
29880b57cec5SDimitry Andric           "Found return instr that returns non-void in Function of void "
29890b57cec5SDimitry Andric           "return type!",
29900b57cec5SDimitry Andric           &RI, F->getReturnType());
29910b57cec5SDimitry Andric   else
299281ad6265SDimitry Andric     Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
29930b57cec5SDimitry Andric           "Function return type does not match operand "
29940b57cec5SDimitry Andric           "type of return inst!",
29950b57cec5SDimitry Andric           &RI, F->getReturnType());
29960b57cec5SDimitry Andric 
29970b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
29980b57cec5SDimitry Andric   // terminators...
29990b57cec5SDimitry Andric   visitTerminator(RI);
30000b57cec5SDimitry Andric }
30010b57cec5SDimitry Andric 
30020b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
300381ad6265SDimitry Andric   Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
30040b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
30050b57cec5SDimitry Andric   // have the same type as the switched-on value.
30060b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
30070b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
30080b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
3009bdd1243dSDimitry Andric     Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
3010bdd1243dSDimitry Andric           "Case value is not a constant integer.", &SI);
301181ad6265SDimitry Andric     Check(Case.getCaseValue()->getType() == SwitchTy,
30120b57cec5SDimitry Andric           "Switch constants must all be same type as switch value!", &SI);
301381ad6265SDimitry Andric     Check(Constants.insert(Case.getCaseValue()).second,
30140b57cec5SDimitry Andric           "Duplicate integer as switch case", &SI, Case.getCaseValue());
30150b57cec5SDimitry Andric   }
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric   visitTerminator(SI);
30180b57cec5SDimitry Andric }
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
302181ad6265SDimitry Andric   Check(BI.getAddress()->getType()->isPointerTy(),
30220b57cec5SDimitry Andric         "Indirectbr operand must have pointer type!", &BI);
30230b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
302481ad6265SDimitry Andric     Check(BI.getDestination(i)->getType()->isLabelTy(),
30250b57cec5SDimitry Andric           "Indirectbr destinations must all have pointer type!", &BI);
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric   visitTerminator(BI);
30280b57cec5SDimitry Andric }
30290b57cec5SDimitry Andric 
30300b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
303181ad6265SDimitry Andric   Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
3032fe6060f1SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
303381ad6265SDimitry Andric   Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
30340b57cec5SDimitry Andric 
303504eeddc0SDimitry Andric   verifyInlineAsmCall(CBI);
30360b57cec5SDimitry Andric   visitTerminator(CBI);
30370b57cec5SDimitry Andric }
30380b57cec5SDimitry Andric 
30390b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
304081ad6265SDimitry Andric   Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
30410b57cec5SDimitry Andric                                         SI.getOperand(2)),
30420b57cec5SDimitry Andric         "Invalid operands for select instruction!", &SI);
30430b57cec5SDimitry Andric 
304481ad6265SDimitry Andric   Check(SI.getTrueValue()->getType() == SI.getType(),
30450b57cec5SDimitry Andric         "Select values must have same type as select instruction!", &SI);
30460b57cec5SDimitry Andric   visitInstruction(SI);
30470b57cec5SDimitry Andric }
30480b57cec5SDimitry Andric 
30490b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
30500b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
30510b57cec5SDimitry Andric ///
30520b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
305381ad6265SDimitry Andric   Check(false, "User-defined operators should not live outside of a pass!", &I);
30540b57cec5SDimitry Andric }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
30570b57cec5SDimitry Andric   // Get the source and destination types
30580b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30590b57cec5SDimitry Andric   Type *DestTy = I.getType();
30600b57cec5SDimitry Andric 
30610b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
30620b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30630b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
30640b57cec5SDimitry Andric 
306581ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
306681ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
306781ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
30680b57cec5SDimitry Andric         "trunc source and destination must both be a vector or neither", &I);
306981ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric   visitInstruction(I);
30720b57cec5SDimitry Andric }
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
30750b57cec5SDimitry Andric   // Get the source and destination types
30760b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30770b57cec5SDimitry Andric   Type *DestTy = I.getType();
30780b57cec5SDimitry Andric 
30790b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
308081ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
308181ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
308281ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
30830b57cec5SDimitry Andric         "zext source and destination must both be a vector or neither", &I);
30840b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30850b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
30860b57cec5SDimitry Andric 
308781ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
30880b57cec5SDimitry Andric 
30890b57cec5SDimitry Andric   visitInstruction(I);
30900b57cec5SDimitry Andric }
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
30930b57cec5SDimitry Andric   // Get the source and destination types
30940b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
30950b57cec5SDimitry Andric   Type *DestTy = I.getType();
30960b57cec5SDimitry Andric 
30970b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
30980b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
30990b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
31000b57cec5SDimitry Andric 
310181ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
310281ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
310381ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
31040b57cec5SDimitry Andric         "sext source and destination must both be a vector or neither", &I);
310581ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric   visitInstruction(I);
31080b57cec5SDimitry Andric }
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
31110b57cec5SDimitry Andric   // Get the source and destination types
31120b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31130b57cec5SDimitry Andric   Type *DestTy = I.getType();
31140b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
31150b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
31160b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
31170b57cec5SDimitry Andric 
311881ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
311981ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
312081ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
31210b57cec5SDimitry Andric         "fptrunc source and destination must both be a vector or neither", &I);
312281ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   visitInstruction(I);
31250b57cec5SDimitry Andric }
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
31280b57cec5SDimitry Andric   // Get the source and destination types
31290b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31300b57cec5SDimitry Andric   Type *DestTy = I.getType();
31310b57cec5SDimitry Andric 
31320b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
31330b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
31340b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
31350b57cec5SDimitry Andric 
313681ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
313781ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
313881ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
31390b57cec5SDimitry Andric         "fpext source and destination must both be a vector or neither", &I);
314081ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
31410b57cec5SDimitry Andric 
31420b57cec5SDimitry Andric   visitInstruction(I);
31430b57cec5SDimitry Andric }
31440b57cec5SDimitry Andric 
31450b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
31460b57cec5SDimitry Andric   // Get the source and destination types
31470b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31480b57cec5SDimitry Andric   Type *DestTy = I.getType();
31490b57cec5SDimitry Andric 
31500b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31510b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31520b57cec5SDimitry Andric 
315381ad6265SDimitry Andric   Check(SrcVec == DstVec,
31540b57cec5SDimitry Andric         "UIToFP source and dest must both be vector or scalar", &I);
315581ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
31560b57cec5SDimitry Andric         "UIToFP source must be integer or integer vector", &I);
315781ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
31580b57cec5SDimitry Andric         &I);
31590b57cec5SDimitry Andric 
31600b57cec5SDimitry Andric   if (SrcVec && DstVec)
316181ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
31625ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
31630b57cec5SDimitry Andric           "UIToFP source and dest vector length mismatch", &I);
31640b57cec5SDimitry Andric 
31650b57cec5SDimitry Andric   visitInstruction(I);
31660b57cec5SDimitry Andric }
31670b57cec5SDimitry Andric 
31680b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
31690b57cec5SDimitry Andric   // Get the source and destination types
31700b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31710b57cec5SDimitry Andric   Type *DestTy = I.getType();
31720b57cec5SDimitry Andric 
31730b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31740b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31750b57cec5SDimitry Andric 
317681ad6265SDimitry Andric   Check(SrcVec == DstVec,
31770b57cec5SDimitry Andric         "SIToFP source and dest must both be vector or scalar", &I);
317881ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
31790b57cec5SDimitry Andric         "SIToFP source must be integer or integer vector", &I);
318081ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
31810b57cec5SDimitry Andric         &I);
31820b57cec5SDimitry Andric 
31830b57cec5SDimitry Andric   if (SrcVec && DstVec)
318481ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
31855ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
31860b57cec5SDimitry Andric           "SIToFP source and dest vector length mismatch", &I);
31870b57cec5SDimitry Andric 
31880b57cec5SDimitry Andric   visitInstruction(I);
31890b57cec5SDimitry Andric }
31900b57cec5SDimitry Andric 
31910b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
31920b57cec5SDimitry Andric   // Get the source and destination types
31930b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
31940b57cec5SDimitry Andric   Type *DestTy = I.getType();
31950b57cec5SDimitry Andric 
31960b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
31970b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
31980b57cec5SDimitry Andric 
319981ad6265SDimitry Andric   Check(SrcVec == DstVec,
32000b57cec5SDimitry Andric         "FPToUI source and dest must both be vector or scalar", &I);
320181ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
320281ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
32030b57cec5SDimitry Andric         "FPToUI result must be integer or integer vector", &I);
32040b57cec5SDimitry Andric 
32050b57cec5SDimitry Andric   if (SrcVec && DstVec)
320681ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
32075ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
32080b57cec5SDimitry Andric           "FPToUI source and dest vector length mismatch", &I);
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric   visitInstruction(I);
32110b57cec5SDimitry Andric }
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &I) {
32140b57cec5SDimitry Andric   // Get the source and destination types
32150b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32160b57cec5SDimitry Andric   Type *DestTy = I.getType();
32170b57cec5SDimitry Andric 
32180b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
32190b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
32200b57cec5SDimitry Andric 
322181ad6265SDimitry Andric   Check(SrcVec == DstVec,
32220b57cec5SDimitry Andric         "FPToSI source and dest must both be vector or scalar", &I);
322381ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
322481ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
32250b57cec5SDimitry Andric         "FPToSI result must be integer or integer vector", &I);
32260b57cec5SDimitry Andric 
32270b57cec5SDimitry Andric   if (SrcVec && DstVec)
322881ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
32295ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
32300b57cec5SDimitry Andric           "FPToSI source and dest vector length mismatch", &I);
32310b57cec5SDimitry Andric 
32320b57cec5SDimitry Andric   visitInstruction(I);
32330b57cec5SDimitry Andric }
32340b57cec5SDimitry Andric 
32350b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
32360b57cec5SDimitry Andric   // Get the source and destination types
32370b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32380b57cec5SDimitry Andric   Type *DestTy = I.getType();
32390b57cec5SDimitry Andric 
324081ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
32410b57cec5SDimitry Andric 
324281ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
324381ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
32440b57cec5SDimitry Andric         &I);
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
32475ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
32485ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
324981ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
32500b57cec5SDimitry Andric           "PtrToInt Vector width mismatch", &I);
32510b57cec5SDimitry Andric   }
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric   visitInstruction(I);
32540b57cec5SDimitry Andric }
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
32570b57cec5SDimitry Andric   // Get the source and destination types
32580b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32590b57cec5SDimitry Andric   Type *DestTy = I.getType();
32600b57cec5SDimitry Andric 
326181ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
326281ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
32630b57cec5SDimitry Andric 
326481ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
32650b57cec5SDimitry Andric         &I);
32660b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
32675ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
32685ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
326981ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
32700b57cec5SDimitry Andric           "IntToPtr Vector width mismatch", &I);
32710b57cec5SDimitry Andric   }
32720b57cec5SDimitry Andric   visitInstruction(I);
32730b57cec5SDimitry Andric }
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
327681ad6265SDimitry Andric   Check(
32770b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
32780b57cec5SDimitry Andric       "Invalid bitcast", &I);
32790b57cec5SDimitry Andric   visitInstruction(I);
32800b57cec5SDimitry Andric }
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
32830b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32840b57cec5SDimitry Andric   Type *DestTy = I.getType();
32850b57cec5SDimitry Andric 
328681ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
32870b57cec5SDimitry Andric         &I);
328881ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
32890b57cec5SDimitry Andric         &I);
329081ad6265SDimitry Andric   Check(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
32910b57cec5SDimitry Andric         "AddrSpaceCast must be between different address spaces", &I);
32925ffd83dbSDimitry Andric   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
329381ad6265SDimitry Andric     Check(SrcVTy->getElementCount() ==
3294e8d8bef9SDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
32950b57cec5SDimitry Andric           "AddrSpaceCast vector pointer number of elements mismatch", &I);
32960b57cec5SDimitry Andric   visitInstruction(I);
32970b57cec5SDimitry Andric }
32980b57cec5SDimitry Andric 
32990b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
33000b57cec5SDimitry Andric ///
33010b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
33020b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
33030b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
33040b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
33050b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
330681ad6265SDimitry Andric   Check(&PN == &PN.getParent()->front() ||
33070b57cec5SDimitry Andric             isa<PHINode>(--BasicBlock::iterator(&PN)),
33080b57cec5SDimitry Andric         "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
33090b57cec5SDimitry Andric 
33100b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
331181ad6265SDimitry Andric   Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
33140b57cec5SDimitry Andric   // result, and that the incoming blocks are really basic blocks.
33150b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
331681ad6265SDimitry Andric     Check(PN.getType() == IncValue->getType(),
33170b57cec5SDimitry Andric           "PHI node operands are not the same type as the result!", &PN);
33180b57cec5SDimitry Andric   }
33190b57cec5SDimitry Andric 
33200b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
33210b57cec5SDimitry Andric 
33220b57cec5SDimitry Andric   visitInstruction(PN);
33230b57cec5SDimitry Andric }
33240b57cec5SDimitry Andric 
33250b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
332681ad6265SDimitry Andric   Check(Call.getCalledOperand()->getType()->isPointerTy(),
33270b57cec5SDimitry Andric         "Called function must be a pointer!", Call);
33280b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
33290b57cec5SDimitry Andric 
33300b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
33310b57cec5SDimitry Andric   if (FTy->isVarArg())
333281ad6265SDimitry Andric     Check(Call.arg_size() >= FTy->getNumParams(),
333381ad6265SDimitry Andric           "Called function requires more parameters than were provided!", Call);
33340b57cec5SDimitry Andric   else
333581ad6265SDimitry Andric     Check(Call.arg_size() == FTy->getNumParams(),
33360b57cec5SDimitry Andric           "Incorrect number of arguments passed to called function!", Call);
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
33390b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
334081ad6265SDimitry Andric     Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
33410b57cec5SDimitry Andric           "Call parameter type does not match function signature!",
33420b57cec5SDimitry Andric           Call.getArgOperand(i), FTy->getParamType(i), Call);
33430b57cec5SDimitry Andric 
33440b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
33450b57cec5SDimitry Andric 
334681ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, Call.arg_size()),
33470b57cec5SDimitry Andric         "Attribute after last parameter!", Call);
33480b57cec5SDimitry Andric 
3349bdd1243dSDimitry Andric   Function *Callee =
3350bdd1243dSDimitry Andric       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3351bdd1243dSDimitry Andric   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3352bdd1243dSDimitry Andric   if (IsIntrinsic)
3353bdd1243dSDimitry Andric     Check(Callee->getValueType() == FTy,
3354bdd1243dSDimitry Andric           "Intrinsic called with incompatible signature", Call);
3355bdd1243dSDimitry Andric 
335606c3fb27SDimitry Andric   // Disallow calls to functions with the amdgpu_cs_chain[_preserve] calling
335706c3fb27SDimitry Andric   // convention.
335806c3fb27SDimitry Andric   auto CC = Call.getCallingConv();
335906c3fb27SDimitry Andric   Check(CC != CallingConv::AMDGPU_CS_Chain &&
336006c3fb27SDimitry Andric             CC != CallingConv::AMDGPU_CS_ChainPreserve,
336106c3fb27SDimitry Andric         "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
336206c3fb27SDimitry Andric         "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
336306c3fb27SDimitry Andric         Call);
336406c3fb27SDimitry Andric 
336581ad6265SDimitry Andric   auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
336681ad6265SDimitry Andric     if (!Ty->isSized())
336781ad6265SDimitry Andric       return;
336881ad6265SDimitry Andric     Align ABIAlign = DL.getABITypeAlign(Ty);
336981ad6265SDimitry Andric     Align MaxAlign(ParamMaxAlignment);
337081ad6265SDimitry Andric     Check(ABIAlign <= MaxAlign,
337181ad6265SDimitry Andric           "Incorrect alignment of " + Message + " to called function!", Call);
337281ad6265SDimitry Andric   };
337381ad6265SDimitry Andric 
3374bdd1243dSDimitry Andric   if (!IsIntrinsic) {
337581ad6265SDimitry Andric     VerifyTypeAlign(FTy->getReturnType(), "return type");
337681ad6265SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
337781ad6265SDimitry Andric       Type *Ty = FTy->getParamType(i);
337881ad6265SDimitry Andric       VerifyTypeAlign(Ty, "argument passed");
337981ad6265SDimitry Andric     }
3380bdd1243dSDimitry Andric   }
33810b57cec5SDimitry Andric 
3382349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
33830b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
33840b57cec5SDimitry Andric     // declaration is also speculatable.
338581ad6265SDimitry Andric     Check(Callee && Callee->isSpeculatable(),
33860b57cec5SDimitry Andric           "speculatable attribute may not apply to call sites", Call);
33870b57cec5SDimitry Andric   }
33880b57cec5SDimitry Andric 
3389349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
339081ad6265SDimitry Andric     Check(Call.getCalledFunction()->getIntrinsicID() ==
33915ffd83dbSDimitry Andric               Intrinsic::call_preallocated_arg,
33925ffd83dbSDimitry Andric           "preallocated as a call site attribute can only be on "
33935ffd83dbSDimitry Andric           "llvm.call.preallocated.arg");
33945ffd83dbSDimitry Andric   }
33955ffd83dbSDimitry Andric 
33960b57cec5SDimitry Andric   // Verify call attributes.
339704eeddc0SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
34000b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
34010b57cec5SDimitry Andric   // inalloca.
34020b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
34030b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
34040b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
340581ad6265SDimitry Andric       Check(AI->isUsedWithInAlloca(),
34060b57cec5SDimitry Andric             "inalloca argument for call has mismatched alloca", AI, Call);
34070b57cec5SDimitry Andric   }
34080b57cec5SDimitry Andric 
34090b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
34100b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
34110b57cec5SDimitry Andric   // well.
34120b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
34130b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
34140b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
34150b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
341681ad6265SDimitry Andric         Check(AI->isSwiftError(),
34170b57cec5SDimitry Andric               "swifterror argument for call has mismatched alloca", AI, Call);
34180b57cec5SDimitry Andric         continue;
34190b57cec5SDimitry Andric       }
34200b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
342181ad6265SDimitry Andric       Check(ArgI, "swifterror argument should come from an alloca or parameter",
34220b57cec5SDimitry Andric             SwiftErrorArg, Call);
342381ad6265SDimitry Andric       Check(ArgI->hasSwiftErrorAttr(),
34240b57cec5SDimitry Andric             "swifterror argument for call has mismatched parameter", ArgI,
34250b57cec5SDimitry Andric             Call);
34260b57cec5SDimitry Andric     }
34270b57cec5SDimitry Andric 
3428349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
34290b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
34300b57cec5SDimitry Andric       // also has the matching immarg.
343181ad6265SDimitry Andric       Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
343281ad6265SDimitry Andric             "immarg may not apply only to call sites", Call.getArgOperand(i),
343381ad6265SDimitry Andric             Call);
34340b57cec5SDimitry Andric     }
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
34370b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
343881ad6265SDimitry Andric       Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
34390b57cec5SDimitry Andric             "immarg operand has non-immediate parameter", ArgVal, Call);
34400b57cec5SDimitry Andric     }
34415ffd83dbSDimitry Andric 
34425ffd83dbSDimitry Andric     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
34435ffd83dbSDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
34445ffd83dbSDimitry Andric       bool hasOB =
34455ffd83dbSDimitry Andric           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
34465ffd83dbSDimitry Andric       bool isMustTail = Call.isMustTailCall();
344781ad6265SDimitry Andric       Check(hasOB != isMustTail,
34485ffd83dbSDimitry Andric             "preallocated operand either requires a preallocated bundle or "
34495ffd83dbSDimitry Andric             "the call to be musttail (but not both)",
34505ffd83dbSDimitry Andric             ArgVal, Call);
34515ffd83dbSDimitry Andric     }
34520b57cec5SDimitry Andric   }
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric   if (FTy->isVarArg()) {
34550b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
34560b57cec5SDimitry Andric     bool SawNest = false;
34570b57cec5SDimitry Andric     bool SawReturned = false;
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3460349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
34610b57cec5SDimitry Andric         SawNest = true;
3462349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
34630b57cec5SDimitry Andric         SawReturned = true;
34640b57cec5SDimitry Andric     }
34650b57cec5SDimitry Andric 
34660b57cec5SDimitry Andric     // Check attributes on the varargs part.
34670b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
34680b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
3469349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
34700b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
347381ad6265SDimitry Andric         Check(!SawNest, "More than one parameter has attribute nest!", Call);
34740b57cec5SDimitry Andric         SawNest = true;
34750b57cec5SDimitry Andric       }
34760b57cec5SDimitry Andric 
34770b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
347881ad6265SDimitry Andric         Check(!SawReturned, "More than one parameter has attribute returned!",
34790b57cec5SDimitry Andric               Call);
348081ad6265SDimitry Andric         Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
34810b57cec5SDimitry Andric               "Incompatible argument and return types for 'returned' "
34820b57cec5SDimitry Andric               "attribute",
34830b57cec5SDimitry Andric               Call);
34840b57cec5SDimitry Andric         SawReturned = true;
34850b57cec5SDimitry Andric       }
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
34880b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
34890b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
34900b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
34910b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
349281ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
34930b57cec5SDimitry Andric               "Attribute 'sret' cannot be used for vararg call arguments!",
34940b57cec5SDimitry Andric               Call);
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
349781ad6265SDimitry Andric         Check(Idx == Call.arg_size() - 1,
34980b57cec5SDimitry Andric               "inalloca isn't on the last argument!", Call);
34990b57cec5SDimitry Andric     }
35000b57cec5SDimitry Andric   }
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
35030b57cec5SDimitry Andric   if (!IsIntrinsic) {
35040b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
350581ad6265SDimitry Andric       Check(!ParamTy->isMetadataTy(),
35060b57cec5SDimitry Andric             "Function has metadata parameter but isn't an intrinsic", Call);
350781ad6265SDimitry Andric       Check(!ParamTy->isTokenTy(),
35080b57cec5SDimitry Andric             "Function has token parameter but isn't an intrinsic", Call);
35090b57cec5SDimitry Andric     }
35100b57cec5SDimitry Andric   }
35110b57cec5SDimitry Andric 
35120b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
3513fe6060f1SDimitry Andric   if (!Call.getCalledFunction()) {
351481ad6265SDimitry Andric     Check(!FTy->getReturnType()->isTokenTy(),
35150b57cec5SDimitry Andric           "Return type cannot be token for indirect call!");
351681ad6265SDimitry Andric     Check(!FTy->getReturnType()->isX86_AMXTy(),
3517fe6060f1SDimitry Andric           "Return type cannot be x86_amx for indirect call!");
3518fe6060f1SDimitry Andric   }
35190b57cec5SDimitry Andric 
35200b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
35210b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
35220b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
35230b57cec5SDimitry Andric 
3524480093f4SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet", at
352581ad6265SDimitry Andric   // most one "gc-transition", at most one "cfguardtarget", at most one
352681ad6265SDimitry Andric   // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
35270b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
35285ffd83dbSDimitry Andric        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3529fe6060f1SDimitry Andric        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3530bdd1243dSDimitry Andric        FoundPtrauthBundle = false, FoundKCFIBundle = false,
3531fe6060f1SDimitry Andric        FoundAttachedCallBundle = false;
35320b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
35330b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
35340b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
35350b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
353681ad6265SDimitry Andric       Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
35370b57cec5SDimitry Andric       FoundDeoptBundle = true;
35380b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
353981ad6265SDimitry Andric       Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
35400b57cec5SDimitry Andric             Call);
35410b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
35420b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
354381ad6265SDimitry Andric       Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
35440b57cec5SDimitry Andric       FoundFuncletBundle = true;
354581ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
35460b57cec5SDimitry Andric             "Expected exactly one funclet bundle operand", Call);
354781ad6265SDimitry Andric       Check(isa<FuncletPadInst>(BU.Inputs.front()),
35480b57cec5SDimitry Andric             "Funclet bundle operands should correspond to a FuncletPadInst",
35490b57cec5SDimitry Andric             Call);
3550480093f4SDimitry Andric     } else if (Tag == LLVMContext::OB_cfguardtarget) {
355181ad6265SDimitry Andric       Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
355281ad6265SDimitry Andric             Call);
3553480093f4SDimitry Andric       FoundCFGuardTargetBundle = true;
355481ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
3555480093f4SDimitry Andric             "Expected exactly one cfguardtarget bundle operand", Call);
355681ad6265SDimitry Andric     } else if (Tag == LLVMContext::OB_ptrauth) {
355781ad6265SDimitry Andric       Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
355881ad6265SDimitry Andric       FoundPtrauthBundle = true;
355981ad6265SDimitry Andric       Check(BU.Inputs.size() == 2,
356081ad6265SDimitry Andric             "Expected exactly two ptrauth bundle operands", Call);
356181ad6265SDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
356281ad6265SDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
356381ad6265SDimitry Andric             "Ptrauth bundle key operand must be an i32 constant", Call);
356481ad6265SDimitry Andric       Check(BU.Inputs[1]->getType()->isIntegerTy(64),
356581ad6265SDimitry Andric             "Ptrauth bundle discriminator operand must be an i64", Call);
3566bdd1243dSDimitry Andric     } else if (Tag == LLVMContext::OB_kcfi) {
3567bdd1243dSDimitry Andric       Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
3568bdd1243dSDimitry Andric       FoundKCFIBundle = true;
3569bdd1243dSDimitry Andric       Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
3570bdd1243dSDimitry Andric             Call);
3571bdd1243dSDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
3572bdd1243dSDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
3573bdd1243dSDimitry Andric             "Kcfi bundle operand must be an i32 constant", Call);
35745ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_preallocated) {
357581ad6265SDimitry Andric       Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
35765ffd83dbSDimitry Andric             Call);
35775ffd83dbSDimitry Andric       FoundPreallocatedBundle = true;
357881ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
35795ffd83dbSDimitry Andric             "Expected exactly one preallocated bundle operand", Call);
35805ffd83dbSDimitry Andric       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
358181ad6265SDimitry Andric       Check(Input &&
35825ffd83dbSDimitry Andric                 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
35835ffd83dbSDimitry Andric             "\"preallocated\" argument must be a token from "
35845ffd83dbSDimitry Andric             "llvm.call.preallocated.setup",
35855ffd83dbSDimitry Andric             Call);
35865ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_gc_live) {
358781ad6265SDimitry Andric       Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
35885ffd83dbSDimitry Andric       FoundGCLiveBundle = true;
3589fe6060f1SDimitry Andric     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
359081ad6265SDimitry Andric       Check(!FoundAttachedCallBundle,
3591fe6060f1SDimitry Andric             "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3592fe6060f1SDimitry Andric       FoundAttachedCallBundle = true;
3593349cc55cSDimitry Andric       verifyAttachedCallBundle(Call, BU);
35940b57cec5SDimitry Andric     }
35950b57cec5SDimitry Andric   }
35960b57cec5SDimitry Andric 
359781ad6265SDimitry Andric   // Verify that callee and callsite agree on whether to use pointer auth.
359881ad6265SDimitry Andric   Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
359981ad6265SDimitry Andric         "Direct call cannot have a ptrauth bundle", Call);
360081ad6265SDimitry Andric 
36010b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
36020b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
3603bdd1243dSDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info
3604bdd1243dSDimitry Andric   // (Interposable functions are not inlinable, neither are functions without
3605bdd1243dSDimitry Andric   //  definitions.)
36060b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3607bdd1243dSDimitry Andric       !Call.getCalledFunction()->isInterposable() &&
3608bdd1243dSDimitry Andric       !Call.getCalledFunction()->isDeclaration() &&
36090b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
361081ad6265SDimitry Andric     CheckDI(Call.getDebugLoc(),
36110b57cec5SDimitry Andric             "inlinable function call in a function with "
36120b57cec5SDimitry Andric             "debug info must have a !dbg location",
36130b57cec5SDimitry Andric             Call);
36140b57cec5SDimitry Andric 
361504eeddc0SDimitry Andric   if (Call.isInlineAsm())
361604eeddc0SDimitry Andric     verifyInlineAsmCall(Call);
361704eeddc0SDimitry Andric 
36185f757f3fSDimitry Andric   ConvergenceVerifyHelper.visit(Call);
361906c3fb27SDimitry Andric 
36200b57cec5SDimitry Andric   visitInstruction(Call);
36210b57cec5SDimitry Andric }
36220b57cec5SDimitry Andric 
36230eae32dcSDimitry Andric void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3624fe6060f1SDimitry Andric                                          StringRef Context) {
362581ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InAlloca),
3626fe6060f1SDimitry Andric         Twine("inalloca attribute not allowed in ") + Context);
362781ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InReg),
3628fe6060f1SDimitry Andric         Twine("inreg attribute not allowed in ") + Context);
362981ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::SwiftError),
3630fe6060f1SDimitry Andric         Twine("swifterror attribute not allowed in ") + Context);
363181ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::Preallocated),
3632fe6060f1SDimitry Andric         Twine("preallocated attribute not allowed in ") + Context);
363381ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::ByRef),
3634fe6060f1SDimitry Andric         Twine("byref attribute not allowed in ") + Context);
3635fe6060f1SDimitry Andric }
3636fe6060f1SDimitry Andric 
36370b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
36380b57cec5SDimitry Andric /// types with different pointee types and the same address space.
36390b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
36400b57cec5SDimitry Andric   if (L == R)
36410b57cec5SDimitry Andric     return true;
36420b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
36430b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
36440b57cec5SDimitry Andric   if (!PL || !PR)
36450b57cec5SDimitry Andric     return false;
36460b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
36470b57cec5SDimitry Andric }
36480b57cec5SDimitry Andric 
364904eeddc0SDimitry Andric static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
36500b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
36510b57cec5SDimitry Andric       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3652fe6060f1SDimitry Andric       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3653fe6060f1SDimitry Andric       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3654fe6060f1SDimitry Andric       Attribute::ByRef};
365504eeddc0SDimitry Andric   AttrBuilder Copy(C);
36560b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
3657349cc55cSDimitry Andric     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3658fe6060f1SDimitry Andric     if (Attr.isValid())
3659fe6060f1SDimitry Andric       Copy.addAttribute(Attr);
36600b57cec5SDimitry Andric   }
3661e8d8bef9SDimitry Andric 
3662e8d8bef9SDimitry Andric   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3663349cc55cSDimitry Andric   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3664349cc55cSDimitry Andric       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3665349cc55cSDimitry Andric        Attrs.hasParamAttr(I, Attribute::ByRef)))
36660b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
36670b57cec5SDimitry Andric   return Copy;
36680b57cec5SDimitry Andric }
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
367181ad6265SDimitry Andric   Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
36720b57cec5SDimitry Andric 
36730b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
36740b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
36750b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
367681ad6265SDimitry Andric   Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
36770b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched varargs", &CI);
367881ad6265SDimitry Andric   Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
36790b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched return types", &CI);
36800b57cec5SDimitry Andric 
36810b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
368281ad6265SDimitry Andric   Check(F->getCallingConv() == CI.getCallingConv(),
36830b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched calling conv", &CI);
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
36860b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
36870b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
36880b57cec5SDimitry Andric   //   produced by the call or void.
36890b57cec5SDimitry Andric   Value *RetVal = &CI;
36900b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
36910b57cec5SDimitry Andric 
36920b57cec5SDimitry Andric   // Handle the optional bitcast.
36930b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
369481ad6265SDimitry Andric     Check(BI->getOperand(0) == RetVal,
36950b57cec5SDimitry Andric           "bitcast following musttail call must use the call", BI);
36960b57cec5SDimitry Andric     RetVal = BI;
36970b57cec5SDimitry Andric     Next = BI->getNextNode();
36980b57cec5SDimitry Andric   }
36990b57cec5SDimitry Andric 
37000b57cec5SDimitry Andric   // Check the return.
37010b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
370281ad6265SDimitry Andric   Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
370381ad6265SDimitry Andric   Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3704fe6060f1SDimitry Andric             isa<UndefValue>(Ret->getReturnValue()),
37050b57cec5SDimitry Andric         "musttail call result must be returned", Ret);
3706fe6060f1SDimitry Andric 
3707fe6060f1SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
3708fe6060f1SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
3709fe6060f1SDimitry Andric   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3710fe6060f1SDimitry Andric       CI.getCallingConv() == CallingConv::Tail) {
3711fe6060f1SDimitry Andric     StringRef CCName =
3712fe6060f1SDimitry Andric         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3713fe6060f1SDimitry Andric 
3714fe6060f1SDimitry Andric     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3715fe6060f1SDimitry Andric     //   are allowed in swifttailcc call
3716349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
371704eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3718fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3719fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3720fe6060f1SDimitry Andric     }
3721349cc55cSDimitry Andric     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
372204eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3723fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3724fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3725fe6060f1SDimitry Andric     }
3726fe6060f1SDimitry Andric     // - Varargs functions are not allowed
372781ad6265SDimitry Andric     Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3728fe6060f1SDimitry Andric                                      " tail call for varargs function");
3729fe6060f1SDimitry Andric     return;
3730fe6060f1SDimitry Andric   }
3731fe6060f1SDimitry Andric 
3732fe6060f1SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
3733fe6060f1SDimitry Andric   //   parameters or return types may differ in pointee type, but not
3734fe6060f1SDimitry Andric   //   address space.
3735fe6060f1SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
373681ad6265SDimitry Andric     Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
373781ad6265SDimitry Andric           "cannot guarantee tail call due to mismatched parameter counts", &CI);
3738349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
373981ad6265SDimitry Andric       Check(
3740fe6060f1SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3741fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
3742fe6060f1SDimitry Andric     }
3743fe6060f1SDimitry Andric   }
3744fe6060f1SDimitry Andric 
3745fe6060f1SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3746fe6060f1SDimitry Andric   //   returned, preallocated, and inalloca, must match.
3747349cc55cSDimitry Andric   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
374804eeddc0SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
374904eeddc0SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
375081ad6265SDimitry Andric     Check(CallerABIAttrs == CalleeABIAttrs,
3751fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched ABI impacting "
3752fe6060f1SDimitry Andric           "function attributes",
3753fe6060f1SDimitry Andric           &CI, CI.getOperand(I));
3754fe6060f1SDimitry Andric   }
37550b57cec5SDimitry Andric }
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
37580b57cec5SDimitry Andric   visitCallBase(CI);
37590b57cec5SDimitry Andric 
37600b57cec5SDimitry Andric   if (CI.isMustTailCall())
37610b57cec5SDimitry Andric     verifyMustTailCall(CI);
37620b57cec5SDimitry Andric }
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
37650b57cec5SDimitry Andric   visitCallBase(II);
37660b57cec5SDimitry Andric 
37670b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
37680b57cec5SDimitry Andric   // exception handling instruction.
376981ad6265SDimitry Andric   Check(
37700b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
37710b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
37720b57cec5SDimitry Andric       &II);
37730b57cec5SDimitry Andric 
37740b57cec5SDimitry Andric   visitTerminator(II);
37750b57cec5SDimitry Andric }
37760b57cec5SDimitry Andric 
37770b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
37780b57cec5SDimitry Andric ///
37790b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
378081ad6265SDimitry Andric   Check(U.getType() == U.getOperand(0)->getType(),
37810b57cec5SDimitry Andric         "Unary operators must have same type for"
37820b57cec5SDimitry Andric         "operands and result!",
37830b57cec5SDimitry Andric         &U);
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric   switch (U.getOpcode()) {
37860b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
37870b57cec5SDimitry Andric   // floating-point operands.
37880b57cec5SDimitry Andric   case Instruction::FNeg:
378981ad6265SDimitry Andric     Check(U.getType()->isFPOrFPVectorTy(),
37900b57cec5SDimitry Andric           "FNeg operator only works with float types!", &U);
37910b57cec5SDimitry Andric     break;
37920b57cec5SDimitry Andric   default:
37930b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
37940b57cec5SDimitry Andric   }
37950b57cec5SDimitry Andric 
37960b57cec5SDimitry Andric   visitInstruction(U);
37970b57cec5SDimitry Andric }
37980b57cec5SDimitry Andric 
37990b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
38000b57cec5SDimitry Andric /// of the same type!
38010b57cec5SDimitry Andric ///
38020b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
380381ad6265SDimitry Andric   Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
38040b57cec5SDimitry Andric         "Both operands to a binary operator are not of the same type!", &B);
38050b57cec5SDimitry Andric 
38060b57cec5SDimitry Andric   switch (B.getOpcode()) {
38070b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
38080b57cec5SDimitry Andric   // integral operands.
38090b57cec5SDimitry Andric   case Instruction::Add:
38100b57cec5SDimitry Andric   case Instruction::Sub:
38110b57cec5SDimitry Andric   case Instruction::Mul:
38120b57cec5SDimitry Andric   case Instruction::SDiv:
38130b57cec5SDimitry Andric   case Instruction::UDiv:
38140b57cec5SDimitry Andric   case Instruction::SRem:
38150b57cec5SDimitry Andric   case Instruction::URem:
381681ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
38170b57cec5SDimitry Andric           "Integer arithmetic operators only work with integral types!", &B);
381881ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
38190b57cec5SDimitry Andric           "Integer arithmetic operators must have same type "
38200b57cec5SDimitry Andric           "for operands and result!",
38210b57cec5SDimitry Andric           &B);
38220b57cec5SDimitry Andric     break;
38230b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
38240b57cec5SDimitry Andric   // floating-point operands.
38250b57cec5SDimitry Andric   case Instruction::FAdd:
38260b57cec5SDimitry Andric   case Instruction::FSub:
38270b57cec5SDimitry Andric   case Instruction::FMul:
38280b57cec5SDimitry Andric   case Instruction::FDiv:
38290b57cec5SDimitry Andric   case Instruction::FRem:
383081ad6265SDimitry Andric     Check(B.getType()->isFPOrFPVectorTy(),
38310b57cec5SDimitry Andric           "Floating-point arithmetic operators only work with "
38320b57cec5SDimitry Andric           "floating-point types!",
38330b57cec5SDimitry Andric           &B);
383481ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
38350b57cec5SDimitry Andric           "Floating-point arithmetic operators must have same type "
38360b57cec5SDimitry Andric           "for operands and result!",
38370b57cec5SDimitry Andric           &B);
38380b57cec5SDimitry Andric     break;
38390b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
38400b57cec5SDimitry Andric   case Instruction::And:
38410b57cec5SDimitry Andric   case Instruction::Or:
38420b57cec5SDimitry Andric   case Instruction::Xor:
384381ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
38440b57cec5SDimitry Andric           "Logical operators only work with integral types!", &B);
384581ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
384681ad6265SDimitry Andric           "Logical operators must have same type for operands and result!", &B);
38470b57cec5SDimitry Andric     break;
38480b57cec5SDimitry Andric   case Instruction::Shl:
38490b57cec5SDimitry Andric   case Instruction::LShr:
38500b57cec5SDimitry Andric   case Instruction::AShr:
385181ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
38520b57cec5SDimitry Andric           "Shifts only work with integral types!", &B);
385381ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
38540b57cec5SDimitry Andric           "Shift return type must be same as operands!", &B);
38550b57cec5SDimitry Andric     break;
38560b57cec5SDimitry Andric   default:
38570b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
38580b57cec5SDimitry Andric   }
38590b57cec5SDimitry Andric 
38600b57cec5SDimitry Andric   visitInstruction(B);
38610b57cec5SDimitry Andric }
38620b57cec5SDimitry Andric 
38630b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
38640b57cec5SDimitry Andric   // Check that the operands are the same type
38650b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
38660b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
386781ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
38680b57cec5SDimitry Andric         "Both operands to ICmp instruction are not of the same type!", &IC);
38690b57cec5SDimitry Andric   // Check that the operands are the right type
387081ad6265SDimitry Andric   Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
38710b57cec5SDimitry Andric         "Invalid operand types for ICmp instruction", &IC);
38720b57cec5SDimitry Andric   // Check that the predicate is valid.
387381ad6265SDimitry Andric   Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
38740b57cec5SDimitry Andric 
38750b57cec5SDimitry Andric   visitInstruction(IC);
38760b57cec5SDimitry Andric }
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
38790b57cec5SDimitry Andric   // Check that the operands are the same type
38800b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
38810b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
388281ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
38830b57cec5SDimitry Andric         "Both operands to FCmp instruction are not of the same type!", &FC);
38840b57cec5SDimitry Andric   // Check that the operands are the right type
388581ad6265SDimitry Andric   Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
388681ad6265SDimitry Andric         &FC);
38870b57cec5SDimitry Andric   // Check that the predicate is valid.
388881ad6265SDimitry Andric   Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
38890b57cec5SDimitry Andric 
38900b57cec5SDimitry Andric   visitInstruction(FC);
38910b57cec5SDimitry Andric }
38920b57cec5SDimitry Andric 
38930b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
389481ad6265SDimitry Andric   Check(ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
38950b57cec5SDimitry Andric         "Invalid extractelement operands!", &EI);
38960b57cec5SDimitry Andric   visitInstruction(EI);
38970b57cec5SDimitry Andric }
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
390081ad6265SDimitry Andric   Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
39010b57cec5SDimitry Andric                                            IE.getOperand(2)),
39020b57cec5SDimitry Andric         "Invalid insertelement operands!", &IE);
39030b57cec5SDimitry Andric   visitInstruction(IE);
39040b57cec5SDimitry Andric }
39050b57cec5SDimitry Andric 
39060b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
390781ad6265SDimitry Andric   Check(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
39085ffd83dbSDimitry Andric                                            SV.getShuffleMask()),
39090b57cec5SDimitry Andric         "Invalid shufflevector operands!", &SV);
39100b57cec5SDimitry Andric   visitInstruction(SV);
39110b57cec5SDimitry Andric }
39120b57cec5SDimitry Andric 
39130b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
39140b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
39150b57cec5SDimitry Andric 
391681ad6265SDimitry Andric   Check(isa<PointerType>(TargetTy),
39170b57cec5SDimitry Andric         "GEP base pointer is not a vector or a vector of pointers", &GEP);
391881ad6265SDimitry Andric   Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
39190b57cec5SDimitry Andric 
392006c3fb27SDimitry Andric   if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
392106c3fb27SDimitry Andric     SmallPtrSet<Type *, 4> Visited;
392206c3fb27SDimitry Andric     Check(!STy->containsScalableVectorType(&Visited),
392306c3fb27SDimitry Andric           "getelementptr cannot target structure that contains scalable vector"
392406c3fb27SDimitry Andric           "type",
392506c3fb27SDimitry Andric           &GEP);
392606c3fb27SDimitry Andric   }
392706c3fb27SDimitry Andric 
3928e8d8bef9SDimitry Andric   SmallVector<Value *, 16> Idxs(GEP.indices());
392981ad6265SDimitry Andric   Check(
393081ad6265SDimitry Andric       all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
39310b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
39320b57cec5SDimitry Andric   Type *ElTy =
39330b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
393481ad6265SDimitry Andric   Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
39350b57cec5SDimitry Andric 
393681ad6265SDimitry Andric   Check(GEP.getType()->isPtrOrPtrVectorTy() &&
39370b57cec5SDimitry Andric             GEP.getResultElementType() == ElTy,
39380b57cec5SDimitry Andric         "GEP is not of right type for indices!", &GEP, ElTy);
39390b57cec5SDimitry Andric 
39405ffd83dbSDimitry Andric   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
39410b57cec5SDimitry Andric     // Additional checks for vector GEPs.
39425ffd83dbSDimitry Andric     ElementCount GEPWidth = GEPVTy->getElementCount();
39430b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
394481ad6265SDimitry Andric       Check(
39455ffd83dbSDimitry Andric           GEPWidth ==
39465ffd83dbSDimitry Andric               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
39470b57cec5SDimitry Andric           "Vector GEP result width doesn't match operand's", &GEP);
39480b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
39490b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
39505ffd83dbSDimitry Andric       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
39515ffd83dbSDimitry Andric         ElementCount IndexWidth = IndexVTy->getElementCount();
395281ad6265SDimitry Andric         Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
39530b57cec5SDimitry Andric       }
395481ad6265SDimitry Andric       Check(IndexTy->isIntOrIntVectorTy(),
39550b57cec5SDimitry Andric             "All GEP indices should be of integer type");
39560b57cec5SDimitry Andric     }
39570b57cec5SDimitry Andric   }
39580b57cec5SDimitry Andric 
39590b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
396081ad6265SDimitry Andric     Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
39610b57cec5SDimitry Andric           "GEP address space doesn't match type", &GEP);
39620b57cec5SDimitry Andric   }
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   visitInstruction(GEP);
39650b57cec5SDimitry Andric }
39660b57cec5SDimitry Andric 
39670b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
39680b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
39690b57cec5SDimitry Andric }
39700b57cec5SDimitry Andric 
397106c3fb27SDimitry Andric /// Verify !range and !absolute_symbol metadata. These have the same
397206c3fb27SDimitry Andric /// restrictions, except !absolute_symbol allows the full set.
397306c3fb27SDimitry Andric void Verifier::verifyRangeMetadata(const Value &I, const MDNode *Range,
397406c3fb27SDimitry Andric                                    Type *Ty, bool IsAbsoluteSymbol) {
39750b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
397681ad6265SDimitry Andric   Check(NumOperands % 2 == 0, "Unfinished range!", Range);
39770b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
397881ad6265SDimitry Andric   Check(NumRanges >= 1, "It should have at least one range!", Range);
39790b57cec5SDimitry Andric 
39800b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
39810b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
39820b57cec5SDimitry Andric     ConstantInt *Low =
39830b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
398481ad6265SDimitry Andric     Check(Low, "The lower limit must be an integer!", Low);
39850b57cec5SDimitry Andric     ConstantInt *High =
39860b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
398781ad6265SDimitry Andric     Check(High, "The upper limit must be an integer!", High);
398806c3fb27SDimitry Andric     Check(High->getType() == Low->getType() &&
398906c3fb27SDimitry Andric           High->getType() == Ty->getScalarType(),
39900b57cec5SDimitry Andric           "Range types must match instruction type!", &I);
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric     APInt HighV = High->getValue();
39930b57cec5SDimitry Andric     APInt LowV = Low->getValue();
399406c3fb27SDimitry Andric 
399506c3fb27SDimitry Andric     // ConstantRange asserts if the ranges are the same except for the min/max
399606c3fb27SDimitry Andric     // value. Leave the cases it tolerates for the empty range error below.
399706c3fb27SDimitry Andric     Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
399806c3fb27SDimitry Andric           "The upper and lower limits cannot be the same value", &I);
399906c3fb27SDimitry Andric 
40000b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
400106c3fb27SDimitry Andric     Check(!CurRange.isEmptySet() && (IsAbsoluteSymbol || !CurRange.isFullSet()),
40020b57cec5SDimitry Andric           "Range must not be empty!", Range);
40030b57cec5SDimitry Andric     if (i != 0) {
400481ad6265SDimitry Andric       Check(CurRange.intersectWith(LastRange).isEmptySet(),
40050b57cec5SDimitry Andric             "Intervals are overlapping", Range);
400681ad6265SDimitry Andric       Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
40070b57cec5SDimitry Andric             Range);
400881ad6265SDimitry Andric       Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
40090b57cec5SDimitry Andric             Range);
40100b57cec5SDimitry Andric     }
40110b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
40120b57cec5SDimitry Andric   }
40130b57cec5SDimitry Andric   if (NumRanges > 2) {
40140b57cec5SDimitry Andric     APInt FirstLow =
40150b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
40160b57cec5SDimitry Andric     APInt FirstHigh =
40170b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
40180b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
401981ad6265SDimitry Andric     Check(FirstRange.intersectWith(LastRange).isEmptySet(),
40200b57cec5SDimitry Andric           "Intervals are overlapping", Range);
402181ad6265SDimitry Andric     Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
40220b57cec5SDimitry Andric           Range);
40230b57cec5SDimitry Andric   }
40240b57cec5SDimitry Andric }
40250b57cec5SDimitry Andric 
402606c3fb27SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
402706c3fb27SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
402806c3fb27SDimitry Andric          "precondition violation");
402906c3fb27SDimitry Andric   verifyRangeMetadata(I, Range, Ty, false);
403006c3fb27SDimitry Andric }
403106c3fb27SDimitry Andric 
40320b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
40330b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
403481ad6265SDimitry Andric   Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
403581ad6265SDimitry Andric   Check(!(Size & (Size - 1)),
40360b57cec5SDimitry Andric         "atomic memory access' operand must have a power-of-two size", Ty, I);
40370b57cec5SDimitry Andric }
40380b57cec5SDimitry Andric 
40390b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
40400b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
404181ad6265SDimitry Andric   Check(PTy, "Load operand must be a pointer.", &LI);
40420b57cec5SDimitry Andric   Type *ElTy = LI.getType();
40430eae32dcSDimitry Andric   if (MaybeAlign A = LI.getAlign()) {
404481ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
40450b57cec5SDimitry Andric           "huge alignment values are unsupported", &LI);
40460eae32dcSDimitry Andric   }
404781ad6265SDimitry Andric   Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
40480b57cec5SDimitry Andric   if (LI.isAtomic()) {
404981ad6265SDimitry Andric     Check(LI.getOrdering() != AtomicOrdering::Release &&
40500b57cec5SDimitry Andric               LI.getOrdering() != AtomicOrdering::AcquireRelease,
40510b57cec5SDimitry Andric           "Load cannot have Release ordering", &LI);
405281ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
40530b57cec5SDimitry Andric           "atomic load operand must have integer, pointer, or floating point "
40540b57cec5SDimitry Andric           "type!",
40550b57cec5SDimitry Andric           ElTy, &LI);
40560b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
40570b57cec5SDimitry Andric   } else {
405881ad6265SDimitry Andric     Check(LI.getSyncScopeID() == SyncScope::System,
40590b57cec5SDimitry Andric           "Non-atomic load cannot have SynchronizationScope specified", &LI);
40600b57cec5SDimitry Andric   }
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric   visitInstruction(LI);
40630b57cec5SDimitry Andric }
40640b57cec5SDimitry Andric 
40650b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
40660b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
406781ad6265SDimitry Andric   Check(PTy, "Store operand must be a pointer.", &SI);
4068fe6060f1SDimitry Andric   Type *ElTy = SI.getOperand(0)->getType();
40690eae32dcSDimitry Andric   if (MaybeAlign A = SI.getAlign()) {
407081ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
40710b57cec5SDimitry Andric           "huge alignment values are unsupported", &SI);
40720eae32dcSDimitry Andric   }
407381ad6265SDimitry Andric   Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
40740b57cec5SDimitry Andric   if (SI.isAtomic()) {
407581ad6265SDimitry Andric     Check(SI.getOrdering() != AtomicOrdering::Acquire &&
40760b57cec5SDimitry Andric               SI.getOrdering() != AtomicOrdering::AcquireRelease,
40770b57cec5SDimitry Andric           "Store cannot have Acquire ordering", &SI);
407881ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
40790b57cec5SDimitry Andric           "atomic store operand must have integer, pointer, or floating point "
40800b57cec5SDimitry Andric           "type!",
40810b57cec5SDimitry Andric           ElTy, &SI);
40820b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
40830b57cec5SDimitry Andric   } else {
408481ad6265SDimitry Andric     Check(SI.getSyncScopeID() == SyncScope::System,
40850b57cec5SDimitry Andric           "Non-atomic store cannot have SynchronizationScope specified", &SI);
40860b57cec5SDimitry Andric   }
40870b57cec5SDimitry Andric   visitInstruction(SI);
40880b57cec5SDimitry Andric }
40890b57cec5SDimitry Andric 
40900b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
40910b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
40920b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
4093fe6060f1SDimitry Andric   for (const auto &I : llvm::enumerate(Call.args())) {
4094fe6060f1SDimitry Andric     if (I.value() == SwiftErrorVal) {
409581ad6265SDimitry Andric       Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
40960b57cec5SDimitry Andric             "swifterror value when used in a callsite should be marked "
40970b57cec5SDimitry Andric             "with swifterror attribute",
40980b57cec5SDimitry Andric             SwiftErrorVal, Call);
40990b57cec5SDimitry Andric     }
41000b57cec5SDimitry Andric   }
41010b57cec5SDimitry Andric }
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
41040b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
41050b57cec5SDimitry Andric   // a swifterror argument.
41060b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
410781ad6265SDimitry Andric     Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
41080b57cec5SDimitry Andric               isa<InvokeInst>(U),
41090b57cec5SDimitry Andric           "swifterror value can only be loaded and stored from, or "
41100b57cec5SDimitry Andric           "as a swifterror argument!",
41110b57cec5SDimitry Andric           SwiftErrorVal, U);
41120b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
41130b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
411481ad6265SDimitry Andric       Check(StoreI->getOperand(1) == SwiftErrorVal,
41150b57cec5SDimitry Andric             "swifterror value should be the second operand when used "
411681ad6265SDimitry Andric             "by stores",
411781ad6265SDimitry Andric             SwiftErrorVal, U);
41180b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
41190b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
41200b57cec5SDimitry Andric   }
41210b57cec5SDimitry Andric }
41220b57cec5SDimitry Andric 
41230b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
41240b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
412581ad6265SDimitry Andric   Check(AI.getAllocatedType()->isSized(&Visited),
41260b57cec5SDimitry Andric         "Cannot allocate unsized type", &AI);
412781ad6265SDimitry Andric   Check(AI.getArraySize()->getType()->isIntegerTy(),
41280b57cec5SDimitry Andric         "Alloca array size must have integer type", &AI);
41290eae32dcSDimitry Andric   if (MaybeAlign A = AI.getAlign()) {
413081ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
41310b57cec5SDimitry Andric           "huge alignment values are unsupported", &AI);
41320eae32dcSDimitry Andric   }
41330b57cec5SDimitry Andric 
41340b57cec5SDimitry Andric   if (AI.isSwiftError()) {
413581ad6265SDimitry Andric     Check(AI.getAllocatedType()->isPointerTy(),
413681ad6265SDimitry Andric           "swifterror alloca must have pointer type", &AI);
413781ad6265SDimitry Andric     Check(!AI.isArrayAllocation(),
413881ad6265SDimitry Andric           "swifterror alloca must not be array allocation", &AI);
41390b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
41400b57cec5SDimitry Andric   }
41410b57cec5SDimitry Andric 
41420b57cec5SDimitry Andric   visitInstruction(AI);
41430b57cec5SDimitry Andric }
41440b57cec5SDimitry Andric 
41450b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4146fe6060f1SDimitry Andric   Type *ElTy = CXI.getOperand(1)->getType();
414781ad6265SDimitry Andric   Check(ElTy->isIntOrPtrTy(),
41480b57cec5SDimitry Andric         "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
41490b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
41500b57cec5SDimitry Andric   visitInstruction(CXI);
41510b57cec5SDimitry Andric }
41520b57cec5SDimitry Andric 
41530b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
415481ad6265SDimitry Andric   Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
41550b57cec5SDimitry Andric         "atomicrmw instructions cannot be unordered.", &RMWI);
41560b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
4157fe6060f1SDimitry Andric   Type *ElTy = RMWI.getOperand(1)->getType();
41580b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
415981ad6265SDimitry Andric     Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
416081ad6265SDimitry Andric               ElTy->isPointerTy(),
416181ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
41620b57cec5SDimitry Andric               " operand must have integer or floating point type!",
41630b57cec5SDimitry Andric           &RMWI, ElTy);
41640b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
416581ad6265SDimitry Andric     Check(ElTy->isFloatingPointTy(),
416681ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
41670b57cec5SDimitry Andric               " operand must have floating point type!",
41680b57cec5SDimitry Andric           &RMWI, ElTy);
41690b57cec5SDimitry Andric   } else {
417081ad6265SDimitry Andric     Check(ElTy->isIntegerTy(),
417181ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
41720b57cec5SDimitry Andric               " operand must have integer type!",
41730b57cec5SDimitry Andric           &RMWI, ElTy);
41740b57cec5SDimitry Andric   }
41750b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
417681ad6265SDimitry Andric   Check(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
41770b57cec5SDimitry Andric         "Invalid binary operation!", &RMWI);
41780b57cec5SDimitry Andric   visitInstruction(RMWI);
41790b57cec5SDimitry Andric }
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
41820b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
418381ad6265SDimitry Andric   Check(Ordering == AtomicOrdering::Acquire ||
41840b57cec5SDimitry Andric             Ordering == AtomicOrdering::Release ||
41850b57cec5SDimitry Andric             Ordering == AtomicOrdering::AcquireRelease ||
41860b57cec5SDimitry Andric             Ordering == AtomicOrdering::SequentiallyConsistent,
41870b57cec5SDimitry Andric         "fence instructions may only have acquire, release, acq_rel, or "
41880b57cec5SDimitry Andric         "seq_cst ordering.",
41890b57cec5SDimitry Andric         &FI);
41900b57cec5SDimitry Andric   visitInstruction(FI);
41910b57cec5SDimitry Andric }
41920b57cec5SDimitry Andric 
41930b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
419481ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
41950b57cec5SDimitry Andric                                          EVI.getIndices()) == EVI.getType(),
41960b57cec5SDimitry Andric         "Invalid ExtractValueInst operands!", &EVI);
41970b57cec5SDimitry Andric 
41980b57cec5SDimitry Andric   visitInstruction(EVI);
41990b57cec5SDimitry Andric }
42000b57cec5SDimitry Andric 
42010b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
420281ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
42030b57cec5SDimitry Andric                                          IVI.getIndices()) ==
42040b57cec5SDimitry Andric             IVI.getOperand(1)->getType(),
42050b57cec5SDimitry Andric         "Invalid InsertValueInst operands!", &IVI);
42060b57cec5SDimitry Andric 
42070b57cec5SDimitry Andric   visitInstruction(IVI);
42080b57cec5SDimitry Andric }
42090b57cec5SDimitry Andric 
42100b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
42110b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
42120b57cec5SDimitry Andric     return FPI->getParentPad();
42130b57cec5SDimitry Andric 
42140b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
42150b57cec5SDimitry Andric }
42160b57cec5SDimitry Andric 
42170b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
42180b57cec5SDimitry Andric   assert(I.isEHPad());
42190b57cec5SDimitry Andric 
42200b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
42210b57cec5SDimitry Andric   Function *F = BB->getParent();
42220b57cec5SDimitry Andric 
422381ad6265SDimitry Andric   Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
42240b57cec5SDimitry Andric 
42250b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
42260b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
42270b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
42280b57cec5SDimitry Andric     // invoke.
42290b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
42300b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
423181ad6265SDimitry Andric       Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
42320b57cec5SDimitry Andric             "Block containing LandingPadInst must be jumped to "
42330b57cec5SDimitry Andric             "only by the unwind edge of an invoke.",
42340b57cec5SDimitry Andric             LPI);
42350b57cec5SDimitry Andric     }
42360b57cec5SDimitry Andric     return;
42370b57cec5SDimitry Andric   }
42380b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
42390b57cec5SDimitry Andric     if (!pred_empty(BB))
424081ad6265SDimitry Andric       Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
42410b57cec5SDimitry Andric             "Block containg CatchPadInst must be jumped to "
42420b57cec5SDimitry Andric             "only by its catchswitch.",
42430b57cec5SDimitry Andric             CPI);
424481ad6265SDimitry Andric     Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
42450b57cec5SDimitry Andric           "Catchswitch cannot unwind to one of its catchpads",
42460b57cec5SDimitry Andric           CPI->getCatchSwitch(), CPI);
42470b57cec5SDimitry Andric     return;
42480b57cec5SDimitry Andric   }
42490b57cec5SDimitry Andric 
42500b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
42510b57cec5SDimitry Andric   // pad relationship.
42520b57cec5SDimitry Andric   Instruction *ToPad = &I;
42530b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
42540b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
42550b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
42560b57cec5SDimitry Andric     Value *FromPad;
42570b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
425881ad6265SDimitry Andric       Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
42590b57cec5SDimitry Andric             "EH pad must be jumped to via an unwind edge", ToPad, II);
42600b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
42610b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
42620b57cec5SDimitry Andric       else
42630b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
42640b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
42650b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
426681ad6265SDimitry Andric       Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
42670b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
42680b57cec5SDimitry Andric       FromPad = CSI;
42690b57cec5SDimitry Andric     } else {
427081ad6265SDimitry Andric       Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
42710b57cec5SDimitry Andric     }
42720b57cec5SDimitry Andric 
42730b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
42740b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
42750b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
427681ad6265SDimitry Andric       Check(FromPad != ToPad,
42770b57cec5SDimitry Andric             "EH pad cannot handle exceptions raised within it", FromPad, TI);
42780b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
42790b57cec5SDimitry Andric         // This is a legal unwind edge.
42800b57cec5SDimitry Andric         break;
42810b57cec5SDimitry Andric       }
428281ad6265SDimitry Andric       Check(!isa<ConstantTokenNone>(FromPad),
42830b57cec5SDimitry Andric             "A single unwind edge may only enter one EH pad", TI);
428481ad6265SDimitry Andric       Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
428581ad6265SDimitry Andric             FromPad);
428604eeddc0SDimitry Andric 
428704eeddc0SDimitry Andric       // This will be diagnosed on the corresponding instruction already. We
428804eeddc0SDimitry Andric       // need the extra check here to make sure getParentPad() works.
428981ad6265SDimitry Andric       Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
429004eeddc0SDimitry Andric             "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
42910b57cec5SDimitry Andric     }
42920b57cec5SDimitry Andric   }
42930b57cec5SDimitry Andric }
42940b57cec5SDimitry Andric 
42950b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
42960b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
42970b57cec5SDimitry Andric   // isn't a cleanup.
429881ad6265SDimitry Andric   Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
42990b57cec5SDimitry Andric         "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
43000b57cec5SDimitry Andric 
43010b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
43020b57cec5SDimitry Andric 
43030b57cec5SDimitry Andric   if (!LandingPadResultTy)
43040b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
43050b57cec5SDimitry Andric   else
430681ad6265SDimitry Andric     Check(LandingPadResultTy == LPI.getType(),
43070b57cec5SDimitry Andric           "The landingpad instruction should have a consistent result type "
43080b57cec5SDimitry Andric           "inside a function.",
43090b57cec5SDimitry Andric           &LPI);
43100b57cec5SDimitry Andric 
43110b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
431281ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
43130b57cec5SDimitry Andric         "LandingPadInst needs to be in a function with a personality.", &LPI);
43140b57cec5SDimitry Andric 
43150b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
43160b57cec5SDimitry Andric   // block.
431781ad6265SDimitry Andric   Check(LPI.getParent()->getLandingPadInst() == &LPI,
431881ad6265SDimitry Andric         "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
43210b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
43220b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
432381ad6265SDimitry Andric       Check(isa<PointerType>(Clause->getType()),
43240b57cec5SDimitry Andric             "Catch operand does not have pointer type!", &LPI);
43250b57cec5SDimitry Andric     } else {
432681ad6265SDimitry Andric       Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
432781ad6265SDimitry Andric       Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
43280b57cec5SDimitry Andric             "Filter operand is not an array of constants!", &LPI);
43290b57cec5SDimitry Andric     }
43300b57cec5SDimitry Andric   }
43310b57cec5SDimitry Andric 
43320b57cec5SDimitry Andric   visitInstruction(LPI);
43330b57cec5SDimitry Andric }
43340b57cec5SDimitry Andric 
43350b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
433681ad6265SDimitry Andric   Check(RI.getFunction()->hasPersonalityFn(),
43370b57cec5SDimitry Andric         "ResumeInst needs to be in a function with a personality.", &RI);
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric   if (!LandingPadResultTy)
43400b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
43410b57cec5SDimitry Andric   else
434281ad6265SDimitry Andric     Check(LandingPadResultTy == RI.getValue()->getType(),
43430b57cec5SDimitry Andric           "The resume instruction should have a consistent result type "
43440b57cec5SDimitry Andric           "inside a function.",
43450b57cec5SDimitry Andric           &RI);
43460b57cec5SDimitry Andric 
43470b57cec5SDimitry Andric   visitTerminator(RI);
43480b57cec5SDimitry Andric }
43490b57cec5SDimitry Andric 
43500b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
43510b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric   Function *F = BB->getParent();
435481ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
43550b57cec5SDimitry Andric         "CatchPadInst needs to be in a function with a personality.", &CPI);
43560b57cec5SDimitry Andric 
435781ad6265SDimitry Andric   Check(isa<CatchSwitchInst>(CPI.getParentPad()),
43580b57cec5SDimitry Andric         "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
43590b57cec5SDimitry Andric         CPI.getParentPad());
43600b57cec5SDimitry Andric 
43610b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
43620b57cec5SDimitry Andric   // block.
436381ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
43640b57cec5SDimitry Andric         "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
43650b57cec5SDimitry Andric 
43660b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
43670b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
43680b57cec5SDimitry Andric }
43690b57cec5SDimitry Andric 
43700b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
437181ad6265SDimitry Andric   Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
43720b57cec5SDimitry Andric         "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
43730b57cec5SDimitry Andric         CatchReturn.getOperand(0));
43740b57cec5SDimitry Andric 
43750b57cec5SDimitry Andric   visitTerminator(CatchReturn);
43760b57cec5SDimitry Andric }
43770b57cec5SDimitry Andric 
43780b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
43790b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
43800b57cec5SDimitry Andric 
43810b57cec5SDimitry Andric   Function *F = BB->getParent();
438281ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
43830b57cec5SDimitry Andric         "CleanupPadInst needs to be in a function with a personality.", &CPI);
43840b57cec5SDimitry Andric 
43850b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
43860b57cec5SDimitry Andric   // block.
438781ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
438881ad6265SDimitry Andric         "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
43890b57cec5SDimitry Andric 
43900b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
439181ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
43920b57cec5SDimitry Andric         "CleanupPadInst has an invalid parent.", &CPI);
43930b57cec5SDimitry Andric 
43940b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
43950b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
43960b57cec5SDimitry Andric }
43970b57cec5SDimitry Andric 
43980b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
43990b57cec5SDimitry Andric   User *FirstUser = nullptr;
44000b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
44010b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
44020b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
44030b57cec5SDimitry Andric 
44040b57cec5SDimitry Andric   while (!Worklist.empty()) {
44050b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
440681ad6265SDimitry Andric     Check(Seen.insert(CurrentPad).second,
44070b57cec5SDimitry Andric           "FuncletPadInst must not be nested within itself", CurrentPad);
44080b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
44090b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
44100b57cec5SDimitry Andric       BasicBlock *UnwindDest;
44110b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
44120b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
44130b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
44140b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
44150b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
44160b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
44170b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
44180b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
44190b57cec5SDimitry Andric           continue;
44200b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
44210b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
44220b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
44230b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
44240b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
44250b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
44260b57cec5SDimitry Andric         // such calls to be annotated nounwind.
44270b57cec5SDimitry Andric         continue;
44280b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
44290b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
44300b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
44310b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
44320b57cec5SDimitry Andric         Worklist.push_back(CPI);
44330b57cec5SDimitry Andric         continue;
44340b57cec5SDimitry Andric       } else {
443581ad6265SDimitry Andric         Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
44360b57cec5SDimitry Andric         continue;
44370b57cec5SDimitry Andric       }
44380b57cec5SDimitry Andric 
44390b57cec5SDimitry Andric       Value *UnwindPad;
44400b57cec5SDimitry Andric       bool ExitsFPI;
44410b57cec5SDimitry Andric       if (UnwindDest) {
44420b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
44430b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
44440b57cec5SDimitry Andric           continue;
44450b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
44460b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
44470b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
44480b57cec5SDimitry Andric           continue;
44490b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
44500b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
44510b57cec5SDimitry Andric         // of them are exited so we can stop searching their
44520b57cec5SDimitry Andric         // children.
44530b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
44540b57cec5SDimitry Andric         ExitsFPI = false;
44550b57cec5SDimitry Andric         do {
44560b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
44570b57cec5SDimitry Andric             ExitsFPI = true;
44580b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
44590b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
44600b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
44610b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
44620b57cec5SDimitry Andric             break;
44630b57cec5SDimitry Andric           }
44640b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
44650b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
44660b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
44670b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
44680b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
44690b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
44700b57cec5SDimitry Andric             break;
44710b57cec5SDimitry Andric           }
44720b57cec5SDimitry Andric           ExitedPad = ExitedParent;
44730b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
44740b57cec5SDimitry Andric       } else {
44750b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
44760b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
44770b57cec5SDimitry Andric         ExitsFPI = true;
44780b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
44790b57cec5SDimitry Andric       }
44800b57cec5SDimitry Andric 
44810b57cec5SDimitry Andric       if (ExitsFPI) {
44820b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
44830b57cec5SDimitry Andric         // such edges.
44840b57cec5SDimitry Andric         if (FirstUser) {
448581ad6265SDimitry Andric           Check(UnwindPad == FirstUnwindPad,
448681ad6265SDimitry Andric                 "Unwind edges out of a funclet "
44870b57cec5SDimitry Andric                 "pad must have the same unwind "
44880b57cec5SDimitry Andric                 "dest",
44890b57cec5SDimitry Andric                 &FPI, U, FirstUser);
44900b57cec5SDimitry Andric         } else {
44910b57cec5SDimitry Andric           FirstUser = U;
44920b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
44930b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
44940b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
44950b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
44960b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
44970b57cec5SDimitry Andric         }
44980b57cec5SDimitry Andric       }
44990b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
45000b57cec5SDimitry Andric       // soon as we know where they unwind to.
45010b57cec5SDimitry Andric       if (CurrentPad != &FPI)
45020b57cec5SDimitry Andric         break;
45030b57cec5SDimitry Andric     }
45040b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
45050b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
45060b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
45070b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
45080b57cec5SDimitry Andric         // all direct uses of FPI.
45090b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
45100b57cec5SDimitry Andric         continue;
45110b57cec5SDimitry Andric       }
45120b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
45130b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
45140b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
45150b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
45160b57cec5SDimitry Andric       // UnresolvedAncestorPad.
45170b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
45180b57cec5SDimitry Andric       while (!Worklist.empty()) {
45190b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
45200b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
45210b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
45220b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
45230b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
45240b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
45250b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
45260b57cec5SDimitry Andric             break;
45270b57cec5SDimitry Andric           }
45280b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
45290b57cec5SDimitry Andric         }
45300b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
45310b57cec5SDimitry Andric         // then the uncle is not yet resolved.
45320b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
45330b57cec5SDimitry Andric           break;
45340b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
45350b57cec5SDimitry Andric         Worklist.pop_back();
45360b57cec5SDimitry Andric       }
45370b57cec5SDimitry Andric     }
45380b57cec5SDimitry Andric   }
45390b57cec5SDimitry Andric 
45400b57cec5SDimitry Andric   if (FirstUnwindPad) {
45410b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
45420b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
45430b57cec5SDimitry Andric       Value *SwitchUnwindPad;
45440b57cec5SDimitry Andric       if (SwitchUnwindDest)
45450b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
45460b57cec5SDimitry Andric       else
45470b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
454881ad6265SDimitry Andric       Check(SwitchUnwindPad == FirstUnwindPad,
45490b57cec5SDimitry Andric             "Unwind edges out of a catch must have the same unwind dest as "
45500b57cec5SDimitry Andric             "the parent catchswitch",
45510b57cec5SDimitry Andric             &FPI, FirstUser, CatchSwitch);
45520b57cec5SDimitry Andric     }
45530b57cec5SDimitry Andric   }
45540b57cec5SDimitry Andric 
45550b57cec5SDimitry Andric   visitInstruction(FPI);
45560b57cec5SDimitry Andric }
45570b57cec5SDimitry Andric 
45580b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
45590b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric   Function *F = BB->getParent();
456281ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
45630b57cec5SDimitry Andric         "CatchSwitchInst needs to be in a function with a personality.",
45640b57cec5SDimitry Andric         &CatchSwitch);
45650b57cec5SDimitry Andric 
45660b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
45670b57cec5SDimitry Andric   // block.
456881ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CatchSwitch,
45690b57cec5SDimitry Andric         "CatchSwitchInst not the first non-PHI instruction in the block.",
45700b57cec5SDimitry Andric         &CatchSwitch);
45710b57cec5SDimitry Andric 
45720b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
457381ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
45740b57cec5SDimitry Andric         "CatchSwitchInst has an invalid parent.", ParentPad);
45750b57cec5SDimitry Andric 
45760b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
45770b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
457881ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
45790b57cec5SDimitry Andric           "CatchSwitchInst must unwind to an EH block which is not a "
45800b57cec5SDimitry Andric           "landingpad.",
45810b57cec5SDimitry Andric           &CatchSwitch);
45820b57cec5SDimitry Andric 
45830b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
45840b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
45850b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
45860b57cec5SDimitry Andric   }
45870b57cec5SDimitry Andric 
458881ad6265SDimitry Andric   Check(CatchSwitch.getNumHandlers() != 0,
45890b57cec5SDimitry Andric         "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
45900b57cec5SDimitry Andric 
45910b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
459281ad6265SDimitry Andric     Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
45930b57cec5SDimitry Andric           "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
45940b57cec5SDimitry Andric   }
45950b57cec5SDimitry Andric 
45960b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
45970b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
45980b57cec5SDimitry Andric }
45990b57cec5SDimitry Andric 
46000b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
460181ad6265SDimitry Andric   Check(isa<CleanupPadInst>(CRI.getOperand(0)),
46020b57cec5SDimitry Andric         "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
46030b57cec5SDimitry Andric         CRI.getOperand(0));
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
46060b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
460781ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
46080b57cec5SDimitry Andric           "CleanupReturnInst must unwind to an EH block which is not a "
46090b57cec5SDimitry Andric           "landingpad.",
46100b57cec5SDimitry Andric           &CRI);
46110b57cec5SDimitry Andric   }
46120b57cec5SDimitry Andric 
46130b57cec5SDimitry Andric   visitTerminator(CRI);
46140b57cec5SDimitry Andric }
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
46170b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
46180b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
46190b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
46200b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
46210b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
46220b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
46230b57cec5SDimitry Andric       return;
46240b57cec5SDimitry Andric   }
46250b57cec5SDimitry Andric 
46260b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
46270b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
46280b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
46290b57cec5SDimitry Andric   //
46300b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
46310b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
46320b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
46330b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
46340b57cec5SDimitry Andric     return;
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
463781ad6265SDimitry Andric   Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
46380b57cec5SDimitry Andric }
46390b57cec5SDimitry Andric 
46400b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
464181ad6265SDimitry Andric   Check(I.getType()->isPointerTy(),
464281ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
464381ad6265SDimitry Andric         "apply only to pointer types",
464481ad6265SDimitry Andric         &I);
464581ad6265SDimitry Andric   Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
46460b57cec5SDimitry Andric         "dereferenceable, dereferenceable_or_null apply only to load"
464781ad6265SDimitry Andric         " and inttoptr instructions, use attributes for calls or invokes",
464881ad6265SDimitry Andric         &I);
464981ad6265SDimitry Andric   Check(MD->getNumOperands() == 1,
465081ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
465181ad6265SDimitry Andric         "take one operand!",
465281ad6265SDimitry Andric         &I);
46530b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
465481ad6265SDimitry Andric   Check(CI && CI->getType()->isIntegerTy(64),
465581ad6265SDimitry Andric         "dereferenceable, "
465681ad6265SDimitry Andric         "dereferenceable_or_null metadata value must be an i64!",
465781ad6265SDimitry Andric         &I);
46580b57cec5SDimitry Andric }
46590b57cec5SDimitry Andric 
46608bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
466181ad6265SDimitry Andric   Check(MD->getNumOperands() >= 2,
46628bcb0991SDimitry Andric         "!prof annotations should have no less than 2 operands", MD);
46638bcb0991SDimitry Andric 
46648bcb0991SDimitry Andric   // Check first operand.
466581ad6265SDimitry Andric   Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
466681ad6265SDimitry Andric   Check(isa<MDString>(MD->getOperand(0)),
46678bcb0991SDimitry Andric         "expected string with name of the !prof annotation", MD);
46688bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
46698bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
46708bcb0991SDimitry Andric 
46718bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
46728bcb0991SDimitry Andric   if (ProfName.equals("branch_weights")) {
46735ffd83dbSDimitry Andric     if (isa<InvokeInst>(&I)) {
467481ad6265SDimitry Andric       Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
46755ffd83dbSDimitry Andric             "Wrong number of InvokeInst branch_weights operands", MD);
46765ffd83dbSDimitry Andric     } else {
46778bcb0991SDimitry Andric       unsigned ExpectedNumOperands = 0;
46788bcb0991SDimitry Andric       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
46798bcb0991SDimitry Andric         ExpectedNumOperands = BI->getNumSuccessors();
46808bcb0991SDimitry Andric       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
46818bcb0991SDimitry Andric         ExpectedNumOperands = SI->getNumSuccessors();
46825ffd83dbSDimitry Andric       else if (isa<CallInst>(&I))
46838bcb0991SDimitry Andric         ExpectedNumOperands = 1;
46848bcb0991SDimitry Andric       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
46858bcb0991SDimitry Andric         ExpectedNumOperands = IBI->getNumDestinations();
46868bcb0991SDimitry Andric       else if (isa<SelectInst>(&I))
46878bcb0991SDimitry Andric         ExpectedNumOperands = 2;
4688bdd1243dSDimitry Andric       else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
4689bdd1243dSDimitry Andric         ExpectedNumOperands = CI->getNumSuccessors();
46908bcb0991SDimitry Andric       else
46918bcb0991SDimitry Andric         CheckFailed("!prof branch_weights are not allowed for this instruction",
46928bcb0991SDimitry Andric                     MD);
46938bcb0991SDimitry Andric 
469481ad6265SDimitry Andric       Check(MD->getNumOperands() == 1 + ExpectedNumOperands,
46958bcb0991SDimitry Andric             "Wrong number of operands", MD);
46965ffd83dbSDimitry Andric     }
46978bcb0991SDimitry Andric     for (unsigned i = 1; i < MD->getNumOperands(); ++i) {
46988bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
469981ad6265SDimitry Andric       Check(MDO, "second operand should not be null", MD);
470081ad6265SDimitry Andric       Check(mdconst::dyn_extract<ConstantInt>(MDO),
47018bcb0991SDimitry Andric             "!prof brunch_weights operand is not a const int");
47028bcb0991SDimitry Andric     }
47038bcb0991SDimitry Andric   }
47048bcb0991SDimitry Andric }
47058bcb0991SDimitry Andric 
4706bdd1243dSDimitry Andric void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
4707bdd1243dSDimitry Andric   assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
4708bdd1243dSDimitry Andric   bool ExpectedInstTy =
4709bdd1243dSDimitry Andric       isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
4710bdd1243dSDimitry Andric   CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
4711bdd1243dSDimitry Andric           I, MD);
4712bdd1243dSDimitry Andric   // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4713bdd1243dSDimitry Andric   // only be found as DbgAssignIntrinsic operands.
4714bdd1243dSDimitry Andric   if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
4715bdd1243dSDimitry Andric     for (auto *User : AsValue->users()) {
4716bdd1243dSDimitry Andric       CheckDI(isa<DbgAssignIntrinsic>(User),
4717bdd1243dSDimitry Andric               "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4718bdd1243dSDimitry Andric               MD, User);
4719bdd1243dSDimitry Andric       // All of the dbg.assign intrinsics should be in the same function as I.
4720bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
4721bdd1243dSDimitry Andric         CheckDI(DAI->getFunction() == I.getFunction(),
4722bdd1243dSDimitry Andric                 "dbg.assign not in same function as inst", DAI, &I);
4723bdd1243dSDimitry Andric     }
4724bdd1243dSDimitry Andric   }
4725bdd1243dSDimitry Andric }
4726bdd1243dSDimitry Andric 
4727fcaf7f86SDimitry Andric void Verifier::visitCallStackMetadata(MDNode *MD) {
4728fcaf7f86SDimitry Andric   // Call stack metadata should consist of a list of at least 1 constant int
4729fcaf7f86SDimitry Andric   // (representing a hash of the location).
4730fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4731fcaf7f86SDimitry Andric         "call stack metadata should have at least 1 operand", MD);
4732fcaf7f86SDimitry Andric 
4733fcaf7f86SDimitry Andric   for (const auto &Op : MD->operands())
4734fcaf7f86SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
4735fcaf7f86SDimitry Andric           "call stack metadata operand should be constant integer", Op);
4736fcaf7f86SDimitry Andric }
4737fcaf7f86SDimitry Andric 
4738fcaf7f86SDimitry Andric void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
4739fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
4740fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4741fcaf7f86SDimitry Andric         "!memprof annotations should have at least 1 metadata operand "
4742fcaf7f86SDimitry Andric         "(MemInfoBlock)",
4743fcaf7f86SDimitry Andric         MD);
4744fcaf7f86SDimitry Andric 
4745fcaf7f86SDimitry Andric   // Check each MIB
4746fcaf7f86SDimitry Andric   for (auto &MIBOp : MD->operands()) {
4747fcaf7f86SDimitry Andric     MDNode *MIB = dyn_cast<MDNode>(MIBOp);
4748fcaf7f86SDimitry Andric     // The first operand of an MIB should be the call stack metadata.
4749fcaf7f86SDimitry Andric     // There rest of the operands should be MDString tags, and there should be
4750fcaf7f86SDimitry Andric     // at least one.
4751fcaf7f86SDimitry Andric     Check(MIB->getNumOperands() >= 2,
4752fcaf7f86SDimitry Andric           "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
4753fcaf7f86SDimitry Andric 
4754fcaf7f86SDimitry Andric     // Check call stack metadata (first operand).
4755fcaf7f86SDimitry Andric     Check(MIB->getOperand(0) != nullptr,
4756fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should not be null", MIB);
4757fcaf7f86SDimitry Andric     Check(isa<MDNode>(MIB->getOperand(0)),
4758fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should be an MDNode", MIB);
4759fcaf7f86SDimitry Andric     MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
4760fcaf7f86SDimitry Andric     visitCallStackMetadata(StackMD);
4761fcaf7f86SDimitry Andric 
4762fcaf7f86SDimitry Andric     // Check that remaining operands are MDString.
4763bdd1243dSDimitry Andric     Check(llvm::all_of(llvm::drop_begin(MIB->operands()),
4764fcaf7f86SDimitry Andric                        [](const MDOperand &Op) { return isa<MDString>(Op); }),
4765fcaf7f86SDimitry Andric           "Not all !memprof MemInfoBlock operands 1 to N are MDString", MIB);
4766fcaf7f86SDimitry Andric   }
4767fcaf7f86SDimitry Andric }
4768fcaf7f86SDimitry Andric 
4769fcaf7f86SDimitry Andric void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
4770fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
4771fcaf7f86SDimitry Andric   // Verify the partial callstack annotated from memprof profiles. This callsite
4772fcaf7f86SDimitry Andric   // is a part of a profiled allocation callstack.
4773fcaf7f86SDimitry Andric   visitCallStackMetadata(MD);
4774fcaf7f86SDimitry Andric }
4775fcaf7f86SDimitry Andric 
4776e8d8bef9SDimitry Andric void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
477781ad6265SDimitry Andric   Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
477881ad6265SDimitry Andric   Check(Annotation->getNumOperands() >= 1,
4779e8d8bef9SDimitry Andric         "annotation must have at least one operand");
478006c3fb27SDimitry Andric   for (const MDOperand &Op : Annotation->operands()) {
478106c3fb27SDimitry Andric     bool TupleOfStrings =
478206c3fb27SDimitry Andric         isa<MDTuple>(Op.get()) &&
478306c3fb27SDimitry Andric         all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
478406c3fb27SDimitry Andric           return isa<MDString>(Annotation.get());
478506c3fb27SDimitry Andric         });
478606c3fb27SDimitry Andric     Check(isa<MDString>(Op.get()) || TupleOfStrings,
478706c3fb27SDimitry Andric           "operands must be a string or a tuple of strings");
478806c3fb27SDimitry Andric   }
4789e8d8bef9SDimitry Andric }
4790e8d8bef9SDimitry Andric 
4791349cc55cSDimitry Andric void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4792349cc55cSDimitry Andric   unsigned NumOps = MD->getNumOperands();
479381ad6265SDimitry Andric   Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4794349cc55cSDimitry Andric         MD);
479581ad6265SDimitry Andric   Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4796349cc55cSDimitry Andric         "first scope operand must be self-referential or string", MD);
4797349cc55cSDimitry Andric   if (NumOps == 3)
479881ad6265SDimitry Andric     Check(isa<MDString>(MD->getOperand(2)),
4799349cc55cSDimitry Andric           "third scope operand must be string (if used)", MD);
4800349cc55cSDimitry Andric 
4801349cc55cSDimitry Andric   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
480281ad6265SDimitry Andric   Check(Domain != nullptr, "second scope operand must be MDNode", MD);
4803349cc55cSDimitry Andric 
4804349cc55cSDimitry Andric   unsigned NumDomainOps = Domain->getNumOperands();
480581ad6265SDimitry Andric   Check(NumDomainOps >= 1 && NumDomainOps <= 2,
4806349cc55cSDimitry Andric         "domain must have one or two operands", Domain);
480781ad6265SDimitry Andric   Check(Domain->getOperand(0).get() == Domain ||
4808349cc55cSDimitry Andric             isa<MDString>(Domain->getOperand(0)),
4809349cc55cSDimitry Andric         "first domain operand must be self-referential or string", Domain);
4810349cc55cSDimitry Andric   if (NumDomainOps == 2)
481181ad6265SDimitry Andric     Check(isa<MDString>(Domain->getOperand(1)),
4812349cc55cSDimitry Andric           "second domain operand must be string (if used)", Domain);
4813349cc55cSDimitry Andric }
4814349cc55cSDimitry Andric 
4815349cc55cSDimitry Andric void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
4816349cc55cSDimitry Andric   for (const MDOperand &Op : MD->operands()) {
4817349cc55cSDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
481881ad6265SDimitry Andric     Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
4819349cc55cSDimitry Andric     visitAliasScopeMetadata(OpMD);
4820349cc55cSDimitry Andric   }
4821349cc55cSDimitry Andric }
4822349cc55cSDimitry Andric 
482381ad6265SDimitry Andric void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
482481ad6265SDimitry Andric   auto IsValidAccessScope = [](const MDNode *MD) {
482581ad6265SDimitry Andric     return MD->getNumOperands() == 0 && MD->isDistinct();
482681ad6265SDimitry Andric   };
482781ad6265SDimitry Andric 
482881ad6265SDimitry Andric   // It must be either an access scope itself...
482981ad6265SDimitry Andric   if (IsValidAccessScope(MD))
483081ad6265SDimitry Andric     return;
483181ad6265SDimitry Andric 
483281ad6265SDimitry Andric   // ...or a list of access scopes.
483381ad6265SDimitry Andric   for (const MDOperand &Op : MD->operands()) {
483481ad6265SDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
483581ad6265SDimitry Andric     Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
483681ad6265SDimitry Andric     Check(IsValidAccessScope(OpMD),
483781ad6265SDimitry Andric           "Access scope list contains invalid access scope", MD);
483881ad6265SDimitry Andric   }
483981ad6265SDimitry Andric }
484081ad6265SDimitry Andric 
48410b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
48420b57cec5SDimitry Andric ///
48430b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
48440b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
484581ad6265SDimitry Andric   Check(BB, "Instruction not embedded in basic block!", &I);
48460b57cec5SDimitry Andric 
48470b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
48480b57cec5SDimitry Andric     for (User *U : I.users()) {
484981ad6265SDimitry Andric       Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
48500b57cec5SDimitry Andric             "Only PHI nodes may reference their own value!", &I);
48510b57cec5SDimitry Andric     }
48520b57cec5SDimitry Andric   }
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric   // Check that void typed values don't have names
485581ad6265SDimitry Andric   Check(!I.getType()->isVoidTy() || !I.hasName(),
48560b57cec5SDimitry Andric         "Instruction has a name, but provides a void value!", &I);
48570b57cec5SDimitry Andric 
48580b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
48590b57cec5SDimitry Andric   // value type.
486081ad6265SDimitry Andric   Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
48610b57cec5SDimitry Andric         "Instruction returns a non-scalar type!", &I);
48620b57cec5SDimitry Andric 
48630b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
48640b57cec5SDimitry Andric   // checked against the callee type.
486581ad6265SDimitry Andric   Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
48660b57cec5SDimitry Andric         "Invalid use of metadata!", &I);
48670b57cec5SDimitry Andric 
48680b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
48690b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
48700b57cec5SDimitry Andric   // instruction, it is an error!
48710b57cec5SDimitry Andric   for (Use &U : I.uses()) {
48720b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
487381ad6265SDimitry Andric       Check(Used->getParent() != nullptr,
48740b57cec5SDimitry Andric             "Instruction referencing"
48750b57cec5SDimitry Andric             " instruction not embedded in a basic block!",
48760b57cec5SDimitry Andric             &I, Used);
48770b57cec5SDimitry Andric     else {
48780b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
48790b57cec5SDimitry Andric       return;
48800b57cec5SDimitry Andric     }
48810b57cec5SDimitry Andric   }
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
48840b57cec5SDimitry Andric   // call.
48850b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
48860b57cec5SDimitry Andric 
48870b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
488881ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
48890b57cec5SDimitry Andric 
48900b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
48910b57cec5SDimitry Andric     // instructions.
48920b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
489381ad6265SDimitry Andric       Check(false, "Instruction operands must be first-class values!", &I);
48940b57cec5SDimitry Andric     }
48950b57cec5SDimitry Andric 
48960b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
4897349cc55cSDimitry Andric       // This code checks whether the function is used as the operand of a
4898349cc55cSDimitry Andric       // clang_arc_attachedcall operand bundle.
4899349cc55cSDimitry Andric       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
4900349cc55cSDimitry Andric                                       int Idx) {
4901349cc55cSDimitry Andric         return CBI && CBI->isOperandBundleOfType(
4902349cc55cSDimitry Andric                           LLVMContext::OB_clang_arc_attachedcall, Idx);
4903349cc55cSDimitry Andric       };
4904349cc55cSDimitry Andric 
49050b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
4906349cc55cSDimitry Andric       // taken. Ignore cases where the address of the intrinsic function is used
4907349cc55cSDimitry Andric       // as the argument of operand bundle "clang.arc.attachedcall" as those
4908349cc55cSDimitry Andric       // cases are handled in verifyAttachedCallBundle.
490981ad6265SDimitry Andric       Check((!F->isIntrinsic() ||
4910349cc55cSDimitry Andric              (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
4911349cc55cSDimitry Andric              IsAttachedCallOperand(F, CBI, i)),
49120b57cec5SDimitry Andric             "Cannot take the address of an intrinsic!", &I);
491381ad6265SDimitry Andric       Check(!F->isIntrinsic() || isa<CallInst>(I) ||
49140b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::donothing ||
4915fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
4916fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_end ||
4917fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
4918fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
49190b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_resume ||
49200b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_destroy ||
492181ad6265SDimitry Andric                 F->getIntrinsicID() ==
492281ad6265SDimitry Andric                     Intrinsic::experimental_patchpoint_void ||
49230b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
49240b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
4925349cc55cSDimitry Andric                 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
4926349cc55cSDimitry Andric                 IsAttachedCallOperand(F, CBI, i),
49270b57cec5SDimitry Andric             "Cannot invoke an intrinsic other than donothing, patchpoint, "
4928349cc55cSDimitry Andric             "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
49290b57cec5SDimitry Andric             &I);
493081ad6265SDimitry Andric       Check(F->getParent() == &M, "Referencing function in another module!", &I,
493181ad6265SDimitry Andric             &M, F, F->getParent());
49320b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
493381ad6265SDimitry Andric       Check(OpBB->getParent() == BB->getParent(),
49340b57cec5SDimitry Andric             "Referring to a basic block in another function!", &I);
49350b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
493681ad6265SDimitry Andric       Check(OpArg->getParent() == BB->getParent(),
49370b57cec5SDimitry Andric             "Referring to an argument in another function!", &I);
49380b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
493981ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!", &I,
49400b57cec5SDimitry Andric             &M, GV, GV->getParent());
49410b57cec5SDimitry Andric     } else if (isa<Instruction>(I.getOperand(i))) {
49420b57cec5SDimitry Andric       verifyDominatesUse(I, i);
49430b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
494481ad6265SDimitry Andric       Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
49450b57cec5SDimitry Andric             "Cannot take the address of an inline asm!", &I);
49460b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
4947fe6060f1SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy()) {
49480b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
4949fe6060f1SDimitry Andric         // illegal bitcast.
49500b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
49510b57cec5SDimitry Andric       }
49520b57cec5SDimitry Andric     }
49530b57cec5SDimitry Andric   }
49540b57cec5SDimitry Andric 
49550b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
495681ad6265SDimitry Andric     Check(I.getType()->isFPOrFPVectorTy(),
49570b57cec5SDimitry Andric           "fpmath requires a floating point result!", &I);
495881ad6265SDimitry Andric     Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
49590b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
49600b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
49610b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
496281ad6265SDimitry Andric       Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
49630b57cec5SDimitry Andric             "fpmath accuracy must have float type", &I);
496481ad6265SDimitry Andric       Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
49650b57cec5SDimitry Andric             "fpmath accuracy not a positive number!", &I);
49660b57cec5SDimitry Andric     } else {
496781ad6265SDimitry Andric       Check(false, "invalid fpmath accuracy!", &I);
49680b57cec5SDimitry Andric     }
49690b57cec5SDimitry Andric   }
49700b57cec5SDimitry Andric 
49710b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
497281ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
49730b57cec5SDimitry Andric           "Ranges are only for loads, calls and invokes!", &I);
49740b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
49750b57cec5SDimitry Andric   }
49760b57cec5SDimitry Andric 
4977349cc55cSDimitry Andric   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
497881ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<StoreInst>(I),
4979349cc55cSDimitry Andric           "invariant.group metadata is only for loads and stores", &I);
4980349cc55cSDimitry Andric   }
4981349cc55cSDimitry Andric 
4982bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
498381ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
49840b57cec5SDimitry Andric           &I);
498581ad6265SDimitry Andric     Check(isa<LoadInst>(I),
49860b57cec5SDimitry Andric           "nonnull applies only to load instructions, use attributes"
49870b57cec5SDimitry Andric           " for calls or invokes",
49880b57cec5SDimitry Andric           &I);
4989bdd1243dSDimitry Andric     Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
49900b57cec5SDimitry Andric   }
49910b57cec5SDimitry Andric 
49920b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
49930b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
49940b57cec5SDimitry Andric 
49950b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
49960b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
49970b57cec5SDimitry Andric 
49980b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
49990b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
50000b57cec5SDimitry Andric 
5001349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
5002349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
5003349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
5004349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
5005349cc55cSDimitry Andric 
500681ad6265SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
500781ad6265SDimitry Andric     visitAccessGroupMetadata(MD);
500881ad6265SDimitry Andric 
50090b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
501081ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "align applies only to pointer types",
50110b57cec5SDimitry Andric           &I);
501281ad6265SDimitry Andric     Check(isa<LoadInst>(I),
501381ad6265SDimitry Andric           "align applies only to load instructions, "
501481ad6265SDimitry Andric           "use attributes for calls or invokes",
501581ad6265SDimitry Andric           &I);
501681ad6265SDimitry Andric     Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
50170b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
501881ad6265SDimitry Andric     Check(CI && CI->getType()->isIntegerTy(64),
50190b57cec5SDimitry Andric           "align metadata value must be an i64!", &I);
50200b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
502181ad6265SDimitry Andric     Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
502281ad6265SDimitry Andric           &I);
502381ad6265SDimitry Andric     Check(Align <= Value::MaximumAlignment,
50240b57cec5SDimitry Andric           "alignment is larger that implementation defined limit", &I);
50250b57cec5SDimitry Andric   }
50260b57cec5SDimitry Andric 
50278bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
50288bcb0991SDimitry Andric     visitProfMetadata(I, MD);
50298bcb0991SDimitry Andric 
5030fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
5031fcaf7f86SDimitry Andric     visitMemProfMetadata(I, MD);
5032fcaf7f86SDimitry Andric 
5033fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
5034fcaf7f86SDimitry Andric     visitCallsiteMetadata(I, MD);
5035fcaf7f86SDimitry Andric 
5036bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
5037bdd1243dSDimitry Andric     visitDIAssignIDMetadata(I, MD);
5038bdd1243dSDimitry Andric 
5039e8d8bef9SDimitry Andric   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
5040e8d8bef9SDimitry Andric     visitAnnotationMetadata(Annotation);
5041e8d8bef9SDimitry Andric 
50420b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
504381ad6265SDimitry Andric     CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
50445ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::Yes);
50450b57cec5SDimitry Andric   }
50460b57cec5SDimitry Andric 
50478bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
50480b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
50498bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
50508bcb0991SDimitry Andric   }
50510b57cec5SDimitry Andric 
50525ffd83dbSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
50535ffd83dbSDimitry Andric   I.getAllMetadata(MDs);
50545ffd83dbSDimitry Andric   for (auto Attachment : MDs) {
50555ffd83dbSDimitry Andric     unsigned Kind = Attachment.first;
50565ffd83dbSDimitry Andric     auto AllowLocs =
50575ffd83dbSDimitry Andric         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
50585ffd83dbSDimitry Andric             ? AreDebugLocsAllowed::Yes
50595ffd83dbSDimitry Andric             : AreDebugLocsAllowed::No;
50605ffd83dbSDimitry Andric     visitMDNode(*Attachment.second, AllowLocs);
50615ffd83dbSDimitry Andric   }
50625ffd83dbSDimitry Andric 
50630b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
50640b57cec5SDimitry Andric }
50650b57cec5SDimitry Andric 
50660b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
50670b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
50680b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
506981ad6265SDimitry Andric   Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
50700b57cec5SDimitry Andric         IF);
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
50730b57cec5SDimitry Andric   // describe.
50740b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
50750b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
50760b57cec5SDimitry Andric 
50770b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
50780b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
50790b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
50820b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
50830b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
50840b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
508581ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
50860b57cec5SDimitry Andric         "Intrinsic has incorrect return type!", IF);
508781ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
50880b57cec5SDimitry Andric         "Intrinsic has incorrect argument type!", IF);
50890b57cec5SDimitry Andric 
50900b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
50910b57cec5SDimitry Andric   if (IsVarArg)
509281ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
50930b57cec5SDimitry Andric           "Intrinsic was not defined with variable arguments!", IF);
50940b57cec5SDimitry Andric   else
509581ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
50960b57cec5SDimitry Andric           "Callsite was not defined with variable arguments!", IF);
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
509981ad6265SDimitry Andric   Check(TableRef.empty(), "Intrinsic has too few arguments!", IF);
51000b57cec5SDimitry Andric 
51010b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
51020b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
51030b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
51040b57cec5SDimitry Andric   // the name.
5105fe6060f1SDimitry Andric   const std::string ExpectedName =
5106fe6060f1SDimitry Andric       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
510781ad6265SDimitry Andric   Check(ExpectedName == IF->getName(),
51080b57cec5SDimitry Andric         "Intrinsic name not mangled correctly for type arguments! "
51090b57cec5SDimitry Andric         "Should be: " +
51100b57cec5SDimitry Andric             ExpectedName,
51110b57cec5SDimitry Andric         IF);
51120b57cec5SDimitry Andric 
51130b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
51140b57cec5SDimitry Andric   // or are local to *this* function.
5115fe6060f1SDimitry Andric   for (Value *V : Call.args()) {
51160b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
51170b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
5118fe6060f1SDimitry Andric     if (auto *Const = dyn_cast<Constant>(V))
511981ad6265SDimitry Andric       Check(!Const->getType()->isX86_AMXTy(),
5120fe6060f1SDimitry Andric             "const x86_amx is not allowed in argument!");
5121fe6060f1SDimitry Andric   }
51220b57cec5SDimitry Andric 
51230b57cec5SDimitry Andric   switch (ID) {
51240b57cec5SDimitry Andric   default:
51250b57cec5SDimitry Andric     break;
51265ffd83dbSDimitry Andric   case Intrinsic::assume: {
51275ffd83dbSDimitry Andric     for (auto &Elem : Call.bundle_op_infos()) {
5128bdd1243dSDimitry Andric       unsigned ArgCount = Elem.End - Elem.Begin;
5129bdd1243dSDimitry Andric       // Separate storage assumptions are special insofar as they're the only
5130bdd1243dSDimitry Andric       // operand bundles allowed on assumes that aren't parameter attributes.
5131bdd1243dSDimitry Andric       if (Elem.Tag->getKey() == "separate_storage") {
5132bdd1243dSDimitry Andric         Check(ArgCount == 2,
5133bdd1243dSDimitry Andric               "separate_storage assumptions should have 2 arguments", Call);
5134bdd1243dSDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
5135bdd1243dSDimitry Andric                   Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
5136bdd1243dSDimitry Andric               "arguments to separate_storage assumptions should be pointers",
5137bdd1243dSDimitry Andric               Call);
5138bdd1243dSDimitry Andric         return;
5139bdd1243dSDimitry Andric       }
514081ad6265SDimitry Andric       Check(Elem.Tag->getKey() == "ignore" ||
51415ffd83dbSDimitry Andric                 Attribute::isExistingAttribute(Elem.Tag->getKey()),
5142349cc55cSDimitry Andric             "tags must be valid attribute names", Call);
51435ffd83dbSDimitry Andric       Attribute::AttrKind Kind =
51445ffd83dbSDimitry Andric           Attribute::getAttrKindFromName(Elem.Tag->getKey());
5145e8d8bef9SDimitry Andric       if (Kind == Attribute::Alignment) {
514681ad6265SDimitry Andric         Check(ArgCount <= 3 && ArgCount >= 2,
5147349cc55cSDimitry Andric               "alignment assumptions should have 2 or 3 arguments", Call);
514881ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
5149349cc55cSDimitry Andric               "first argument should be a pointer", Call);
515081ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
5151349cc55cSDimitry Andric               "second argument should be an integer", Call);
5152e8d8bef9SDimitry Andric         if (ArgCount == 3)
515381ad6265SDimitry Andric           Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
5154349cc55cSDimitry Andric                 "third argument should be an integer if present", Call);
5155e8d8bef9SDimitry Andric         return;
5156e8d8bef9SDimitry Andric       }
515781ad6265SDimitry Andric       Check(ArgCount <= 2, "too many arguments", Call);
51585ffd83dbSDimitry Andric       if (Kind == Attribute::None)
51595ffd83dbSDimitry Andric         break;
5160fe6060f1SDimitry Andric       if (Attribute::isIntAttrKind(Kind)) {
516181ad6265SDimitry Andric         Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
516281ad6265SDimitry Andric         Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
5163349cc55cSDimitry Andric               "the second argument should be a constant integral value", Call);
5164fe6060f1SDimitry Andric       } else if (Attribute::canUseAsParamAttr(Kind)) {
516581ad6265SDimitry Andric         Check((ArgCount) == 1, "this attribute should have one argument", Call);
5166fe6060f1SDimitry Andric       } else if (Attribute::canUseAsFnAttr(Kind)) {
516781ad6265SDimitry Andric         Check((ArgCount) == 0, "this attribute has no argument", Call);
51685ffd83dbSDimitry Andric       }
51695ffd83dbSDimitry Andric     }
51705ffd83dbSDimitry Andric     break;
51715ffd83dbSDimitry Andric   }
51720b57cec5SDimitry Andric   case Intrinsic::coro_id: {
51730b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
51740b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
51750b57cec5SDimitry Andric       break;
51760b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
517781ad6265SDimitry Andric     Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
5178fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to an initialized "
51790b57cec5SDimitry Andric           "constant");
51800b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
518181ad6265SDimitry Andric     Check(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
5182fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to either a struct or "
51830b57cec5SDimitry Andric           "an array");
51840b57cec5SDimitry Andric     break;
51850b57cec5SDimitry Andric   }
5186bdd1243dSDimitry Andric   case Intrinsic::is_fpclass: {
5187bdd1243dSDimitry Andric     const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
518806c3fb27SDimitry Andric     Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
5189bdd1243dSDimitry Andric           "unsupported bits for llvm.is.fpclass test mask");
5190bdd1243dSDimitry Andric     break;
5191bdd1243dSDimitry Andric   }
519281ad6265SDimitry Andric   case Intrinsic::fptrunc_round: {
519381ad6265SDimitry Andric     // Check the rounding mode
519481ad6265SDimitry Andric     Metadata *MD = nullptr;
519581ad6265SDimitry Andric     auto *MAV = dyn_cast<MetadataAsValue>(Call.getOperand(1));
519681ad6265SDimitry Andric     if (MAV)
519781ad6265SDimitry Andric       MD = MAV->getMetadata();
519881ad6265SDimitry Andric 
519981ad6265SDimitry Andric     Check(MD != nullptr, "missing rounding mode argument", Call);
520081ad6265SDimitry Andric 
520181ad6265SDimitry Andric     Check(isa<MDString>(MD),
520281ad6265SDimitry Andric           ("invalid value for llvm.fptrunc.round metadata operand"
520381ad6265SDimitry Andric            " (the operand should be a string)"),
520481ad6265SDimitry Andric           MD);
520581ad6265SDimitry Andric 
5206bdd1243dSDimitry Andric     std::optional<RoundingMode> RoundMode =
520781ad6265SDimitry Andric         convertStrToRoundingMode(cast<MDString>(MD)->getString());
520881ad6265SDimitry Andric     Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
520981ad6265SDimitry Andric           "unsupported rounding mode argument", Call);
521081ad6265SDimitry Andric     break;
521181ad6265SDimitry Andric   }
521281ad6265SDimitry Andric #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
521381ad6265SDimitry Andric #include "llvm/IR/VPIntrinsics.def"
521481ad6265SDimitry Andric     visitVPIntrinsic(cast<VPIntrinsic>(Call));
521581ad6265SDimitry Andric     break;
52165ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
5217480093f4SDimitry Andric   case Intrinsic::INTRINSIC:
5218480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
52190b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
52200b57cec5SDimitry Andric     break;
52210b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
522281ad6265SDimitry Andric     Check(isa<MetadataAsValue>(Call.getArgOperand(0)),
52230b57cec5SDimitry Andric           "invalid llvm.dbg.declare intrinsic call 1", Call);
52240b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
52250b57cec5SDimitry Andric     break;
52260b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
52270b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
52280b57cec5SDimitry Andric     break;
5229bdd1243dSDimitry Andric   case Intrinsic::dbg_assign: // llvm.dbg.assign
5230bdd1243dSDimitry Andric     visitDbgIntrinsic("assign", cast<DbgVariableIntrinsic>(Call));
5231bdd1243dSDimitry Andric     break;
52320b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
52330b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
52340b57cec5SDimitry Andric     break;
52350b57cec5SDimitry Andric   case Intrinsic::memcpy:
52365ffd83dbSDimitry Andric   case Intrinsic::memcpy_inline:
52370b57cec5SDimitry Andric   case Intrinsic::memmove:
523881ad6265SDimitry Andric   case Intrinsic::memset:
523981ad6265SDimitry Andric   case Intrinsic::memset_inline: {
52400b57cec5SDimitry Andric     break;
52410b57cec5SDimitry Andric   }
52420b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
52430b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
52440b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
52450b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
52460b57cec5SDimitry Andric 
52470b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
52480b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
52490b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
525081ad6265SDimitry Andric     Check(ElementSizeVal.isPowerOf2(),
52510b57cec5SDimitry Andric           "element size of the element-wise atomic memory intrinsic "
52520b57cec5SDimitry Andric           "must be a power of 2",
52530b57cec5SDimitry Andric           Call);
52540b57cec5SDimitry Andric 
5255bdd1243dSDimitry Andric     auto IsValidAlignment = [&](MaybeAlign Alignment) {
5256bdd1243dSDimitry Andric       return Alignment && ElementSizeVal.ule(Alignment->value());
52570b57cec5SDimitry Andric     };
5258bdd1243dSDimitry Andric     Check(IsValidAlignment(AMI->getDestAlign()),
52590b57cec5SDimitry Andric           "incorrect alignment of the destination argument", Call);
52600b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
5261bdd1243dSDimitry Andric       Check(IsValidAlignment(AMT->getSourceAlign()),
52620b57cec5SDimitry Andric             "incorrect alignment of the source argument", Call);
52630b57cec5SDimitry Andric     }
52640b57cec5SDimitry Andric     break;
52650b57cec5SDimitry Andric   }
52665ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_setup: {
52675ffd83dbSDimitry Andric     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
526881ad6265SDimitry Andric     Check(NumArgs != nullptr,
52695ffd83dbSDimitry Andric           "llvm.call.preallocated.setup argument must be a constant");
52705ffd83dbSDimitry Andric     bool FoundCall = false;
52715ffd83dbSDimitry Andric     for (User *U : Call.users()) {
52725ffd83dbSDimitry Andric       auto *UseCall = dyn_cast<CallBase>(U);
527381ad6265SDimitry Andric       Check(UseCall != nullptr,
52745ffd83dbSDimitry Andric             "Uses of llvm.call.preallocated.setup must be calls");
52755ffd83dbSDimitry Andric       const Function *Fn = UseCall->getCalledFunction();
52765ffd83dbSDimitry Andric       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
52775ffd83dbSDimitry Andric         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
527881ad6265SDimitry Andric         Check(AllocArgIndex != nullptr,
52795ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be a constant");
52805ffd83dbSDimitry Andric         auto AllocArgIndexInt = AllocArgIndex->getValue();
528181ad6265SDimitry Andric         Check(AllocArgIndexInt.sge(0) &&
52825ffd83dbSDimitry Andric                   AllocArgIndexInt.slt(NumArgs->getValue()),
52835ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be between 0 and "
52845ffd83dbSDimitry Andric               "corresponding "
52855ffd83dbSDimitry Andric               "llvm.call.preallocated.setup's argument count");
52865ffd83dbSDimitry Andric       } else if (Fn && Fn->getIntrinsicID() ==
52875ffd83dbSDimitry Andric                            Intrinsic::call_preallocated_teardown) {
52885ffd83dbSDimitry Andric         // nothing to do
52895ffd83dbSDimitry Andric       } else {
529081ad6265SDimitry Andric         Check(!FoundCall, "Can have at most one call corresponding to a "
52915ffd83dbSDimitry Andric                           "llvm.call.preallocated.setup");
52925ffd83dbSDimitry Andric         FoundCall = true;
52935ffd83dbSDimitry Andric         size_t NumPreallocatedArgs = 0;
5294349cc55cSDimitry Andric         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
52955ffd83dbSDimitry Andric           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
52965ffd83dbSDimitry Andric             ++NumPreallocatedArgs;
52975ffd83dbSDimitry Andric           }
52985ffd83dbSDimitry Andric         }
529981ad6265SDimitry Andric         Check(NumPreallocatedArgs != 0,
53005ffd83dbSDimitry Andric               "cannot use preallocated intrinsics on a call without "
53015ffd83dbSDimitry Andric               "preallocated arguments");
530281ad6265SDimitry Andric         Check(NumArgs->equalsInt(NumPreallocatedArgs),
53035ffd83dbSDimitry Andric               "llvm.call.preallocated.setup arg size must be equal to number "
53045ffd83dbSDimitry Andric               "of preallocated arguments "
53055ffd83dbSDimitry Andric               "at call site",
53065ffd83dbSDimitry Andric               Call, *UseCall);
53075ffd83dbSDimitry Andric         // getOperandBundle() cannot be called if more than one of the operand
53085ffd83dbSDimitry Andric         // bundle exists. There is already a check elsewhere for this, so skip
53095ffd83dbSDimitry Andric         // here if we see more than one.
53105ffd83dbSDimitry Andric         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
53115ffd83dbSDimitry Andric             1) {
53125ffd83dbSDimitry Andric           return;
53135ffd83dbSDimitry Andric         }
53145ffd83dbSDimitry Andric         auto PreallocatedBundle =
53155ffd83dbSDimitry Andric             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
531681ad6265SDimitry Andric         Check(PreallocatedBundle,
53175ffd83dbSDimitry Andric               "Use of llvm.call.preallocated.setup outside intrinsics "
53185ffd83dbSDimitry Andric               "must be in \"preallocated\" operand bundle");
531981ad6265SDimitry Andric         Check(PreallocatedBundle->Inputs.front().get() == &Call,
53205ffd83dbSDimitry Andric               "preallocated bundle must have token from corresponding "
53215ffd83dbSDimitry Andric               "llvm.call.preallocated.setup");
53225ffd83dbSDimitry Andric       }
53235ffd83dbSDimitry Andric     }
53245ffd83dbSDimitry Andric     break;
53255ffd83dbSDimitry Andric   }
53265ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_arg: {
53275ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
532881ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
53295ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
53305ffd83dbSDimitry Andric           "llvm.call.preallocated.arg token argument must be a "
53315ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
533281ad6265SDimitry Andric     Check(Call.hasFnAttr(Attribute::Preallocated),
53335ffd83dbSDimitry Andric           "llvm.call.preallocated.arg must be called with a \"preallocated\" "
53345ffd83dbSDimitry Andric           "call site attribute");
53355ffd83dbSDimitry Andric     break;
53365ffd83dbSDimitry Andric   }
53375ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_teardown: {
53385ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
533981ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
53405ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
53415ffd83dbSDimitry Andric           "llvm.call.preallocated.teardown token argument must be a "
53425ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
53435ffd83dbSDimitry Andric     break;
53445ffd83dbSDimitry Andric   }
53450b57cec5SDimitry Andric   case Intrinsic::gcroot:
53460b57cec5SDimitry Andric   case Intrinsic::gcwrite:
53470b57cec5SDimitry Andric   case Intrinsic::gcread:
53480b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
53490b57cec5SDimitry Andric       AllocaInst *AI =
53500b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
535181ad6265SDimitry Andric       Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
535281ad6265SDimitry Andric       Check(isa<Constant>(Call.getArgOperand(1)),
53530b57cec5SDimitry Andric             "llvm.gcroot parameter #2 must be a constant.", Call);
53540b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
535581ad6265SDimitry Andric         Check(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
53560b57cec5SDimitry Andric               "llvm.gcroot parameter #1 must either be a pointer alloca, "
53570b57cec5SDimitry Andric               "or argument #2 must be a non-null constant.",
53580b57cec5SDimitry Andric               Call);
53590b57cec5SDimitry Andric       }
53600b57cec5SDimitry Andric     }
53610b57cec5SDimitry Andric 
536281ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
53630b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
53640b57cec5SDimitry Andric     break;
53650b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
536681ad6265SDimitry Andric     Check(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
53670b57cec5SDimitry Andric           "llvm.init_trampoline parameter #2 must resolve to a function.",
53680b57cec5SDimitry Andric           Call);
53690b57cec5SDimitry Andric     break;
53700b57cec5SDimitry Andric   case Intrinsic::prefetch:
5371bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5372bdd1243dSDimitry Andric           "rw argument to llvm.prefetch must be 0-1", Call);
5373bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
53745f757f3fSDimitry Andric           "locality argument to llvm.prefetch must be 0-3", Call);
5375bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5376bdd1243dSDimitry Andric           "cache type argument to llvm.prefetch must be 0-1", Call);
53770b57cec5SDimitry Andric     break;
53780b57cec5SDimitry Andric   case Intrinsic::stackprotector:
537981ad6265SDimitry Andric     Check(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
53800b57cec5SDimitry Andric           "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
53810b57cec5SDimitry Andric     break;
53820b57cec5SDimitry Andric   case Intrinsic::localescape: {
53830b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
5384bdd1243dSDimitry Andric     Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
5385bdd1243dSDimitry Andric           Call);
538681ad6265SDimitry Andric     Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
538781ad6265SDimitry Andric           Call);
53880b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
53890b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
53900b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
53910b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
539281ad6265SDimitry Andric       Check(AI && AI->isStaticAlloca(),
53930b57cec5SDimitry Andric             "llvm.localescape only accepts static allocas", Call);
53940b57cec5SDimitry Andric     }
5395349cc55cSDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
53960b57cec5SDimitry Andric     SawFrameEscape = true;
53970b57cec5SDimitry Andric     break;
53980b57cec5SDimitry Andric   }
53990b57cec5SDimitry Andric   case Intrinsic::localrecover: {
54000b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
54010b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
540281ad6265SDimitry Andric     Check(Fn && !Fn->isDeclaration(),
54030b57cec5SDimitry Andric           "llvm.localrecover first "
54040b57cec5SDimitry Andric           "argument must be function defined in this module",
54050b57cec5SDimitry Andric           Call);
54060b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
54070b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
54080b57cec5SDimitry Andric     Entry.second = unsigned(
54090b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
54100b57cec5SDimitry Andric     break;
54110b57cec5SDimitry Andric   }
54120b57cec5SDimitry Andric 
54130b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
54140b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
541581ad6265SDimitry Andric       Check(!CI->isInlineAsm(),
54160b57cec5SDimitry Andric             "gc.statepoint support for inline assembly unimplemented", CI);
541781ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
54180b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric     verifyStatepoint(Call);
54210b57cec5SDimitry Andric     break;
54220b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
542381ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
54240b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
5425bdd1243dSDimitry Andric 
5426bdd1243dSDimitry Andric     auto *Statepoint = Call.getArgOperand(0);
5427bdd1243dSDimitry Andric     if (isa<UndefValue>(Statepoint))
5428bdd1243dSDimitry Andric       break;
5429bdd1243dSDimitry Andric 
54300b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
5431bdd1243dSDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
54320b57cec5SDimitry Andric     const Function *StatepointFn =
54330b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
543481ad6265SDimitry Andric     Check(StatepointFn && StatepointFn->isDeclaration() &&
54350b57cec5SDimitry Andric               StatepointFn->getIntrinsicID() ==
54360b57cec5SDimitry Andric                   Intrinsic::experimental_gc_statepoint,
54370b57cec5SDimitry Andric           "gc.result operand #1 must be from a statepoint", Call,
54380b57cec5SDimitry Andric           Call.getArgOperand(0));
54390b57cec5SDimitry Andric 
544081ad6265SDimitry Andric     // Check that result type matches wrapped callee.
544181ad6265SDimitry Andric     auto *TargetFuncType =
544281ad6265SDimitry Andric         cast<FunctionType>(StatepointCall->getParamElementType(2));
544381ad6265SDimitry Andric     Check(Call.getType() == TargetFuncType->getReturnType(),
54440b57cec5SDimitry Andric           "gc.result result type does not match wrapped callee", Call);
54450b57cec5SDimitry Andric     break;
54460b57cec5SDimitry Andric   }
54470b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
544881ad6265SDimitry Andric     Check(Call.arg_size() == 3, "wrong number of arguments", Call);
54490b57cec5SDimitry Andric 
545081ad6265SDimitry Andric     Check(isa<PointerType>(Call.getType()->getScalarType()),
54510b57cec5SDimitry Andric           "gc.relocate must return a pointer or a vector of pointers", Call);
54520b57cec5SDimitry Andric 
54530b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
54560b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
54570b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
54580b57cec5SDimitry Andric 
54590b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
54600b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
54630b57cec5SDimitry Andric       // statepoint terminator
546481ad6265SDimitry Andric       Check(InvokeBB, "safepoints should have unique landingpads",
54650b57cec5SDimitry Andric             LandingPad->getParent());
546681ad6265SDimitry Andric       Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
54670b57cec5SDimitry Andric             InvokeBB);
546881ad6265SDimitry Andric       Check(isa<GCStatepointInst>(InvokeBB->getTerminator()),
54690b57cec5SDimitry Andric             "gc relocate should be linked to a statepoint", InvokeBB);
54700b57cec5SDimitry Andric     } else {
54710b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
54720b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
54730b57cec5SDimitry Andric       // relocates of a call statepoint.
5474fcaf7f86SDimitry Andric       auto *Token = Call.getArgOperand(0);
5475fcaf7f86SDimitry Andric       Check(isa<GCStatepointInst>(Token) || isa<UndefValue>(Token),
54760b57cec5SDimitry Andric             "gc relocate is incorrectly tied to the statepoint", Call, Token);
54770b57cec5SDimitry Andric     }
54780b57cec5SDimitry Andric 
54790b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
5480fcaf7f86SDimitry Andric     const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
54810b57cec5SDimitry Andric 
54820b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
54830b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
548481ad6265SDimitry Andric     Check(isa<ConstantInt>(Base),
54850b57cec5SDimitry Andric           "gc.relocate operand #2 must be integer offset", Call);
54860b57cec5SDimitry Andric 
54870b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
548881ad6265SDimitry Andric     Check(isa<ConstantInt>(Derived),
54890b57cec5SDimitry Andric           "gc.relocate operand #3 must be integer offset", Call);
54900b57cec5SDimitry Andric 
54915ffd83dbSDimitry Andric     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
54925ffd83dbSDimitry Andric     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
54935ffd83dbSDimitry Andric 
54940b57cec5SDimitry Andric     // Check the bounds
5495fcaf7f86SDimitry Andric     if (isa<UndefValue>(StatepointCall))
5496fcaf7f86SDimitry Andric       break;
5497fcaf7f86SDimitry Andric     if (auto Opt = cast<GCStatepointInst>(StatepointCall)
5498fcaf7f86SDimitry Andric                        .getOperandBundle(LLVMContext::OB_gc_live)) {
549981ad6265SDimitry Andric       Check(BaseIndex < Opt->Inputs.size(),
55000b57cec5SDimitry Andric             "gc.relocate: statepoint base index out of bounds", Call);
550181ad6265SDimitry Andric       Check(DerivedIndex < Opt->Inputs.size(),
55025ffd83dbSDimitry Andric             "gc.relocate: statepoint derived index out of bounds", Call);
55035ffd83dbSDimitry Andric     }
55040b57cec5SDimitry Andric 
55050b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
55060b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
55070b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
55080b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
55090b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5510bdd1243dSDimitry Andric     auto *ResultType = Call.getType();
5511bdd1243dSDimitry Andric     auto *DerivedType = Relocate.getDerivedPtr()->getType();
5512bdd1243dSDimitry Andric     auto *BaseType = Relocate.getBasePtr()->getType();
55130b57cec5SDimitry Andric 
5514bdd1243dSDimitry Andric     Check(BaseType->isPtrOrPtrVectorTy(),
5515bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5516bdd1243dSDimitry Andric     Check(DerivedType->isPtrOrPtrVectorTy(),
5517bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5518bdd1243dSDimitry Andric 
551981ad6265SDimitry Andric     Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
55200b57cec5SDimitry Andric           "gc.relocate: vector relocates to vector and pointer to pointer",
55210b57cec5SDimitry Andric           Call);
552281ad6265SDimitry Andric     Check(
55230b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
55240b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
55250b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
55260b57cec5SDimitry Andric         Call);
5527bdd1243dSDimitry Andric 
5528bdd1243dSDimitry Andric     auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
5529bdd1243dSDimitry Andric     Check(GC, "gc.relocate: calling function must have GCStrategy",
5530bdd1243dSDimitry Andric           Call.getFunction());
5531bdd1243dSDimitry Andric     if (GC) {
5532bdd1243dSDimitry Andric       auto isGCPtr = [&GC](Type *PTy) {
5533bdd1243dSDimitry Andric         return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
5534bdd1243dSDimitry Andric       };
5535bdd1243dSDimitry Andric       Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
5536bdd1243dSDimitry Andric       Check(isGCPtr(BaseType),
5537bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5538bdd1243dSDimitry Andric       Check(isGCPtr(DerivedType),
5539bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5540bdd1243dSDimitry Andric     }
55410b57cec5SDimitry Andric     break;
55420b57cec5SDimitry Andric   }
55430b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
55440b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
554581ad6265SDimitry Andric     Check(isa<CatchPadInst>(Call.getArgOperand(0)),
55460b57cec5SDimitry Andric           "eh.exceptionpointer argument must be a catchpad", Call);
55470b57cec5SDimitry Andric     break;
55480b57cec5SDimitry Andric   }
55495ffd83dbSDimitry Andric   case Intrinsic::get_active_lane_mask: {
555081ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(),
555181ad6265SDimitry Andric           "get_active_lane_mask: must return a "
555281ad6265SDimitry Andric           "vector",
555381ad6265SDimitry Andric           Call);
55545ffd83dbSDimitry Andric     auto *ElemTy = Call.getType()->getScalarType();
555581ad6265SDimitry Andric     Check(ElemTy->isIntegerTy(1),
555681ad6265SDimitry Andric           "get_active_lane_mask: element type is not "
555781ad6265SDimitry Andric           "i1",
555881ad6265SDimitry Andric           Call);
55595ffd83dbSDimitry Andric     break;
55605ffd83dbSDimitry Andric   }
556106c3fb27SDimitry Andric   case Intrinsic::experimental_get_vector_length: {
556206c3fb27SDimitry Andric     ConstantInt *VF = cast<ConstantInt>(Call.getArgOperand(1));
556306c3fb27SDimitry Andric     Check(!VF->isNegative() && !VF->isZero(),
556406c3fb27SDimitry Andric           "get_vector_length: VF must be positive", Call);
556506c3fb27SDimitry Andric     break;
556606c3fb27SDimitry Andric   }
55670b57cec5SDimitry Andric   case Intrinsic::masked_load: {
556881ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
55690b57cec5SDimitry Andric           Call);
55700b57cec5SDimitry Andric 
55710b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
55720b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
55730b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
557481ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
55750b57cec5SDimitry Andric           Call);
557681ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
55770b57cec5SDimitry Andric           "masked_load: alignment must be a power of 2", Call);
557881ad6265SDimitry Andric     Check(PassThru->getType() == Call.getType(),
5579fe6060f1SDimitry Andric           "masked_load: pass through and return type must match", Call);
558081ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5581fe6060f1SDimitry Andric               cast<VectorType>(Call.getType())->getElementCount(),
5582fe6060f1SDimitry Andric           "masked_load: vector mask must be same length as return", Call);
55830b57cec5SDimitry Andric     break;
55840b57cec5SDimitry Andric   }
55850b57cec5SDimitry Andric   case Intrinsic::masked_store: {
55860b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
55870b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
55880b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
558981ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
55900b57cec5SDimitry Andric           Call);
559181ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
55920b57cec5SDimitry Andric           "masked_store: alignment must be a power of 2", Call);
559381ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5594fe6060f1SDimitry Andric               cast<VectorType>(Val->getType())->getElementCount(),
5595fe6060f1SDimitry Andric           "masked_store: vector mask must be same length as value", Call);
55960b57cec5SDimitry Andric     break;
55970b57cec5SDimitry Andric   }
55980b57cec5SDimitry Andric 
55995ffd83dbSDimitry Andric   case Intrinsic::masked_gather: {
56005ffd83dbSDimitry Andric     const APInt &Alignment =
56015ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
560281ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
56035ffd83dbSDimitry Andric           "masked_gather: alignment must be 0 or a power of 2", Call);
56045ffd83dbSDimitry Andric     break;
56055ffd83dbSDimitry Andric   }
56065ffd83dbSDimitry Andric   case Intrinsic::masked_scatter: {
56075ffd83dbSDimitry Andric     const APInt &Alignment =
56085ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
560981ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
56105ffd83dbSDimitry Andric           "masked_scatter: alignment must be 0 or a power of 2", Call);
56115ffd83dbSDimitry Andric     break;
56125ffd83dbSDimitry Andric   }
56135ffd83dbSDimitry Andric 
56140b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
561581ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
561681ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
56170b57cec5SDimitry Andric           "experimental_guard must have exactly one "
56180b57cec5SDimitry Andric           "\"deopt\" operand bundle");
56190b57cec5SDimitry Andric     break;
56200b57cec5SDimitry Andric   }
56210b57cec5SDimitry Andric 
56220b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
562381ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
56240b57cec5SDimitry Andric           Call);
562581ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
56260b57cec5SDimitry Andric           "experimental_deoptimize must have exactly one "
56270b57cec5SDimitry Andric           "\"deopt\" operand bundle");
562881ad6265SDimitry Andric     Check(Call.getType() == Call.getFunction()->getReturnType(),
56290b57cec5SDimitry Andric           "experimental_deoptimize return type must match caller return type");
56300b57cec5SDimitry Andric 
56310b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
56320b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
563381ad6265SDimitry Andric       Check(RI,
56340b57cec5SDimitry Andric             "calls to experimental_deoptimize must be followed by a return");
56350b57cec5SDimitry Andric 
56360b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
563781ad6265SDimitry Andric         Check(RI->getReturnValue() == &Call,
56380b57cec5SDimitry Andric               "calls to experimental_deoptimize must be followed by a return "
56390b57cec5SDimitry Andric               "of the value computed by experimental_deoptimize");
56400b57cec5SDimitry Andric     }
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric     break;
56430b57cec5SDimitry Andric   }
5644fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_and:
5645fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_or:
5646fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_xor:
5647fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_add:
5648fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_mul:
5649fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smax:
5650fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smin:
5651fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umax:
5652fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umin: {
5653fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
565481ad6265SDimitry Andric     Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5655fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5656fe6060f1SDimitry Andric     break;
5657fe6060f1SDimitry Andric   }
5658fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmax:
5659fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmin: {
5660fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
566181ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5662fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5663fe6060f1SDimitry Andric     break;
5664fe6060f1SDimitry Andric   }
5665fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fadd:
5666fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmul: {
5667fe6060f1SDimitry Andric     // Unlike the other reductions, the first argument is a start value. The
5668fe6060f1SDimitry Andric     // second argument is the vector to be reduced.
5669fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(1)->getType();
567081ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5671fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
56720b57cec5SDimitry Andric     break;
56730b57cec5SDimitry Andric   }
56740b57cec5SDimitry Andric   case Intrinsic::smul_fix:
56750b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
56768bcb0991SDimitry Andric   case Intrinsic::umul_fix:
5677480093f4SDimitry Andric   case Intrinsic::umul_fix_sat:
5678480093f4SDimitry Andric   case Intrinsic::sdiv_fix:
56795ffd83dbSDimitry Andric   case Intrinsic::sdiv_fix_sat:
56805ffd83dbSDimitry Andric   case Intrinsic::udiv_fix:
56815ffd83dbSDimitry Andric   case Intrinsic::udiv_fix_sat: {
56820b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
56830b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
568481ad6265SDimitry Andric     Check(Op1->getType()->isIntOrIntVectorTy(),
5685480093f4SDimitry Andric           "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5686480093f4SDimitry Andric           "vector of ints");
568781ad6265SDimitry Andric     Check(Op2->getType()->isIntOrIntVectorTy(),
5688480093f4SDimitry Andric           "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5689480093f4SDimitry Andric           "vector of ints");
56900b57cec5SDimitry Andric 
56910b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5692*cb14a3feSDimitry Andric     Check(Op3->getType()->isIntegerTy(),
5693*cb14a3feSDimitry Andric           "third operand of [us][mul|div]_fix[_sat] must be an int type");
5694*cb14a3feSDimitry Andric     Check(Op3->getBitWidth() <= 32,
5695*cb14a3feSDimitry Andric           "third operand of [us][mul|div]_fix[_sat] must fit within 32 bits");
56960b57cec5SDimitry Andric 
5697480093f4SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
56985ffd83dbSDimitry Andric         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
569981ad6265SDimitry Andric       Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5700480093f4SDimitry Andric             "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5701480093f4SDimitry Andric             "the operands");
57020b57cec5SDimitry Andric     } else {
570381ad6265SDimitry Andric       Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5704480093f4SDimitry Andric             "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5705480093f4SDimitry Andric             "to the width of the operands");
57060b57cec5SDimitry Andric     }
57070b57cec5SDimitry Andric     break;
57080b57cec5SDimitry Andric   }
57090b57cec5SDimitry Andric   case Intrinsic::lrint:
57100b57cec5SDimitry Andric   case Intrinsic::llrint: {
57110b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
57120b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
57135f757f3fSDimitry Andric     Check(
57145f757f3fSDimitry Andric         ValTy->isFPOrFPVectorTy() && ResultTy->isIntOrIntVectorTy(),
57155f757f3fSDimitry Andric         "llvm.lrint, llvm.llrint: argument must be floating-point or vector "
57165f757f3fSDimitry Andric         "of floating-points, and result must be integer or vector of integers",
57175f757f3fSDimitry Andric         &Call);
57185f757f3fSDimitry Andric     Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
57195f757f3fSDimitry Andric           "llvm.lrint, llvm.llrint: argument and result disagree on vector use",
57205f757f3fSDimitry Andric           &Call);
57215f757f3fSDimitry Andric     if (ValTy->isVectorTy()) {
57225f757f3fSDimitry Andric       Check(cast<VectorType>(ValTy)->getElementCount() ==
57235f757f3fSDimitry Andric                 cast<VectorType>(ResultTy)->getElementCount(),
57245f757f3fSDimitry Andric             "llvm.lrint, llvm.llrint: argument must be same length as result",
57255f757f3fSDimitry Andric             &Call);
57265f757f3fSDimitry Andric     }
57275f757f3fSDimitry Andric     break;
57285f757f3fSDimitry Andric   }
57295f757f3fSDimitry Andric   case Intrinsic::lround:
57305f757f3fSDimitry Andric   case Intrinsic::llround: {
57315f757f3fSDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
57325f757f3fSDimitry Andric     Type *ResultTy = Call.getType();
573381ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
57340b57cec5SDimitry Andric           "Intrinsic does not support vectors", &Call);
57350b57cec5SDimitry Andric     break;
57360b57cec5SDimitry Andric   }
57375ffd83dbSDimitry Andric   case Intrinsic::bswap: {
57385ffd83dbSDimitry Andric     Type *Ty = Call.getType();
57395ffd83dbSDimitry Andric     unsigned Size = Ty->getScalarSizeInBits();
574081ad6265SDimitry Andric     Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
57415ffd83dbSDimitry Andric     break;
57425ffd83dbSDimitry Andric   }
5743e8d8bef9SDimitry Andric   case Intrinsic::invariant_start: {
5744e8d8bef9SDimitry Andric     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
574581ad6265SDimitry Andric     Check(InvariantSize &&
5746e8d8bef9SDimitry Andric               (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5747e8d8bef9SDimitry Andric           "invariant_start parameter must be -1, 0 or a positive number",
5748e8d8bef9SDimitry Andric           &Call);
5749e8d8bef9SDimitry Andric     break;
5750e8d8bef9SDimitry Andric   }
57515ffd83dbSDimitry Andric   case Intrinsic::matrix_multiply:
57525ffd83dbSDimitry Andric   case Intrinsic::matrix_transpose:
57535ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_load:
57545ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_store: {
57555ffd83dbSDimitry Andric     Function *IF = Call.getCalledFunction();
57565ffd83dbSDimitry Andric     ConstantInt *Stride = nullptr;
57575ffd83dbSDimitry Andric     ConstantInt *NumRows;
57585ffd83dbSDimitry Andric     ConstantInt *NumColumns;
57595ffd83dbSDimitry Andric     VectorType *ResultTy;
57605ffd83dbSDimitry Andric     Type *Op0ElemTy = nullptr;
57615ffd83dbSDimitry Andric     Type *Op1ElemTy = nullptr;
57625ffd83dbSDimitry Andric     switch (ID) {
576306c3fb27SDimitry Andric     case Intrinsic::matrix_multiply: {
57645ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
576506c3fb27SDimitry Andric       ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
57665ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
576706c3fb27SDimitry Andric       Check(cast<FixedVectorType>(Call.getArgOperand(0)->getType())
576806c3fb27SDimitry Andric                     ->getNumElements() ==
576906c3fb27SDimitry Andric                 NumRows->getZExtValue() * N->getZExtValue(),
577006c3fb27SDimitry Andric             "First argument of a matrix operation does not match specified "
577106c3fb27SDimitry Andric             "shape!");
577206c3fb27SDimitry Andric       Check(cast<FixedVectorType>(Call.getArgOperand(1)->getType())
577306c3fb27SDimitry Andric                     ->getNumElements() ==
577406c3fb27SDimitry Andric                 N->getZExtValue() * NumColumns->getZExtValue(),
577506c3fb27SDimitry Andric             "Second argument of a matrix operation does not match specified "
577606c3fb27SDimitry Andric             "shape!");
577706c3fb27SDimitry Andric 
57785ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
57795ffd83dbSDimitry Andric       Op0ElemTy =
57805ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
57815ffd83dbSDimitry Andric       Op1ElemTy =
57825ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
57835ffd83dbSDimitry Andric       break;
578406c3fb27SDimitry Andric     }
57855ffd83dbSDimitry Andric     case Intrinsic::matrix_transpose:
57865ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
57875ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
57885ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
57895ffd83dbSDimitry Andric       Op0ElemTy =
57905ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
57915ffd83dbSDimitry Andric       break;
57924824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_load: {
57935ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
57945ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
57955ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
57965ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
57975ffd83dbSDimitry Andric       break;
57984824e7fdSDimitry Andric     }
57994824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_store: {
58005ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
58015ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
58025ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
58035ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
58045ffd83dbSDimitry Andric       Op0ElemTy =
58055ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
58065ffd83dbSDimitry Andric       break;
58074824e7fdSDimitry Andric     }
58085ffd83dbSDimitry Andric     default:
58095ffd83dbSDimitry Andric       llvm_unreachable("unexpected intrinsic");
58105ffd83dbSDimitry Andric     }
58115ffd83dbSDimitry Andric 
581281ad6265SDimitry Andric     Check(ResultTy->getElementType()->isIntegerTy() ||
58135ffd83dbSDimitry Andric               ResultTy->getElementType()->isFloatingPointTy(),
58145ffd83dbSDimitry Andric           "Result type must be an integer or floating-point type!", IF);
58155ffd83dbSDimitry Andric 
58164824e7fdSDimitry Andric     if (Op0ElemTy)
581781ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op0ElemTy,
58185ffd83dbSDimitry Andric             "Vector element type mismatch of the result and first operand "
581981ad6265SDimitry Andric             "vector!",
582081ad6265SDimitry Andric             IF);
58215ffd83dbSDimitry Andric 
58225ffd83dbSDimitry Andric     if (Op1ElemTy)
582381ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op1ElemTy,
58245ffd83dbSDimitry Andric             "Vector element type mismatch of the result and second operand "
582581ad6265SDimitry Andric             "vector!",
582681ad6265SDimitry Andric             IF);
58275ffd83dbSDimitry Andric 
582881ad6265SDimitry Andric     Check(cast<FixedVectorType>(ResultTy)->getNumElements() ==
58295ffd83dbSDimitry Andric               NumRows->getZExtValue() * NumColumns->getZExtValue(),
58305ffd83dbSDimitry Andric           "Result of a matrix operation does not fit in the returned vector!");
58315ffd83dbSDimitry Andric 
58325ffd83dbSDimitry Andric     if (Stride)
583381ad6265SDimitry Andric       Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
58345ffd83dbSDimitry Andric             "Stride must be greater or equal than the number of rows!", IF);
58355ffd83dbSDimitry Andric 
58365ffd83dbSDimitry Andric     break;
58375ffd83dbSDimitry Andric   }
583804eeddc0SDimitry Andric   case Intrinsic::experimental_vector_splice: {
583904eeddc0SDimitry Andric     VectorType *VecTy = cast<VectorType>(Call.getType());
584004eeddc0SDimitry Andric     int64_t Idx = cast<ConstantInt>(Call.getArgOperand(2))->getSExtValue();
584104eeddc0SDimitry Andric     int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
584204eeddc0SDimitry Andric     if (Call.getParent() && Call.getParent()->getParent()) {
584304eeddc0SDimitry Andric       AttributeList Attrs = Call.getParent()->getParent()->getAttributes();
584404eeddc0SDimitry Andric       if (Attrs.hasFnAttr(Attribute::VScaleRange))
584504eeddc0SDimitry Andric         KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
584604eeddc0SDimitry Andric     }
584781ad6265SDimitry Andric     Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
584804eeddc0SDimitry Andric               (Idx >= 0 && Idx < KnownMinNumElements),
584904eeddc0SDimitry Andric           "The splice index exceeds the range [-VL, VL-1] where VL is the "
585004eeddc0SDimitry Andric           "known minimum number of elements in the vector. For scalable "
585104eeddc0SDimitry Andric           "vectors the minimum number of elements is determined from "
585204eeddc0SDimitry Andric           "vscale_range.",
585304eeddc0SDimitry Andric           &Call);
585404eeddc0SDimitry Andric     break;
585504eeddc0SDimitry Andric   }
5856fe6060f1SDimitry Andric   case Intrinsic::experimental_stepvector: {
5857fe6060f1SDimitry Andric     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
585881ad6265SDimitry Andric     Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
5859fe6060f1SDimitry Andric               VecTy->getScalarSizeInBits() >= 8,
5860fe6060f1SDimitry Andric           "experimental_stepvector only supported for vectors of integers "
5861fe6060f1SDimitry Andric           "with a bitwidth of at least 8.",
5862fe6060f1SDimitry Andric           &Call);
5863fe6060f1SDimitry Andric     break;
5864fe6060f1SDimitry Andric   }
586581ad6265SDimitry Andric   case Intrinsic::vector_insert: {
5866fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5867fe6060f1SDimitry Andric     Value *SubVec = Call.getArgOperand(1);
5868fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(2);
5869fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5870e8d8bef9SDimitry Andric 
5871fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5872fe6060f1SDimitry Andric     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
5873fe6060f1SDimitry Andric 
5874fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5875fe6060f1SDimitry Andric     ElementCount SubVecEC = SubVecTy->getElementCount();
587681ad6265SDimitry Andric     Check(VecTy->getElementType() == SubVecTy->getElementType(),
587781ad6265SDimitry Andric           "vector_insert parameters must have the same element "
5878e8d8bef9SDimitry Andric           "type.",
5879e8d8bef9SDimitry Andric           &Call);
588081ad6265SDimitry Andric     Check(IdxN % SubVecEC.getKnownMinValue() == 0,
588181ad6265SDimitry Andric           "vector_insert index must be a constant multiple of "
5882fe6060f1SDimitry Andric           "the subvector's known minimum vector length.");
5883fe6060f1SDimitry Andric 
5884fe6060f1SDimitry Andric     // If this insertion is not the 'mixed' case where a fixed vector is
5885fe6060f1SDimitry Andric     // inserted into a scalable vector, ensure that the insertion of the
5886fe6060f1SDimitry Andric     // subvector does not overrun the parent vector.
5887fe6060f1SDimitry Andric     if (VecEC.isScalable() == SubVecEC.isScalable()) {
588881ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
5889fe6060f1SDimitry Andric                 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
589081ad6265SDimitry Andric             "subvector operand of vector_insert would overrun the "
5891fe6060f1SDimitry Andric             "vector being inserted into.");
5892fe6060f1SDimitry Andric     }
5893e8d8bef9SDimitry Andric     break;
5894e8d8bef9SDimitry Andric   }
589581ad6265SDimitry Andric   case Intrinsic::vector_extract: {
5896fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
5897fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(1);
5898fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
5899fe6060f1SDimitry Andric 
5900e8d8bef9SDimitry Andric     VectorType *ResultTy = cast<VectorType>(Call.getType());
5901fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
5902fe6060f1SDimitry Andric 
5903fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
5904fe6060f1SDimitry Andric     ElementCount ResultEC = ResultTy->getElementCount();
5905e8d8bef9SDimitry Andric 
590681ad6265SDimitry Andric     Check(ResultTy->getElementType() == VecTy->getElementType(),
590781ad6265SDimitry Andric           "vector_extract result must have the same element "
5908e8d8bef9SDimitry Andric           "type as the input vector.",
5909e8d8bef9SDimitry Andric           &Call);
591081ad6265SDimitry Andric     Check(IdxN % ResultEC.getKnownMinValue() == 0,
591181ad6265SDimitry Andric           "vector_extract index must be a constant multiple of "
5912fe6060f1SDimitry Andric           "the result type's known minimum vector length.");
5913fe6060f1SDimitry Andric 
59145f757f3fSDimitry Andric     // If this extraction is not the 'mixed' case where a fixed vector is
5915fe6060f1SDimitry Andric     // extracted from a scalable vector, ensure that the extraction does not
5916fe6060f1SDimitry Andric     // overrun the parent vector.
5917fe6060f1SDimitry Andric     if (VecEC.isScalable() == ResultEC.isScalable()) {
591881ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
5919fe6060f1SDimitry Andric                 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
592081ad6265SDimitry Andric             "vector_extract would overrun.");
5921fe6060f1SDimitry Andric     }
5922e8d8bef9SDimitry Andric     break;
5923e8d8bef9SDimitry Andric   }
5924e8d8bef9SDimitry Andric   case Intrinsic::experimental_noalias_scope_decl: {
5925e8d8bef9SDimitry Andric     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
5926e8d8bef9SDimitry Andric     break;
5927e8d8bef9SDimitry Andric   }
5928fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
592981ad6265SDimitry Andric   case Intrinsic::preserve_struct_access_index:
593081ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
593181ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
593281ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
593381ad6265SDimitry Andric   case Intrinsic::arm_ldrex: {
593481ad6265SDimitry Andric     Type *ElemTy = Call.getParamElementType(0);
593581ad6265SDimitry Andric     Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
593681ad6265SDimitry Andric           &Call);
593781ad6265SDimitry Andric     break;
593881ad6265SDimitry Andric   }
593981ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
594081ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
594181ad6265SDimitry Andric   case Intrinsic::arm_stlex:
594281ad6265SDimitry Andric   case Intrinsic::arm_strex: {
594381ad6265SDimitry Andric     Type *ElemTy = Call.getAttributes().getParamElementType(1);
594481ad6265SDimitry Andric     Check(ElemTy,
594581ad6265SDimitry Andric           "Intrinsic requires elementtype attribute on second argument.",
5946fe6060f1SDimitry Andric           &Call);
5947fe6060f1SDimitry Andric     break;
5948fe6060f1SDimitry Andric   }
5949bdd1243dSDimitry Andric   case Intrinsic::aarch64_prefetch: {
5950bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5951bdd1243dSDimitry Andric           "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5952bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
5953bdd1243dSDimitry Andric           "target argument to llvm.aarch64.prefetch must be 0-3", Call);
5954bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5955bdd1243dSDimitry Andric           "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5956bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
5957bdd1243dSDimitry Andric           "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
5958bdd1243dSDimitry Andric     break;
5959bdd1243dSDimitry Andric   }
596006c3fb27SDimitry Andric   case Intrinsic::callbr_landingpad: {
596106c3fb27SDimitry Andric     const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
596206c3fb27SDimitry Andric     Check(CBR, "intrinstic requires callbr operand", &Call);
596306c3fb27SDimitry Andric     if (!CBR)
596406c3fb27SDimitry Andric       break;
596506c3fb27SDimitry Andric 
596606c3fb27SDimitry Andric     const BasicBlock *LandingPadBB = Call.getParent();
596706c3fb27SDimitry Andric     const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
596806c3fb27SDimitry Andric     if (!PredBB) {
596906c3fb27SDimitry Andric       CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
597006c3fb27SDimitry Andric       break;
597106c3fb27SDimitry Andric     }
597206c3fb27SDimitry Andric     if (!isa<CallBrInst>(PredBB->getTerminator())) {
597306c3fb27SDimitry Andric       CheckFailed("Intrinsic must have corresponding callbr in predecessor",
597406c3fb27SDimitry Andric                   &Call);
597506c3fb27SDimitry Andric       break;
597606c3fb27SDimitry Andric     }
597706c3fb27SDimitry Andric     Check(llvm::any_of(CBR->getIndirectDests(),
597806c3fb27SDimitry Andric                        [LandingPadBB](const BasicBlock *IndDest) {
597906c3fb27SDimitry Andric                          return IndDest == LandingPadBB;
598006c3fb27SDimitry Andric                        }),
598106c3fb27SDimitry Andric           "Intrinsic's corresponding callbr must have intrinsic's parent basic "
598206c3fb27SDimitry Andric           "block in indirect destination list",
598306c3fb27SDimitry Andric           &Call);
598406c3fb27SDimitry Andric     const Instruction &First = *LandingPadBB->begin();
598506c3fb27SDimitry Andric     Check(&First == &Call, "No other instructions may proceed intrinsic",
598606c3fb27SDimitry Andric           &Call);
598706c3fb27SDimitry Andric     break;
598806c3fb27SDimitry Andric   }
598906c3fb27SDimitry Andric   case Intrinsic::amdgcn_cs_chain: {
599006c3fb27SDimitry Andric     auto CallerCC = Call.getCaller()->getCallingConv();
599106c3fb27SDimitry Andric     switch (CallerCC) {
599206c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS:
599306c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS_Chain:
599406c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS_ChainPreserve:
599506c3fb27SDimitry Andric       break;
599606c3fb27SDimitry Andric     default:
599706c3fb27SDimitry Andric       CheckFailed("Intrinsic can only be used from functions with the "
599806c3fb27SDimitry Andric                   "amdgpu_cs, amdgpu_cs_chain or amdgpu_cs_chain_preserve "
599906c3fb27SDimitry Andric                   "calling conventions",
600006c3fb27SDimitry Andric                   &Call);
600106c3fb27SDimitry Andric       break;
600206c3fb27SDimitry Andric     }
60035f757f3fSDimitry Andric 
60045f757f3fSDimitry Andric     Check(Call.paramHasAttr(2, Attribute::InReg),
60055f757f3fSDimitry Andric           "SGPR arguments must have the `inreg` attribute", &Call);
60065f757f3fSDimitry Andric     Check(!Call.paramHasAttr(3, Attribute::InReg),
60075f757f3fSDimitry Andric           "VGPR arguments must not have the `inreg` attribute", &Call);
60085f757f3fSDimitry Andric     break;
60095f757f3fSDimitry Andric   }
60105f757f3fSDimitry Andric   case Intrinsic::amdgcn_set_inactive_chain_arg: {
60115f757f3fSDimitry Andric     auto CallerCC = Call.getCaller()->getCallingConv();
60125f757f3fSDimitry Andric     switch (CallerCC) {
60135f757f3fSDimitry Andric     case CallingConv::AMDGPU_CS_Chain:
60145f757f3fSDimitry Andric     case CallingConv::AMDGPU_CS_ChainPreserve:
60155f757f3fSDimitry Andric       break;
60165f757f3fSDimitry Andric     default:
60175f757f3fSDimitry Andric       CheckFailed("Intrinsic can only be used from functions with the "
60185f757f3fSDimitry Andric                   "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
60195f757f3fSDimitry Andric                   "calling conventions",
60205f757f3fSDimitry Andric                   &Call);
60215f757f3fSDimitry Andric       break;
60225f757f3fSDimitry Andric     }
60235f757f3fSDimitry Andric 
60245f757f3fSDimitry Andric     unsigned InactiveIdx = 1;
60255f757f3fSDimitry Andric     Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
60265f757f3fSDimitry Andric           "Value for inactive lanes must not have the `inreg` attribute",
60275f757f3fSDimitry Andric           &Call);
60285f757f3fSDimitry Andric     Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
60295f757f3fSDimitry Andric           "Value for inactive lanes must be a function argument", &Call);
60305f757f3fSDimitry Andric     Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
60315f757f3fSDimitry Andric           "Value for inactive lanes must be a VGPR function argument", &Call);
603206c3fb27SDimitry Andric     break;
603306c3fb27SDimitry Andric   }
603406c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_entry:
603506c3fb27SDimitry Andric     LLVM_FALLTHROUGH;
603606c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_anchor:
603706c3fb27SDimitry Andric     break;
603806c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_loop:
603906c3fb27SDimitry Andric     break;
60405f757f3fSDimitry Andric   case Intrinsic::ptrmask: {
60415f757f3fSDimitry Andric     Type *Ty0 = Call.getArgOperand(0)->getType();
60425f757f3fSDimitry Andric     Type *Ty1 = Call.getArgOperand(1)->getType();
60435f757f3fSDimitry Andric     Check(Ty0->isPtrOrPtrVectorTy(),
60445f757f3fSDimitry Andric           "llvm.ptrmask intrinsic first argument must be pointer or vector "
60455f757f3fSDimitry Andric           "of pointers",
60465f757f3fSDimitry Andric           &Call);
60475f757f3fSDimitry Andric     Check(
60485f757f3fSDimitry Andric         Ty0->isVectorTy() == Ty1->isVectorTy(),
60495f757f3fSDimitry Andric         "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
60505f757f3fSDimitry Andric         &Call);
60515f757f3fSDimitry Andric     if (Ty0->isVectorTy())
60525f757f3fSDimitry Andric       Check(cast<VectorType>(Ty0)->getElementCount() ==
60535f757f3fSDimitry Andric                 cast<VectorType>(Ty1)->getElementCount(),
60545f757f3fSDimitry Andric             "llvm.ptrmask intrinsic arguments must have the same number of "
60555f757f3fSDimitry Andric             "elements",
60565f757f3fSDimitry Andric             &Call);
60575f757f3fSDimitry Andric     Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
60585f757f3fSDimitry Andric           "llvm.ptrmask intrinsic second argument bitwidth must match "
60595f757f3fSDimitry Andric           "pointer index type size of first argument",
60605f757f3fSDimitry Andric           &Call);
60615f757f3fSDimitry Andric     break;
60625f757f3fSDimitry Andric   }
60630b57cec5SDimitry Andric   };
606406c3fb27SDimitry Andric 
606506c3fb27SDimitry Andric   // Verify that there aren't any unmediated control transfers between funclets.
606606c3fb27SDimitry Andric   if (IntrinsicInst::mayLowerToFunctionCall(ID)) {
606706c3fb27SDimitry Andric     Function *F = Call.getParent()->getParent();
606806c3fb27SDimitry Andric     if (F->hasPersonalityFn() &&
606906c3fb27SDimitry Andric         isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
607006c3fb27SDimitry Andric       // Run EH funclet coloring on-demand and cache results for other intrinsic
607106c3fb27SDimitry Andric       // calls in this function
607206c3fb27SDimitry Andric       if (BlockEHFuncletColors.empty())
607306c3fb27SDimitry Andric         BlockEHFuncletColors = colorEHFunclets(*F);
607406c3fb27SDimitry Andric 
607506c3fb27SDimitry Andric       // Check for catch-/cleanup-pad in first funclet block
607606c3fb27SDimitry Andric       bool InEHFunclet = false;
607706c3fb27SDimitry Andric       BasicBlock *CallBB = Call.getParent();
607806c3fb27SDimitry Andric       const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
607906c3fb27SDimitry Andric       assert(CV.size() > 0 && "Uncolored block");
608006c3fb27SDimitry Andric       for (BasicBlock *ColorFirstBB : CV)
608106c3fb27SDimitry Andric         if (dyn_cast_or_null<FuncletPadInst>(ColorFirstBB->getFirstNonPHI()))
608206c3fb27SDimitry Andric           InEHFunclet = true;
608306c3fb27SDimitry Andric 
608406c3fb27SDimitry Andric       // Check for funclet operand bundle
608506c3fb27SDimitry Andric       bool HasToken = false;
608606c3fb27SDimitry Andric       for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
608706c3fb27SDimitry Andric         if (Call.getOperandBundleAt(I).getTagID() == LLVMContext::OB_funclet)
608806c3fb27SDimitry Andric           HasToken = true;
608906c3fb27SDimitry Andric 
609006c3fb27SDimitry Andric       // This would cause silent code truncation in WinEHPrepare
609106c3fb27SDimitry Andric       if (InEHFunclet)
609206c3fb27SDimitry Andric         Check(HasToken, "Missing funclet token on intrinsic call", &Call);
609306c3fb27SDimitry Andric     }
609406c3fb27SDimitry Andric   }
60950b57cec5SDimitry Andric }
60960b57cec5SDimitry Andric 
60970b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
60980b57cec5SDimitry Andric ///
60990b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
61000b57cec5SDimitry Andric /// built-in assertions that would typically fire.
61010b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
61020b57cec5SDimitry Andric   if (!LocalScope)
61030b57cec5SDimitry Andric     return nullptr;
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
61060b57cec5SDimitry Andric     return SP;
61070b57cec5SDimitry Andric 
61080b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
61090b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
61100b57cec5SDimitry Andric 
61110b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
61120b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
61130b57cec5SDimitry Andric   return nullptr;
61140b57cec5SDimitry Andric }
61150b57cec5SDimitry Andric 
611681ad6265SDimitry Andric void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
611781ad6265SDimitry Andric   if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
611881ad6265SDimitry Andric     auto *RetTy = cast<VectorType>(VPCast->getType());
611981ad6265SDimitry Andric     auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
612081ad6265SDimitry Andric     Check(RetTy->getElementCount() == ValTy->getElementCount(),
612181ad6265SDimitry Andric           "VP cast intrinsic first argument and result vector lengths must be "
612281ad6265SDimitry Andric           "equal",
612381ad6265SDimitry Andric           *VPCast);
612481ad6265SDimitry Andric 
612581ad6265SDimitry Andric     switch (VPCast->getIntrinsicID()) {
612681ad6265SDimitry Andric     default:
612781ad6265SDimitry Andric       llvm_unreachable("Unknown VP cast intrinsic");
612881ad6265SDimitry Andric     case Intrinsic::vp_trunc:
612981ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
613081ad6265SDimitry Andric             "llvm.vp.trunc intrinsic first argument and result element type "
613181ad6265SDimitry Andric             "must be integer",
613281ad6265SDimitry Andric             *VPCast);
613381ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
613481ad6265SDimitry Andric             "llvm.vp.trunc intrinsic the bit size of first argument must be "
613581ad6265SDimitry Andric             "larger than the bit size of the return type",
613681ad6265SDimitry Andric             *VPCast);
613781ad6265SDimitry Andric       break;
613881ad6265SDimitry Andric     case Intrinsic::vp_zext:
613981ad6265SDimitry Andric     case Intrinsic::vp_sext:
614081ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
614181ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
614281ad6265SDimitry Andric             "element type must be integer",
614381ad6265SDimitry Andric             *VPCast);
614481ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
614581ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
614681ad6265SDimitry Andric             "argument must be smaller than the bit size of the return type",
614781ad6265SDimitry Andric             *VPCast);
614881ad6265SDimitry Andric       break;
614981ad6265SDimitry Andric     case Intrinsic::vp_fptoui:
615081ad6265SDimitry Andric     case Intrinsic::vp_fptosi:
615181ad6265SDimitry Andric       Check(
615281ad6265SDimitry Andric           RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
615381ad6265SDimitry Andric           "llvm.vp.fptoui or llvm.vp.fptosi intrinsic first argument element "
615481ad6265SDimitry Andric           "type must be floating-point and result element type must be integer",
615581ad6265SDimitry Andric           *VPCast);
615681ad6265SDimitry Andric       break;
615781ad6265SDimitry Andric     case Intrinsic::vp_uitofp:
615881ad6265SDimitry Andric     case Intrinsic::vp_sitofp:
615981ad6265SDimitry Andric       Check(
616081ad6265SDimitry Andric           RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
616181ad6265SDimitry Andric           "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
616281ad6265SDimitry Andric           "type must be integer and result element type must be floating-point",
616381ad6265SDimitry Andric           *VPCast);
616481ad6265SDimitry Andric       break;
616581ad6265SDimitry Andric     case Intrinsic::vp_fptrunc:
616681ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
616781ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic first argument and result element type "
616881ad6265SDimitry Andric             "must be floating-point",
616981ad6265SDimitry Andric             *VPCast);
617081ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
617181ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
617281ad6265SDimitry Andric             "larger than the bit size of the return type",
617381ad6265SDimitry Andric             *VPCast);
617481ad6265SDimitry Andric       break;
617581ad6265SDimitry Andric     case Intrinsic::vp_fpext:
617681ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
617781ad6265SDimitry Andric             "llvm.vp.fpext intrinsic first argument and result element type "
617881ad6265SDimitry Andric             "must be floating-point",
617981ad6265SDimitry Andric             *VPCast);
618081ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
618181ad6265SDimitry Andric             "llvm.vp.fpext intrinsic the bit size of first argument must be "
618281ad6265SDimitry Andric             "smaller than the bit size of the return type",
618381ad6265SDimitry Andric             *VPCast);
618481ad6265SDimitry Andric       break;
618581ad6265SDimitry Andric     case Intrinsic::vp_ptrtoint:
618681ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
618781ad6265SDimitry Andric             "llvm.vp.ptrtoint intrinsic first argument element type must be "
618881ad6265SDimitry Andric             "pointer and result element type must be integer",
618981ad6265SDimitry Andric             *VPCast);
619081ad6265SDimitry Andric       break;
619181ad6265SDimitry Andric     case Intrinsic::vp_inttoptr:
619281ad6265SDimitry Andric       Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
619381ad6265SDimitry Andric             "llvm.vp.inttoptr intrinsic first argument element type must be "
619481ad6265SDimitry Andric             "integer and result element type must be pointer",
619581ad6265SDimitry Andric             *VPCast);
619681ad6265SDimitry Andric       break;
619781ad6265SDimitry Andric     }
619881ad6265SDimitry Andric   }
619981ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_fcmp) {
620081ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
620181ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
620281ad6265SDimitry Andric           "invalid predicate for VP FP comparison intrinsic", &VPI);
620381ad6265SDimitry Andric   }
620481ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_icmp) {
620581ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
620681ad6265SDimitry Andric     Check(CmpInst::isIntPredicate(Pred),
620781ad6265SDimitry Andric           "invalid predicate for VP integer comparison intrinsic", &VPI);
620881ad6265SDimitry Andric   }
62095f757f3fSDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_is_fpclass) {
62105f757f3fSDimitry Andric     auto TestMask = cast<ConstantInt>(VPI.getOperand(1));
62115f757f3fSDimitry Andric     Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
62125f757f3fSDimitry Andric           "unsupported bits for llvm.vp.is.fpclass test mask");
62135f757f3fSDimitry Andric   }
621481ad6265SDimitry Andric }
621581ad6265SDimitry Andric 
62160b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
6217480093f4SDimitry Andric   unsigned NumOperands;
6218480093f4SDimitry Andric   bool HasRoundingMD;
62190b57cec5SDimitry Andric   switch (FPI.getIntrinsicID()) {
62205ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6221480093f4SDimitry Andric   case Intrinsic::INTRINSIC:                                                   \
6222480093f4SDimitry Andric     NumOperands = NARG;                                                        \
6223480093f4SDimitry Andric     HasRoundingMD = ROUND_MODE;                                                \
62240b57cec5SDimitry Andric     break;
6225480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
6226480093f4SDimitry Andric   default:
6227480093f4SDimitry Andric     llvm_unreachable("Invalid constrained FP intrinsic!");
6228480093f4SDimitry Andric   }
6229480093f4SDimitry Andric   NumOperands += (1 + HasRoundingMD);
6230480093f4SDimitry Andric   // Compare intrinsics carry an extra predicate metadata operand.
6231480093f4SDimitry Andric   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
6232480093f4SDimitry Andric     NumOperands += 1;
623381ad6265SDimitry Andric   Check((FPI.arg_size() == NumOperands),
6234480093f4SDimitry Andric         "invalid arguments for constrained FP intrinsic", &FPI);
62350b57cec5SDimitry Andric 
6236480093f4SDimitry Andric   switch (FPI.getIntrinsicID()) {
62378bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
62388bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
62398bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
62408bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
624181ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
62428bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
62438bcb0991SDimitry Andric   }
62448bcb0991SDimitry Andric     break;
62458bcb0991SDimitry Andric 
62468bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
62478bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
62488bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
62498bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
625081ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
62518bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
62528bcb0991SDimitry Andric     break;
62538bcb0991SDimitry Andric   }
62548bcb0991SDimitry Andric 
6255480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmp:
6256480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmps: {
6257480093f4SDimitry Andric     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
625881ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
6259480093f4SDimitry Andric           "invalid predicate for constrained FP comparison intrinsic", &FPI);
62600b57cec5SDimitry Andric     break;
6261480093f4SDimitry Andric   }
62620b57cec5SDimitry Andric 
62638bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
62648bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
62658bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
626606c3fb27SDimitry Andric     ElementCount SrcEC;
626781ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
62688bcb0991SDimitry Andric           "Intrinsic first argument must be floating point", &FPI);
62698bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
627006c3fb27SDimitry Andric       SrcEC = cast<VectorType>(OperandT)->getElementCount();
62718bcb0991SDimitry Andric     }
62728bcb0991SDimitry Andric 
62738bcb0991SDimitry Andric     Operand = &FPI;
627406c3fb27SDimitry Andric     Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
62758bcb0991SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
627681ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
62778bcb0991SDimitry Andric           "Intrinsic result must be an integer", &FPI);
62788bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
627906c3fb27SDimitry Andric       Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
62808bcb0991SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
62818bcb0991SDimitry Andric             &FPI);
62828bcb0991SDimitry Andric     }
62838bcb0991SDimitry Andric   }
62848bcb0991SDimitry Andric     break;
62858bcb0991SDimitry Andric 
6286480093f4SDimitry Andric   case Intrinsic::experimental_constrained_sitofp:
6287480093f4SDimitry Andric   case Intrinsic::experimental_constrained_uitofp: {
6288480093f4SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
628906c3fb27SDimitry Andric     ElementCount SrcEC;
629081ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
6291480093f4SDimitry Andric           "Intrinsic first argument must be integer", &FPI);
6292480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
629306c3fb27SDimitry Andric       SrcEC = cast<VectorType>(OperandT)->getElementCount();
6294480093f4SDimitry Andric     }
6295480093f4SDimitry Andric 
6296480093f4SDimitry Andric     Operand = &FPI;
629706c3fb27SDimitry Andric     Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
6298480093f4SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
629981ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
6300480093f4SDimitry Andric           "Intrinsic result must be a floating point", &FPI);
6301480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
630206c3fb27SDimitry Andric       Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
6303480093f4SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
6304480093f4SDimitry Andric             &FPI);
6305480093f4SDimitry Andric     }
6306480093f4SDimitry Andric   } break;
6307480093f4SDimitry Andric 
63080b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
63090b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
63100b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
63110b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
63120b57cec5SDimitry Andric     Value *Result = &FPI;
63130b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
631481ad6265SDimitry Andric     Check(OperandTy->isFPOrFPVectorTy(),
63150b57cec5SDimitry Andric           "Intrinsic first argument must be FP or FP vector", &FPI);
631681ad6265SDimitry Andric     Check(ResultTy->isFPOrFPVectorTy(),
63170b57cec5SDimitry Andric           "Intrinsic result must be FP or FP vector", &FPI);
631881ad6265SDimitry Andric     Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
63190b57cec5SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
63200b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
632106c3fb27SDimitry Andric       Check(cast<VectorType>(OperandTy)->getElementCount() ==
632206c3fb27SDimitry Andric                 cast<VectorType>(ResultTy)->getElementCount(),
63230b57cec5SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
63240b57cec5SDimitry Andric             &FPI);
63250b57cec5SDimitry Andric     }
63260b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
632781ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
63280b57cec5SDimitry Andric             "Intrinsic first argument's type must be larger than result type",
63290b57cec5SDimitry Andric             &FPI);
63300b57cec5SDimitry Andric     } else {
633181ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
63320b57cec5SDimitry Andric             "Intrinsic first argument's type must be smaller than result type",
63330b57cec5SDimitry Andric             &FPI);
63340b57cec5SDimitry Andric     }
63350b57cec5SDimitry Andric   }
63360b57cec5SDimitry Andric     break;
63370b57cec5SDimitry Andric 
63380b57cec5SDimitry Andric   default:
6339480093f4SDimitry Andric     break;
63400b57cec5SDimitry Andric   }
63410b57cec5SDimitry Andric 
63420b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
63430b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
63440b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
63450b57cec5SDimitry Andric   // argument type check is needed here.
63460b57cec5SDimitry Andric 
634781ad6265SDimitry Andric   Check(FPI.getExceptionBehavior().has_value(),
63480b57cec5SDimitry Andric         "invalid exception behavior argument", &FPI);
63490b57cec5SDimitry Andric   if (HasRoundingMD) {
635081ad6265SDimitry Andric     Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
635181ad6265SDimitry Andric           &FPI);
63520b57cec5SDimitry Andric   }
63530b57cec5SDimitry Andric }
63540b57cec5SDimitry Andric 
63550b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
6356fe6060f1SDimitry Andric   auto *MD = DII.getRawLocation();
635781ad6265SDimitry Andric   CheckDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
63580b57cec5SDimitry Andric               (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
63590b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
636081ad6265SDimitry Andric   CheckDI(isa<DILocalVariable>(DII.getRawVariable()),
63610b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
63620b57cec5SDimitry Andric           DII.getRawVariable());
636381ad6265SDimitry Andric   CheckDI(isa<DIExpression>(DII.getRawExpression()),
63640b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
63650b57cec5SDimitry Andric           DII.getRawExpression());
63660b57cec5SDimitry Andric 
6367bdd1243dSDimitry Andric   if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&DII)) {
6368bdd1243dSDimitry Andric     CheckDI(isa<DIAssignID>(DAI->getRawAssignID()),
6369bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic DIAssignID", &DII,
6370bdd1243dSDimitry Andric             DAI->getRawAssignID());
6371bdd1243dSDimitry Andric     const auto *RawAddr = DAI->getRawAddress();
6372bdd1243dSDimitry Andric     CheckDI(
6373bdd1243dSDimitry Andric         isa<ValueAsMetadata>(RawAddr) ||
6374bdd1243dSDimitry Andric             (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
6375bdd1243dSDimitry Andric         "invalid llvm.dbg.assign intrinsic address", &DII,
6376bdd1243dSDimitry Andric         DAI->getRawAddress());
6377bdd1243dSDimitry Andric     CheckDI(isa<DIExpression>(DAI->getRawAddressExpression()),
6378bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic address expression", &DII,
6379bdd1243dSDimitry Andric             DAI->getRawAddressExpression());
6380bdd1243dSDimitry Andric     // All of the linked instructions should be in the same function as DII.
6381bdd1243dSDimitry Andric     for (Instruction *I : at::getAssignmentInsts(DAI))
6382bdd1243dSDimitry Andric       CheckDI(DAI->getFunction() == I->getFunction(),
6383bdd1243dSDimitry Andric               "inst not in same function as dbg.assign", I, DAI);
6384bdd1243dSDimitry Andric   }
6385bdd1243dSDimitry Andric 
63860b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
63870b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
63880b57cec5SDimitry Andric     if (!isa<DILocation>(N))
63890b57cec5SDimitry Andric       return;
63900b57cec5SDimitry Andric 
63910b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
63920b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
63930b57cec5SDimitry Andric 
63940b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
63950b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
63960b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
639781ad6265SDimitry Andric   CheckDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
63980b57cec5SDimitry Andric           &DII, BB, F);
63990b57cec5SDimitry Andric 
64000b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
64010b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
64020b57cec5SDimitry Andric   if (!VarSP || !LocSP)
64030b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
64040b57cec5SDimitry Andric 
640581ad6265SDimitry Andric   CheckDI(VarSP == LocSP,
640681ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
64070b57cec5SDimitry Andric               " variable and !dbg attachment",
64080b57cec5SDimitry Andric           &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
64090b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
64100b57cec5SDimitry Andric 
64110b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
641281ad6265SDimitry Andric   CheckDI(isType(Var->getRawType()), "invalid type ref", Var,
64130b57cec5SDimitry Andric           Var->getRawType());
64140b57cec5SDimitry Andric   verifyFnArgs(DII);
64150b57cec5SDimitry Andric }
64160b57cec5SDimitry Andric 
64170b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
641881ad6265SDimitry Andric   CheckDI(isa<DILabel>(DLI.getRawLabel()),
64190b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
64200b57cec5SDimitry Andric           DLI.getRawLabel());
64210b57cec5SDimitry Andric 
64220b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
64230b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
64240b57cec5SDimitry Andric     if (!isa<DILocation>(N))
64250b57cec5SDimitry Andric       return;
64260b57cec5SDimitry Andric 
64270b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
64280b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
64290b57cec5SDimitry Andric 
64300b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
64310b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
64320b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
643381ad6265SDimitry Andric   Check(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", &DLI,
643481ad6265SDimitry Andric         BB, F);
64350b57cec5SDimitry Andric 
64360b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
64370b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
64380b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
64390b57cec5SDimitry Andric     return;
64400b57cec5SDimitry Andric 
644181ad6265SDimitry Andric   CheckDI(LabelSP == LocSP,
644281ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
64430b57cec5SDimitry Andric               " label and !dbg attachment",
64440b57cec5SDimitry Andric           &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
64450b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
64460b57cec5SDimitry Andric }
64470b57cec5SDimitry Andric 
64480b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
64490b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
64500b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
64510b57cec5SDimitry Andric 
64520b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
64530b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
64540b57cec5SDimitry Andric     return;
64550b57cec5SDimitry Andric 
64560b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
64570b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
64580b57cec5SDimitry Andric   if (!Fragment)
64590b57cec5SDimitry Andric     return;
64600b57cec5SDimitry Andric 
64610b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
64620b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
64630b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
64640b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
64650b57cec5SDimitry Andric   // variable and this check fails.
64660b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
64670b57cec5SDimitry Andric   if (V->isArtificial())
64680b57cec5SDimitry Andric     return;
64690b57cec5SDimitry Andric 
64700b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
64710b57cec5SDimitry Andric }
64720b57cec5SDimitry Andric 
64730b57cec5SDimitry Andric template <typename ValueOrMetadata>
64740b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
64750b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
64760b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
64770b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
64780b57cec5SDimitry Andric   // elsewhere.
64790b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
64800b57cec5SDimitry Andric   if (!VarSize)
64810b57cec5SDimitry Andric     return;
64820b57cec5SDimitry Andric 
64830b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
64840b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
648581ad6265SDimitry Andric   CheckDI(FragSize + FragOffset <= *VarSize,
64860b57cec5SDimitry Andric           "fragment is larger than or outside of variable", Desc, &V);
648781ad6265SDimitry Andric   CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
64880b57cec5SDimitry Andric }
64890b57cec5SDimitry Andric 
64900b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
64910b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
64920b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
64930b57cec5SDimitry Andric   // contain inlined debug intrinsics.
64940b57cec5SDimitry Andric   if (!HasDebugInfo)
64950b57cec5SDimitry Andric     return;
64960b57cec5SDimitry Andric 
64970b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
64980b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
64990b57cec5SDimitry Andric     return;
65000b57cec5SDimitry Andric 
65010b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
650281ad6265SDimitry Andric   CheckDI(Var, "dbg intrinsic without variable");
65030b57cec5SDimitry Andric 
65040b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
65050b57cec5SDimitry Andric   if (!ArgNo)
65060b57cec5SDimitry Andric     return;
65070b57cec5SDimitry Andric 
65080b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
65090b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
65100b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
65110b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
65120b57cec5SDimitry Andric 
65130b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
65140b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
651581ad6265SDimitry Andric   CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
65160b57cec5SDimitry Andric           Prev, Var);
65170b57cec5SDimitry Andric }
65180b57cec5SDimitry Andric 
65198bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
65208bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
65218bcb0991SDimitry Andric 
65228bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
65238bcb0991SDimitry Andric   if (!E || !E->isValid())
65248bcb0991SDimitry Andric     return;
65258bcb0991SDimitry Andric 
65265f757f3fSDimitry Andric   if (isa<ValueAsMetadata>(I.getRawLocation())) {
65275f757f3fSDimitry Andric     Value *VarValue = I.getVariableLocationOp(0);
65285f757f3fSDimitry Andric     if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
65295f757f3fSDimitry Andric       return;
653006c3fb27SDimitry Andric     // We allow EntryValues for swift async arguments, as they have an
653106c3fb27SDimitry Andric     // ABI-guarantee to be turned into a specific register.
65325f757f3fSDimitry Andric     if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
653306c3fb27SDimitry Andric         ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
653406c3fb27SDimitry Andric       return;
65355f757f3fSDimitry Andric   }
653606c3fb27SDimitry Andric 
653706c3fb27SDimitry Andric   CheckDI(!E->isEntryValue(),
653806c3fb27SDimitry Andric           "Entry values are only allowed in MIR unless they target a "
653906c3fb27SDimitry Andric           "swiftasync Argument",
654006c3fb27SDimitry Andric           &I);
65418bcb0991SDimitry Andric }
65428bcb0991SDimitry Andric 
65430b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
65440b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
65450b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
65460b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
65470b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
65480b57cec5SDimitry Andric     return;
65490b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
65500b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
65510b57cec5SDimitry Andric   if (CUs)
65520b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
6553bdd1243dSDimitry Andric   for (const auto *CU : CUVisited)
655481ad6265SDimitry Andric     CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
65550b57cec5SDimitry Andric   CUVisited.clear();
65560b57cec5SDimitry Andric }
65570b57cec5SDimitry Andric 
65580b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
65590b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
65600b57cec5SDimitry Andric     return;
65610b57cec5SDimitry Andric 
65620b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
6563bdd1243dSDimitry Andric   for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
656481ad6265SDimitry Andric     Check(First->getCallingConv() == F->getCallingConv(),
65650b57cec5SDimitry Andric           "All llvm.experimental.deoptimize declarations must have the same "
65660b57cec5SDimitry Andric           "calling convention",
65670b57cec5SDimitry Andric           First, F);
65680b57cec5SDimitry Andric   }
65690b57cec5SDimitry Andric }
65700b57cec5SDimitry Andric 
6571349cc55cSDimitry Andric void Verifier::verifyAttachedCallBundle(const CallBase &Call,
6572349cc55cSDimitry Andric                                         const OperandBundleUse &BU) {
6573349cc55cSDimitry Andric   FunctionType *FTy = Call.getFunctionType();
6574349cc55cSDimitry Andric 
657581ad6265SDimitry Andric   Check((FTy->getReturnType()->isPointerTy() ||
6576349cc55cSDimitry Andric          (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
6577349cc55cSDimitry Andric         "a call with operand bundle \"clang.arc.attachedcall\" must call a "
6578349cc55cSDimitry Andric         "function returning a pointer or a non-returning function that has a "
6579349cc55cSDimitry Andric         "void return type",
6580349cc55cSDimitry Andric         Call);
6581349cc55cSDimitry Andric 
658281ad6265SDimitry Andric   Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
65831fd87a68SDimitry Andric         "operand bundle \"clang.arc.attachedcall\" requires one function as "
65841fd87a68SDimitry Andric         "an argument",
6585349cc55cSDimitry Andric         Call);
6586349cc55cSDimitry Andric 
6587349cc55cSDimitry Andric   auto *Fn = cast<Function>(BU.Inputs.front());
6588349cc55cSDimitry Andric   Intrinsic::ID IID = Fn->getIntrinsicID();
6589349cc55cSDimitry Andric 
6590349cc55cSDimitry Andric   if (IID) {
659181ad6265SDimitry Andric     Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
6592349cc55cSDimitry Andric            IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
6593349cc55cSDimitry Andric           "invalid function argument", Call);
6594349cc55cSDimitry Andric   } else {
6595349cc55cSDimitry Andric     StringRef FnName = Fn->getName();
659681ad6265SDimitry Andric     Check((FnName == "objc_retainAutoreleasedReturnValue" ||
6597349cc55cSDimitry Andric            FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
6598349cc55cSDimitry Andric           "invalid function argument", Call);
6599349cc55cSDimitry Andric   }
6600349cc55cSDimitry Andric }
6601349cc55cSDimitry Andric 
6602e8d8bef9SDimitry Andric void Verifier::verifyNoAliasScopeDecl() {
6603e8d8bef9SDimitry Andric   if (NoAliasScopeDecls.empty())
6604e8d8bef9SDimitry Andric     return;
6605e8d8bef9SDimitry Andric 
6606e8d8bef9SDimitry Andric   // only a single scope must be declared at a time.
6607e8d8bef9SDimitry Andric   for (auto *II : NoAliasScopeDecls) {
6608e8d8bef9SDimitry Andric     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
6609e8d8bef9SDimitry Andric            "Not a llvm.experimental.noalias.scope.decl ?");
6610e8d8bef9SDimitry Andric     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
6611e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
661281ad6265SDimitry Andric     Check(ScopeListMV != nullptr,
6613e8d8bef9SDimitry Andric           "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
6614e8d8bef9SDimitry Andric           "argument",
6615e8d8bef9SDimitry Andric           II);
6616e8d8bef9SDimitry Andric 
6617e8d8bef9SDimitry Andric     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
661881ad6265SDimitry Andric     Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
661981ad6265SDimitry Andric     Check(ScopeListMD->getNumOperands() == 1,
6620e8d8bef9SDimitry Andric           "!id.scope.list must point to a list with a single scope", II);
6621349cc55cSDimitry Andric     visitAliasScopeListMetadata(ScopeListMD);
6622e8d8bef9SDimitry Andric   }
6623e8d8bef9SDimitry Andric 
6624e8d8bef9SDimitry Andric   // Only check the domination rule when requested. Once all passes have been
6625e8d8bef9SDimitry Andric   // adapted this option can go away.
6626e8d8bef9SDimitry Andric   if (!VerifyNoAliasScopeDomination)
6627e8d8bef9SDimitry Andric     return;
6628e8d8bef9SDimitry Andric 
6629e8d8bef9SDimitry Andric   // Now sort the intrinsics based on the scope MDNode so that declarations of
6630e8d8bef9SDimitry Andric   // the same scopes are next to each other.
6631e8d8bef9SDimitry Andric   auto GetScope = [](IntrinsicInst *II) {
6632e8d8bef9SDimitry Andric     const auto *ScopeListMV = cast<MetadataAsValue>(
6633e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
6634e8d8bef9SDimitry Andric     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
6635e8d8bef9SDimitry Andric   };
6636e8d8bef9SDimitry Andric 
6637e8d8bef9SDimitry Andric   // We are sorting on MDNode pointers here. For valid input IR this is ok.
6638e8d8bef9SDimitry Andric   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
6639e8d8bef9SDimitry Andric   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
6640e8d8bef9SDimitry Andric     return GetScope(Lhs) < GetScope(Rhs);
6641e8d8bef9SDimitry Andric   };
6642e8d8bef9SDimitry Andric 
6643e8d8bef9SDimitry Andric   llvm::sort(NoAliasScopeDecls, Compare);
6644e8d8bef9SDimitry Andric 
6645e8d8bef9SDimitry Andric   // Go over the intrinsics and check that for the same scope, they are not
6646e8d8bef9SDimitry Andric   // dominating each other.
6647e8d8bef9SDimitry Andric   auto ItCurrent = NoAliasScopeDecls.begin();
6648e8d8bef9SDimitry Andric   while (ItCurrent != NoAliasScopeDecls.end()) {
6649e8d8bef9SDimitry Andric     auto CurScope = GetScope(*ItCurrent);
6650e8d8bef9SDimitry Andric     auto ItNext = ItCurrent;
6651e8d8bef9SDimitry Andric     do {
6652e8d8bef9SDimitry Andric       ++ItNext;
6653e8d8bef9SDimitry Andric     } while (ItNext != NoAliasScopeDecls.end() &&
6654e8d8bef9SDimitry Andric              GetScope(*ItNext) == CurScope);
6655e8d8bef9SDimitry Andric 
6656e8d8bef9SDimitry Andric     // [ItCurrent, ItNext) represents the declarations for the same scope.
6657e8d8bef9SDimitry Andric     // Ensure they are not dominating each other.. but only if it is not too
6658e8d8bef9SDimitry Andric     // expensive.
6659e8d8bef9SDimitry Andric     if (ItNext - ItCurrent < 32)
6660e8d8bef9SDimitry Andric       for (auto *I : llvm::make_range(ItCurrent, ItNext))
6661e8d8bef9SDimitry Andric         for (auto *J : llvm::make_range(ItCurrent, ItNext))
6662e8d8bef9SDimitry Andric           if (I != J)
666381ad6265SDimitry Andric             Check(!DT.dominates(I, J),
6664e8d8bef9SDimitry Andric                   "llvm.experimental.noalias.scope.decl dominates another one "
6665e8d8bef9SDimitry Andric                   "with the same scope",
6666e8d8bef9SDimitry Andric                   I);
6667e8d8bef9SDimitry Andric     ItCurrent = ItNext;
6668e8d8bef9SDimitry Andric   }
6669e8d8bef9SDimitry Andric }
6670e8d8bef9SDimitry Andric 
66710b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66720b57cec5SDimitry Andric //  Implement the public interfaces to this file...
66730b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66740b57cec5SDimitry Andric 
66750b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
66760b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
66770b57cec5SDimitry Andric 
66780b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
66790b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
66800b57cec5SDimitry Andric 
66810b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
66820b57cec5SDimitry Andric   // expect of a function called "verify".
66830b57cec5SDimitry Andric   return !V.verify(F);
66840b57cec5SDimitry Andric }
66850b57cec5SDimitry Andric 
66860b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
66870b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
66880b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
66890b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
66900b57cec5SDimitry Andric 
66910b57cec5SDimitry Andric   bool Broken = false;
66920b57cec5SDimitry Andric   for (const Function &F : M)
66930b57cec5SDimitry Andric     Broken |= !V.verify(F);
66940b57cec5SDimitry Andric 
66950b57cec5SDimitry Andric   Broken |= !V.verify();
66960b57cec5SDimitry Andric   if (BrokenDebugInfo)
66970b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
66980b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
66990b57cec5SDimitry Andric   // expect of a function called "verify".
67000b57cec5SDimitry Andric   return Broken;
67010b57cec5SDimitry Andric }
67020b57cec5SDimitry Andric 
67030b57cec5SDimitry Andric namespace {
67040b57cec5SDimitry Andric 
67050b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
67060b57cec5SDimitry Andric   static char ID;
67070b57cec5SDimitry Andric 
67080b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
67090b57cec5SDimitry Andric   bool FatalErrors = true;
67100b57cec5SDimitry Andric 
67110b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
67120b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
67130b57cec5SDimitry Andric   }
67140b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
67150b57cec5SDimitry Andric       : FunctionPass(ID),
67160b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
67170b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
67180b57cec5SDimitry Andric   }
67190b57cec5SDimitry Andric 
67200b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
67218bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
67220b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
67230b57cec5SDimitry Andric     return false;
67240b57cec5SDimitry Andric   }
67250b57cec5SDimitry Andric 
67260b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
67270b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
67280b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
67290b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
67300b57cec5SDimitry Andric     }
67310b57cec5SDimitry Andric     return false;
67320b57cec5SDimitry Andric   }
67330b57cec5SDimitry Andric 
67340b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
67350b57cec5SDimitry Andric     bool HasErrors = false;
67360b57cec5SDimitry Andric     for (Function &F : M)
67370b57cec5SDimitry Andric       if (F.isDeclaration())
67380b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
67390b57cec5SDimitry Andric 
67400b57cec5SDimitry Andric     HasErrors |= !V->verify();
67410b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
67420b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
67430b57cec5SDimitry Andric     return false;
67440b57cec5SDimitry Andric   }
67450b57cec5SDimitry Andric 
67460b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
67470b57cec5SDimitry Andric     AU.setPreservesAll();
67480b57cec5SDimitry Andric   }
67490b57cec5SDimitry Andric };
67500b57cec5SDimitry Andric 
67510b57cec5SDimitry Andric } // end anonymous namespace
67520b57cec5SDimitry Andric 
67530b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
67540b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
67550b57cec5SDimitry Andric   if (Diagnostic)
67560b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
67570b57cec5SDimitry Andric }
67580b57cec5SDimitry Andric 
675981ad6265SDimitry Andric #define CheckTBAA(C, ...)                                                      \
67600b57cec5SDimitry Andric   do {                                                                         \
67610b57cec5SDimitry Andric     if (!(C)) {                                                                \
67620b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
67630b57cec5SDimitry Andric       return false;                                                            \
67640b57cec5SDimitry Andric     }                                                                          \
67650b57cec5SDimitry Andric   } while (false)
67660b57cec5SDimitry Andric 
67670b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
67680b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
67690b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
67700b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
67710b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
67720b57cec5SDimitry Andric                                  bool IsNewFormat) {
67730b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
67740b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
67750b57cec5SDimitry Andric     return {true, ~0u};
67760b57cec5SDimitry Andric   }
67770b57cec5SDimitry Andric 
67780b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
67790b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
67800b57cec5SDimitry Andric     return Itr->second;
67810b57cec5SDimitry Andric 
67820b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
67830b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
67840b57cec5SDimitry Andric   (void)InsertResult;
67850b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
67860b57cec5SDimitry Andric   return Result;
67870b57cec5SDimitry Andric }
67880b57cec5SDimitry Andric 
67890b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
67900b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
67910b57cec5SDimitry Andric                                      bool IsNewFormat) {
67920b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
67930b57cec5SDimitry Andric 
67940b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
67950b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
67960b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
67970b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
67980b57cec5SDimitry Andric                : InvalidNode;
67990b57cec5SDimitry Andric   }
68000b57cec5SDimitry Andric 
68010b57cec5SDimitry Andric   if (IsNewFormat) {
68020b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
68030b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
68040b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
68050b57cec5SDimitry Andric       return InvalidNode;
68060b57cec5SDimitry Andric     }
68070b57cec5SDimitry Andric   } else {
68080b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
68090b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
68100b57cec5SDimitry Andric                   BaseNode);
68110b57cec5SDimitry Andric       return InvalidNode;
68120b57cec5SDimitry Andric     }
68130b57cec5SDimitry Andric   }
68140b57cec5SDimitry Andric 
68150b57cec5SDimitry Andric   // Check the type size field.
68160b57cec5SDimitry Andric   if (IsNewFormat) {
68170b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
68180b57cec5SDimitry Andric         BaseNode->getOperand(1));
68190b57cec5SDimitry Andric     if (!TypeSizeNode) {
68200b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
68210b57cec5SDimitry Andric       return InvalidNode;
68220b57cec5SDimitry Andric     }
68230b57cec5SDimitry Andric   }
68240b57cec5SDimitry Andric 
68250b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
68260b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
68270b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
68280b57cec5SDimitry Andric                 BaseNode);
68290b57cec5SDimitry Andric     return InvalidNode;
68300b57cec5SDimitry Andric   }
68310b57cec5SDimitry Andric 
68320b57cec5SDimitry Andric   bool Failed = false;
68330b57cec5SDimitry Andric 
6834bdd1243dSDimitry Andric   std::optional<APInt> PrevOffset;
68350b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
68360b57cec5SDimitry Andric 
68370b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
68380b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
68390b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
68400b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
68410b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
68420b57cec5SDimitry Andric            Idx += NumOpsPerField) {
68430b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
68440b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
68450b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
68460b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
68470b57cec5SDimitry Andric       Failed = true;
68480b57cec5SDimitry Andric       continue;
68490b57cec5SDimitry Andric     }
68500b57cec5SDimitry Andric 
68510b57cec5SDimitry Andric     auto *OffsetEntryCI =
68520b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
68530b57cec5SDimitry Andric     if (!OffsetEntryCI) {
68540b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
68550b57cec5SDimitry Andric       Failed = true;
68560b57cec5SDimitry Andric       continue;
68570b57cec5SDimitry Andric     }
68580b57cec5SDimitry Andric 
68590b57cec5SDimitry Andric     if (BitWidth == ~0u)
68600b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
68610b57cec5SDimitry Andric 
68620b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
68630b57cec5SDimitry Andric       CheckFailed(
68640b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
68650b57cec5SDimitry Andric           BaseNode);
68660b57cec5SDimitry Andric       Failed = true;
68670b57cec5SDimitry Andric       continue;
68680b57cec5SDimitry Andric     }
68690b57cec5SDimitry Andric 
68700b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
68710b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
68720b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
68730b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
68740b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
68750b57cec5SDimitry Andric     bool IsAscending =
68760b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
68770b57cec5SDimitry Andric 
68780b57cec5SDimitry Andric     if (!IsAscending) {
68790b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
68800b57cec5SDimitry Andric       Failed = true;
68810b57cec5SDimitry Andric     }
68820b57cec5SDimitry Andric 
68830b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
68840b57cec5SDimitry Andric 
68850b57cec5SDimitry Andric     if (IsNewFormat) {
68860b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
68870b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
68880b57cec5SDimitry Andric       if (!MemberSizeNode) {
68890b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
68900b57cec5SDimitry Andric         Failed = true;
68910b57cec5SDimitry Andric         continue;
68920b57cec5SDimitry Andric       }
68930b57cec5SDimitry Andric     }
68940b57cec5SDimitry Andric   }
68950b57cec5SDimitry Andric 
68960b57cec5SDimitry Andric   return Failed ? InvalidNode
68970b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
68980b57cec5SDimitry Andric }
68990b57cec5SDimitry Andric 
69000b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
69010b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
69020b57cec5SDimitry Andric }
69030b57cec5SDimitry Andric 
69040b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
69050b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
69060b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
69070b57cec5SDimitry Andric     return false;
69080b57cec5SDimitry Andric 
69090b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
69100b57cec5SDimitry Andric     return false;
69110b57cec5SDimitry Andric 
69120b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
69130b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
69140b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
69150b57cec5SDimitry Andric       return false;
69160b57cec5SDimitry Andric   }
69170b57cec5SDimitry Andric 
69180b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
69190b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
69200b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
69210b57cec5SDimitry Andric }
69220b57cec5SDimitry Andric 
69230b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
69240b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
69250b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
69260b57cec5SDimitry Andric     return ResultIt->second;
69270b57cec5SDimitry Andric 
69280b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
69290b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
69300b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
69310b57cec5SDimitry Andric   (void)InsertResult;
69320b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
69330b57cec5SDimitry Andric 
69340b57cec5SDimitry Andric   return Result;
69350b57cec5SDimitry Andric }
69360b57cec5SDimitry Andric 
69370b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
69380b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
69390b57cec5SDimitry Andric ///
69400b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
69410b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
69420b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
69430b57cec5SDimitry Andric                                                    APInt &Offset,
69440b57cec5SDimitry Andric                                                    bool IsNewFormat) {
69450b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
69460b57cec5SDimitry Andric 
69470b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
69480b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
694981ad6265SDimitry Andric   // to check that.
69500b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
69510b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
69520b57cec5SDimitry Andric 
69530b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
69540b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
69550b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
69560b57cec5SDimitry Andric            Idx += NumOpsPerField) {
69570b57cec5SDimitry Andric     auto *OffsetEntryCI =
69580b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
69590b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
69600b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
69610b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
69620b57cec5SDimitry Andric                     BaseNode, &Offset);
69630b57cec5SDimitry Andric         return nullptr;
69640b57cec5SDimitry Andric       }
69650b57cec5SDimitry Andric 
69660b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
69670b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
69680b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
69690b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
69700b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
69710b57cec5SDimitry Andric     }
69720b57cec5SDimitry Andric   }
69730b57cec5SDimitry Andric 
69740b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
69750b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
69760b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
69770b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
69780b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
69790b57cec5SDimitry Andric }
69800b57cec5SDimitry Andric 
69810b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
69820b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
69830b57cec5SDimitry Andric     return false;
69840b57cec5SDimitry Andric 
69850b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
69860b57cec5SDimitry Andric   // its first operand.
6987349cc55cSDimitry Andric   return isa_and_nonnull<MDNode>(Type->getOperand(0));
69880b57cec5SDimitry Andric }
69890b57cec5SDimitry Andric 
69900b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
699106c3fb27SDimitry Andric   CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands",
699206c3fb27SDimitry Andric             &I, MD);
699306c3fb27SDimitry Andric 
699481ad6265SDimitry Andric   CheckTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
69950b57cec5SDimitry Andric                 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
69960b57cec5SDimitry Andric                 isa<AtomicCmpXchgInst>(I),
69970b57cec5SDimitry Andric             "This instruction shall not have a TBAA access tag!", &I);
69980b57cec5SDimitry Andric 
69990b57cec5SDimitry Andric   bool IsStructPathTBAA =
70000b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
70010b57cec5SDimitry Andric 
700281ad6265SDimitry Andric   CheckTBAA(IsStructPathTBAA,
700381ad6265SDimitry Andric             "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
700481ad6265SDimitry Andric             &I);
70050b57cec5SDimitry Andric 
70060b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
70070b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
70080b57cec5SDimitry Andric 
70090b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
70100b57cec5SDimitry Andric 
70110b57cec5SDimitry Andric   if (IsNewFormat) {
701281ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
70130b57cec5SDimitry Andric               "Access tag metadata must have either 4 or 5 operands", &I, MD);
70140b57cec5SDimitry Andric   } else {
701581ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() < 5,
70160b57cec5SDimitry Andric               "Struct tag metadata must have either 3 or 4 operands", &I, MD);
70170b57cec5SDimitry Andric   }
70180b57cec5SDimitry Andric 
70190b57cec5SDimitry Andric   // Check the access size field.
70200b57cec5SDimitry Andric   if (IsNewFormat) {
70210b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
70220b57cec5SDimitry Andric         MD->getOperand(3));
702381ad6265SDimitry Andric     CheckTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
70240b57cec5SDimitry Andric   }
70250b57cec5SDimitry Andric 
70260b57cec5SDimitry Andric   // Check the immutability flag.
70270b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
70280b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
70290b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
70300b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
703181ad6265SDimitry Andric     CheckTBAA(IsImmutableCI,
703281ad6265SDimitry Andric               "Immutability tag on struct tag metadata must be a constant", &I,
703381ad6265SDimitry Andric               MD);
703481ad6265SDimitry Andric     CheckTBAA(
70350b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
70360b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
70370b57cec5SDimitry Andric         &I, MD);
70380b57cec5SDimitry Andric   }
70390b57cec5SDimitry Andric 
704081ad6265SDimitry Andric   CheckTBAA(BaseNode && AccessType,
70410b57cec5SDimitry Andric             "Malformed struct tag metadata: base and access-type "
70420b57cec5SDimitry Andric             "should be non-null and point to Metadata nodes",
70430b57cec5SDimitry Andric             &I, MD, BaseNode, AccessType);
70440b57cec5SDimitry Andric 
70450b57cec5SDimitry Andric   if (!IsNewFormat) {
704681ad6265SDimitry Andric     CheckTBAA(isValidScalarTBAANode(AccessType),
70470b57cec5SDimitry Andric               "Access type node must be a valid scalar type", &I, MD,
70480b57cec5SDimitry Andric               AccessType);
70490b57cec5SDimitry Andric   }
70500b57cec5SDimitry Andric 
70510b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
705281ad6265SDimitry Andric   CheckTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
70530b57cec5SDimitry Andric 
70540b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
70550b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
70560b57cec5SDimitry Andric 
70570b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
70580b57cec5SDimitry Andric 
70590b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
70600b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
70610b57cec5SDimitry Andric                                                IsNewFormat)) {
70620b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
70630b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
70640b57cec5SDimitry Andric       return false;
70650b57cec5SDimitry Andric     }
70660b57cec5SDimitry Andric 
70670b57cec5SDimitry Andric     bool Invalid;
70680b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
70690b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
70700b57cec5SDimitry Andric                                                              IsNewFormat);
70710b57cec5SDimitry Andric 
70720b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
70730b57cec5SDimitry Andric     // errors we wanted to print.
70740b57cec5SDimitry Andric     if (Invalid)
70750b57cec5SDimitry Andric       return false;
70760b57cec5SDimitry Andric 
70770b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
70780b57cec5SDimitry Andric 
70790b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
708081ad6265SDimitry Andric       CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access",
70810b57cec5SDimitry Andric                 &I, MD, &Offset);
70820b57cec5SDimitry Andric 
708381ad6265SDimitry Andric     CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
70840b57cec5SDimitry Andric                   (BaseNodeBitWidth == 0 && Offset == 0) ||
70850b57cec5SDimitry Andric                   (IsNewFormat && BaseNodeBitWidth == ~0u),
70860b57cec5SDimitry Andric               "Access bit-width not the same as description bit-width", &I, MD,
70870b57cec5SDimitry Andric               BaseNodeBitWidth, Offset.getBitWidth());
70880b57cec5SDimitry Andric 
70890b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
70900b57cec5SDimitry Andric       break;
70910b57cec5SDimitry Andric   }
70920b57cec5SDimitry Andric 
709381ad6265SDimitry Andric   CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", &I,
709481ad6265SDimitry Andric             MD);
70950b57cec5SDimitry Andric   return true;
70960b57cec5SDimitry Andric }
70970b57cec5SDimitry Andric 
70980b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
70990b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
71000b57cec5SDimitry Andric 
71010b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
71020b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
71030b57cec5SDimitry Andric }
71040b57cec5SDimitry Andric 
71050b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
71060b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
71070b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
71080b57cec5SDimitry Andric   Result Res;
71090b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
71100b57cec5SDimitry Andric   return Res;
71110b57cec5SDimitry Andric }
71120b57cec5SDimitry Andric 
71130b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
71140b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
71150b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
71160b57cec5SDimitry Andric }
71170b57cec5SDimitry Andric 
71180b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
71190b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
71200b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
71210b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
71220b57cec5SDimitry Andric 
71230b57cec5SDimitry Andric   return PreservedAnalyses::all();
71240b57cec5SDimitry Andric }
71250b57cec5SDimitry Andric 
71260b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
71270b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
71280b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
71290b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
71300b57cec5SDimitry Andric 
71310b57cec5SDimitry Andric   return PreservedAnalyses::all();
71320b57cec5SDimitry Andric }
7133