xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Verifier.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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"
75*0fca6ea1SDimitry Andric #include "llvm/IR/ConstantRangeList.h"
760b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
775f757f3fSDimitry Andric #include "llvm/IR/ConvergenceVerifier.h"
780b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
79bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
800b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
810b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
820b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
830b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
8406c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
850b57cec5SDimitry Andric #include "llvm/IR/Function.h"
86bdd1243dSDimitry Andric #include "llvm/IR/GCStrategy.h"
870b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
880b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
890b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
900b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
910b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
920b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
930b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
940b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
950b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
960b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
9781ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
9806c3fb27SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
9981ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
100297eecfbSDimitry Andric #include "llvm/IR/IntrinsicsNVPTX.h"
101480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
1020b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
103*0fca6ea1SDimitry Andric #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
1040b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
1050b57cec5SDimitry Andric #include "llvm/IR/Module.h"
1060b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
1070b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
108*0fca6ea1SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
1090b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
1100b57cec5SDimitry Andric #include "llvm/IR/Type.h"
1110b57cec5SDimitry Andric #include "llvm/IR/Use.h"
1120b57cec5SDimitry Andric #include "llvm/IR/User.h"
1137a6dacacSDimitry Andric #include "llvm/IR/VFABIDemangler.h"
1140b57cec5SDimitry Andric #include "llvm/IR/Value.h"
115480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1160b57cec5SDimitry Andric #include "llvm/Pass.h"
1170b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
1180b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1190b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
1200b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1210b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
122*0fca6ea1SDimitry Andric #include "llvm/Support/ModRef.h"
1230b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1240b57cec5SDimitry Andric #include <algorithm>
1250b57cec5SDimitry Andric #include <cassert>
1260b57cec5SDimitry Andric #include <cstdint>
1270b57cec5SDimitry Andric #include <memory>
128bdd1243dSDimitry Andric #include <optional>
1290b57cec5SDimitry Andric #include <string>
1300b57cec5SDimitry Andric #include <utility>
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric using namespace llvm;
1330b57cec5SDimitry Andric 
134e8d8bef9SDimitry Andric static cl::opt<bool> VerifyNoAliasScopeDomination(
135e8d8bef9SDimitry Andric     "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false),
136e8d8bef9SDimitry Andric     cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical "
137e8d8bef9SDimitry Andric              "scopes are not dominating"));
138e8d8bef9SDimitry Andric 
1390b57cec5SDimitry Andric namespace llvm {
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric struct VerifierSupport {
1420b57cec5SDimitry Andric   raw_ostream *OS;
1430b57cec5SDimitry Andric   const Module &M;
1440b57cec5SDimitry Andric   ModuleSlotTracker MST;
1458bcb0991SDimitry Andric   Triple TT;
1460b57cec5SDimitry Andric   const DataLayout &DL;
1470b57cec5SDimitry Andric   LLVMContext &Context;
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   /// Track the brokenness of the module while recursively visiting.
1500b57cec5SDimitry Andric   bool Broken = false;
1510b57cec5SDimitry Andric   /// Broken debug info can be "recovered" from by stripping the debug info.
1520b57cec5SDimitry Andric   bool BrokenDebugInfo = false;
1530b57cec5SDimitry Andric   /// Whether to treat broken debug info as an error.
1540b57cec5SDimitry Andric   bool TreatBrokenDebugInfoAsError = true;
1550b57cec5SDimitry Andric 
VerifierSupportllvm::VerifierSupport1560b57cec5SDimitry Andric   explicit VerifierSupport(raw_ostream *OS, const Module &M)
157*0fca6ea1SDimitry Andric       : OS(OS), M(M), MST(&M), TT(Triple::normalize(M.getTargetTriple())),
158*0fca6ea1SDimitry Andric         DL(M.getDataLayout()), Context(M.getContext()) {}
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric private:
Writellvm::VerifierSupport1610b57cec5SDimitry Andric   void Write(const Module *M) {
1620b57cec5SDimitry Andric     *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1630b57cec5SDimitry Andric   }
1640b57cec5SDimitry Andric 
Writellvm::VerifierSupport1650b57cec5SDimitry Andric   void Write(const Value *V) {
1660b57cec5SDimitry Andric     if (V)
1670b57cec5SDimitry Andric       Write(*V);
1680b57cec5SDimitry Andric   }
1690b57cec5SDimitry Andric 
Writellvm::VerifierSupport1700b57cec5SDimitry Andric   void Write(const Value &V) {
1710b57cec5SDimitry Andric     if (isa<Instruction>(V)) {
1720b57cec5SDimitry Andric       V.print(*OS, MST);
1730b57cec5SDimitry Andric       *OS << '\n';
1740b57cec5SDimitry Andric     } else {
1750b57cec5SDimitry Andric       V.printAsOperand(*OS, true, MST);
1760b57cec5SDimitry Andric       *OS << '\n';
1770b57cec5SDimitry Andric     }
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric 
Writellvm::VerifierSupport180*0fca6ea1SDimitry Andric   void Write(const DbgRecord *DR) {
181*0fca6ea1SDimitry Andric     if (DR) {
182*0fca6ea1SDimitry Andric       DR->print(*OS, MST, false);
183*0fca6ea1SDimitry Andric       *OS << '\n';
184*0fca6ea1SDimitry Andric     }
185*0fca6ea1SDimitry Andric   }
186*0fca6ea1SDimitry Andric 
Writellvm::VerifierSupport187*0fca6ea1SDimitry Andric   void Write(DbgVariableRecord::LocationType Type) {
188*0fca6ea1SDimitry Andric     switch (Type) {
189*0fca6ea1SDimitry Andric     case DbgVariableRecord::LocationType::Value:
190*0fca6ea1SDimitry Andric       *OS << "value";
191*0fca6ea1SDimitry Andric       break;
192*0fca6ea1SDimitry Andric     case DbgVariableRecord::LocationType::Declare:
193*0fca6ea1SDimitry Andric       *OS << "declare";
194*0fca6ea1SDimitry Andric       break;
195*0fca6ea1SDimitry Andric     case DbgVariableRecord::LocationType::Assign:
196*0fca6ea1SDimitry Andric       *OS << "assign";
197*0fca6ea1SDimitry Andric       break;
198*0fca6ea1SDimitry Andric     case DbgVariableRecord::LocationType::End:
199*0fca6ea1SDimitry Andric       *OS << "end";
200*0fca6ea1SDimitry Andric       break;
201*0fca6ea1SDimitry Andric     case DbgVariableRecord::LocationType::Any:
202*0fca6ea1SDimitry Andric       *OS << "any";
203*0fca6ea1SDimitry Andric       break;
204*0fca6ea1SDimitry Andric     };
2057a6dacacSDimitry Andric   }
2067a6dacacSDimitry Andric 
Writellvm::VerifierSupport2070b57cec5SDimitry Andric   void Write(const Metadata *MD) {
2080b57cec5SDimitry Andric     if (!MD)
2090b57cec5SDimitry Andric       return;
2100b57cec5SDimitry Andric     MD->print(*OS, MST, &M);
2110b57cec5SDimitry Andric     *OS << '\n';
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric 
Writellvm::VerifierSupport2140b57cec5SDimitry Andric   template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
2150b57cec5SDimitry Andric     Write(MD.get());
2160b57cec5SDimitry Andric   }
2170b57cec5SDimitry Andric 
Writellvm::VerifierSupport2180b57cec5SDimitry Andric   void Write(const NamedMDNode *NMD) {
2190b57cec5SDimitry Andric     if (!NMD)
2200b57cec5SDimitry Andric       return;
2210b57cec5SDimitry Andric     NMD->print(*OS, MST);
2220b57cec5SDimitry Andric     *OS << '\n';
2230b57cec5SDimitry Andric   }
2240b57cec5SDimitry Andric 
Writellvm::VerifierSupport2250b57cec5SDimitry Andric   void Write(Type *T) {
2260b57cec5SDimitry Andric     if (!T)
2270b57cec5SDimitry Andric       return;
2280b57cec5SDimitry Andric     *OS << ' ' << *T;
2290b57cec5SDimitry Andric   }
2300b57cec5SDimitry Andric 
Writellvm::VerifierSupport2310b57cec5SDimitry Andric   void Write(const Comdat *C) {
2320b57cec5SDimitry Andric     if (!C)
2330b57cec5SDimitry Andric       return;
2340b57cec5SDimitry Andric     *OS << *C;
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
Writellvm::VerifierSupport2370b57cec5SDimitry Andric   void Write(const APInt *AI) {
2380b57cec5SDimitry Andric     if (!AI)
2390b57cec5SDimitry Andric       return;
2400b57cec5SDimitry Andric     *OS << *AI << '\n';
2410b57cec5SDimitry Andric   }
2420b57cec5SDimitry Andric 
Writellvm::VerifierSupport2430b57cec5SDimitry Andric   void Write(const unsigned i) { *OS << i << '\n'; }
2440b57cec5SDimitry Andric 
245fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
Writellvm::VerifierSupport246fe6060f1SDimitry Andric   void Write(const Attribute *A) {
247fe6060f1SDimitry Andric     if (!A)
248fe6060f1SDimitry Andric       return;
249fe6060f1SDimitry Andric     *OS << A->getAsString() << '\n';
250fe6060f1SDimitry Andric   }
251fe6060f1SDimitry Andric 
252fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
Writellvm::VerifierSupport253fe6060f1SDimitry Andric   void Write(const AttributeSet *AS) {
254fe6060f1SDimitry Andric     if (!AS)
255fe6060f1SDimitry Andric       return;
256fe6060f1SDimitry Andric     *OS << AS->getAsString() << '\n';
257fe6060f1SDimitry Andric   }
258fe6060f1SDimitry Andric 
259fe6060f1SDimitry Andric   // NOLINTNEXTLINE(readability-identifier-naming)
Writellvm::VerifierSupport260fe6060f1SDimitry Andric   void Write(const AttributeList *AL) {
261fe6060f1SDimitry Andric     if (!AL)
262fe6060f1SDimitry Andric       return;
263fe6060f1SDimitry Andric     AL->print(*OS);
264fe6060f1SDimitry Andric   }
265fe6060f1SDimitry Andric 
Writellvm::VerifierSupport26606c3fb27SDimitry Andric   void Write(Printable P) { *OS << P << '\n'; }
26706c3fb27SDimitry Andric 
Writellvm::VerifierSupport2680b57cec5SDimitry Andric   template <typename T> void Write(ArrayRef<T> Vs) {
2690b57cec5SDimitry Andric     for (const T &V : Vs)
2700b57cec5SDimitry Andric       Write(V);
2710b57cec5SDimitry Andric   }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   template <typename T1, typename... Ts>
WriteTsllvm::VerifierSupport2740b57cec5SDimitry Andric   void WriteTs(const T1 &V1, const Ts &... Vs) {
2750b57cec5SDimitry Andric     Write(V1);
2760b57cec5SDimitry Andric     WriteTs(Vs...);
2770b57cec5SDimitry Andric   }
2780b57cec5SDimitry Andric 
WriteTsllvm::VerifierSupport2790b57cec5SDimitry Andric   template <typename... Ts> void WriteTs() {}
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric public:
2820b57cec5SDimitry Andric   /// A check failed, so printout out the condition and the message.
2830b57cec5SDimitry Andric   ///
2840b57cec5SDimitry Andric   /// This provides a nice place to put a breakpoint if you want to see why
2850b57cec5SDimitry Andric   /// something is not correct.
CheckFailedllvm::VerifierSupport2860b57cec5SDimitry Andric   void CheckFailed(const Twine &Message) {
2870b57cec5SDimitry Andric     if (OS)
2880b57cec5SDimitry Andric       *OS << Message << '\n';
2890b57cec5SDimitry Andric     Broken = true;
2900b57cec5SDimitry Andric   }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   /// A check failed (with values to print).
2930b57cec5SDimitry Andric   ///
2940b57cec5SDimitry Andric   /// This calls the Message-only version so that the above is easier to set a
2950b57cec5SDimitry Andric   /// breakpoint on.
2960b57cec5SDimitry Andric   template <typename T1, typename... Ts>
CheckFailedllvm::VerifierSupport2970b57cec5SDimitry Andric   void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
2980b57cec5SDimitry Andric     CheckFailed(Message);
2990b57cec5SDimitry Andric     if (OS)
3000b57cec5SDimitry Andric       WriteTs(V1, Vs...);
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   /// A debug info check failed.
DebugInfoCheckFailedllvm::VerifierSupport3040b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message) {
3050b57cec5SDimitry Andric     if (OS)
3060b57cec5SDimitry Andric       *OS << Message << '\n';
3070b57cec5SDimitry Andric     Broken |= TreatBrokenDebugInfoAsError;
3080b57cec5SDimitry Andric     BrokenDebugInfo = true;
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   /// A debug info check failed (with values to print).
3120b57cec5SDimitry Andric   template <typename T1, typename... Ts>
DebugInfoCheckFailedllvm::VerifierSupport3130b57cec5SDimitry Andric   void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
3140b57cec5SDimitry Andric                             const Ts &... Vs) {
3150b57cec5SDimitry Andric     DebugInfoCheckFailed(Message);
3160b57cec5SDimitry Andric     if (OS)
3170b57cec5SDimitry Andric       WriteTs(V1, Vs...);
3180b57cec5SDimitry Andric   }
3190b57cec5SDimitry Andric };
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric } // namespace llvm
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric namespace {
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric class Verifier : public InstVisitor<Verifier>, VerifierSupport {
3260b57cec5SDimitry Andric   friend class InstVisitor<Verifier>;
3270b57cec5SDimitry Andric   DominatorTree DT;
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   /// When verifying a basic block, keep track of all of the
3300b57cec5SDimitry Andric   /// instructions we have seen so far.
3310b57cec5SDimitry Andric   ///
3320b57cec5SDimitry Andric   /// This allows us to do efficient dominance checks for the case when an
3330b57cec5SDimitry Andric   /// instruction has an operand that is an instruction in the same block.
3340b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 16> InstsInThisBlock;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   /// Keep track of the metadata nodes that have been checked already.
3370b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> MDNodes;
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   /// Keep track which DISubprogram is attached to which function.
3400b57cec5SDimitry Andric   DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   /// Track all DICompileUnits visited.
3430b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> CUVisited;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   /// The result type for a landingpad.
3460b57cec5SDimitry Andric   Type *LandingPadResultTy;
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   /// Whether we've seen a call to @llvm.localescape in this function
3490b57cec5SDimitry Andric   /// already.
3500b57cec5SDimitry Andric   bool SawFrameEscape;
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   /// Whether the current function has a DISubprogram attached to it.
3530b57cec5SDimitry Andric   bool HasDebugInfo = false;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   /// Stores the count of how many objects were passed to llvm.localescape for a
3560b57cec5SDimitry Andric   /// given function and the largest index passed to llvm.localrecover.
3570b57cec5SDimitry Andric   DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   // Maps catchswitches and cleanuppads that unwind to siblings to the
3600b57cec5SDimitry Andric   // terminators that indicate the unwind, used to detect cycles therein.
3610b57cec5SDimitry Andric   MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
3620b57cec5SDimitry Andric 
36306c3fb27SDimitry Andric   /// Cache which blocks are in which funclet, if an EH funclet personality is
36406c3fb27SDimitry Andric   /// in use. Otherwise empty.
36506c3fb27SDimitry Andric   DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
36606c3fb27SDimitry Andric 
3670b57cec5SDimitry Andric   /// Cache of constants visited in search of ConstantExprs.
3680b57cec5SDimitry Andric   SmallPtrSet<const Constant *, 32> ConstantExprVisited;
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
3710b57cec5SDimitry Andric   SmallVector<const Function *, 4> DeoptimizeDeclarations;
3720b57cec5SDimitry Andric 
373fe6060f1SDimitry Andric   /// Cache of attribute lists verified.
374fe6060f1SDimitry Andric   SmallPtrSet<const void *, 32> AttributeListsVisited;
375fe6060f1SDimitry Andric 
3760b57cec5SDimitry Andric   // Verify that this GlobalValue is only used in this module.
3770b57cec5SDimitry Andric   // This map is used to avoid visiting uses twice. We can arrive at a user
3780b57cec5SDimitry Andric   // twice, if they have multiple operands. In particular for very large
3790b57cec5SDimitry Andric   // constant expressions, we can arrive at a particular user many times.
3800b57cec5SDimitry Andric   SmallPtrSet<const Value *, 32> GlobalValueVisited;
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   // Keeps track of duplicate function argument debug info.
3830b57cec5SDimitry Andric   SmallVector<const DILocalVariable *, 16> DebugFnArgs;
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
3865f757f3fSDimitry Andric   ConvergenceVerifier ConvergenceVerifyHelper;
3870b57cec5SDimitry Andric 
388e8d8bef9SDimitry Andric   SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
389e8d8bef9SDimitry Andric 
3900b57cec5SDimitry Andric   void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric public:
Verifier(raw_ostream * OS,bool ShouldTreatBrokenDebugInfoAsError,const Module & M)3930b57cec5SDimitry Andric   explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
3940b57cec5SDimitry Andric                     const Module &M)
3950b57cec5SDimitry Andric       : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
3960b57cec5SDimitry Andric         SawFrameEscape(false), TBAAVerifyHelper(this) {
3970b57cec5SDimitry Andric     TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
3980b57cec5SDimitry Andric   }
3990b57cec5SDimitry Andric 
hasBrokenDebugInfo() const4000b57cec5SDimitry Andric   bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
4010b57cec5SDimitry Andric 
verify(const Function & F)4020b57cec5SDimitry Andric   bool verify(const Function &F) {
4030b57cec5SDimitry Andric     assert(F.getParent() == &M &&
4040b57cec5SDimitry Andric            "An instance of this class only works with a specific module!");
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     // First ensure the function is well-enough formed to compute dominance
4070b57cec5SDimitry Andric     // information, and directly compute a dominance tree. We don't rely on the
4080b57cec5SDimitry Andric     // pass manager to provide this as it isolates us from a potentially
4090b57cec5SDimitry Andric     // out-of-date dominator tree and makes it significantly more complex to run
4100b57cec5SDimitry Andric     // this code outside of a pass manager.
4110b57cec5SDimitry Andric     // FIXME: It's really gross that we have to cast away constness here.
4120b57cec5SDimitry Andric     if (!F.empty())
4130b57cec5SDimitry Andric       DT.recalculate(const_cast<Function &>(F));
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric     for (const BasicBlock &BB : F) {
4160b57cec5SDimitry Andric       if (!BB.empty() && BB.back().isTerminator())
4170b57cec5SDimitry Andric         continue;
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric       if (OS) {
4200b57cec5SDimitry Andric         *OS << "Basic Block in function '" << F.getName()
4210b57cec5SDimitry Andric             << "' does not have terminator!\n";
4220b57cec5SDimitry Andric         BB.printAsOperand(*OS, true, MST);
4230b57cec5SDimitry Andric         *OS << "\n";
4240b57cec5SDimitry Andric       }
4250b57cec5SDimitry Andric       return false;
4260b57cec5SDimitry Andric     }
4270b57cec5SDimitry Andric 
4285f757f3fSDimitry Andric     auto FailureCB = [this](const Twine &Message) {
4295f757f3fSDimitry Andric       this->CheckFailed(Message);
4305f757f3fSDimitry Andric     };
4315f757f3fSDimitry Andric     ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
4325f757f3fSDimitry Andric 
4330b57cec5SDimitry Andric     Broken = false;
4340b57cec5SDimitry Andric     // FIXME: We strip const here because the inst visitor strips const.
4350b57cec5SDimitry Andric     visit(const_cast<Function &>(F));
4360b57cec5SDimitry Andric     verifySiblingFuncletUnwinds();
4375f757f3fSDimitry Andric 
4385f757f3fSDimitry Andric     if (ConvergenceVerifyHelper.sawTokens())
4395f757f3fSDimitry Andric       ConvergenceVerifyHelper.verify(DT);
4405f757f3fSDimitry Andric 
4410b57cec5SDimitry Andric     InstsInThisBlock.clear();
4420b57cec5SDimitry Andric     DebugFnArgs.clear();
4430b57cec5SDimitry Andric     LandingPadResultTy = nullptr;
4440b57cec5SDimitry Andric     SawFrameEscape = false;
4450b57cec5SDimitry Andric     SiblingFuncletInfo.clear();
446e8d8bef9SDimitry Andric     verifyNoAliasScopeDecl();
447e8d8bef9SDimitry Andric     NoAliasScopeDecls.clear();
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric     return !Broken;
4500b57cec5SDimitry Andric   }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   /// Verify the module that this instance of \c Verifier was initialized with.
verify()4530b57cec5SDimitry Andric   bool verify() {
4540b57cec5SDimitry Andric     Broken = false;
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric     // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
4570b57cec5SDimitry Andric     for (const Function &F : M)
4580b57cec5SDimitry Andric       if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
4590b57cec5SDimitry Andric         DeoptimizeDeclarations.push_back(&F);
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric     // Now that we've visited every function, verify that we never asked to
4620b57cec5SDimitry Andric     // recover a frame index that wasn't escaped.
4630b57cec5SDimitry Andric     verifyFrameRecoverIndices();
4640b57cec5SDimitry Andric     for (const GlobalVariable &GV : M.globals())
4650b57cec5SDimitry Andric       visitGlobalVariable(GV);
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric     for (const GlobalAlias &GA : M.aliases())
4680b57cec5SDimitry Andric       visitGlobalAlias(GA);
4690b57cec5SDimitry Andric 
470349cc55cSDimitry Andric     for (const GlobalIFunc &GI : M.ifuncs())
471349cc55cSDimitry Andric       visitGlobalIFunc(GI);
472349cc55cSDimitry Andric 
4730b57cec5SDimitry Andric     for (const NamedMDNode &NMD : M.named_metadata())
4740b57cec5SDimitry Andric       visitNamedMDNode(NMD);
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric     for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
4770b57cec5SDimitry Andric       visitComdat(SMEC.getValue());
4780b57cec5SDimitry Andric 
479349cc55cSDimitry Andric     visitModuleFlags();
480349cc55cSDimitry Andric     visitModuleIdents();
481349cc55cSDimitry Andric     visitModuleCommandLines();
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric     verifyCompileUnits();
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric     verifyDeoptimizeCallingConvs();
4860b57cec5SDimitry Andric     DISubprogramAttachments.clear();
4870b57cec5SDimitry Andric     return !Broken;
4880b57cec5SDimitry Andric   }
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric private:
4915ffd83dbSDimitry Andric   /// Whether a metadata node is allowed to be, or contain, a DILocation.
4925ffd83dbSDimitry Andric   enum class AreDebugLocsAllowed { No, Yes };
4935ffd83dbSDimitry Andric 
4940b57cec5SDimitry Andric   // Verification methods...
4950b57cec5SDimitry Andric   void visitGlobalValue(const GlobalValue &GV);
4960b57cec5SDimitry Andric   void visitGlobalVariable(const GlobalVariable &GV);
4970b57cec5SDimitry Andric   void visitGlobalAlias(const GlobalAlias &GA);
498349cc55cSDimitry Andric   void visitGlobalIFunc(const GlobalIFunc &GI);
4990b57cec5SDimitry Andric   void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
5000b57cec5SDimitry Andric   void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
5010b57cec5SDimitry Andric                            const GlobalAlias &A, const Constant &C);
5020b57cec5SDimitry Andric   void visitNamedMDNode(const NamedMDNode &NMD);
5035ffd83dbSDimitry Andric   void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
5040b57cec5SDimitry Andric   void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
5050b57cec5SDimitry Andric   void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
5065f757f3fSDimitry Andric   void visitDIArgList(const DIArgList &AL, Function *F);
5070b57cec5SDimitry Andric   void visitComdat(const Comdat &C);
508349cc55cSDimitry Andric   void visitModuleIdents();
509349cc55cSDimitry Andric   void visitModuleCommandLines();
510349cc55cSDimitry Andric   void visitModuleFlags();
5110b57cec5SDimitry Andric   void visitModuleFlag(const MDNode *Op,
5120b57cec5SDimitry Andric                        DenseMap<const MDString *, const MDNode *> &SeenIDs,
5130b57cec5SDimitry Andric                        SmallVectorImpl<const MDNode *> &Requirements);
5140b57cec5SDimitry Andric   void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
5150b57cec5SDimitry Andric   void visitFunction(const Function &F);
5160b57cec5SDimitry Andric   void visitBasicBlock(BasicBlock &BB);
51706c3fb27SDimitry Andric   void verifyRangeMetadata(const Value &V, const MDNode *Range, Type *Ty,
51806c3fb27SDimitry Andric                            bool IsAbsoluteSymbol);
5190b57cec5SDimitry Andric   void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
5200b57cec5SDimitry Andric   void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
5218bcb0991SDimitry Andric   void visitProfMetadata(Instruction &I, MDNode *MD);
522fcaf7f86SDimitry Andric   void visitCallStackMetadata(MDNode *MD);
523fcaf7f86SDimitry Andric   void visitMemProfMetadata(Instruction &I, MDNode *MD);
524fcaf7f86SDimitry Andric   void visitCallsiteMetadata(Instruction &I, MDNode *MD);
525bdd1243dSDimitry Andric   void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
526*0fca6ea1SDimitry Andric   void visitMMRAMetadata(Instruction &I, MDNode *MD);
527e8d8bef9SDimitry Andric   void visitAnnotationMetadata(MDNode *Annotation);
528349cc55cSDimitry Andric   void visitAliasScopeMetadata(const MDNode *MD);
529349cc55cSDimitry Andric   void visitAliasScopeListMetadata(const MDNode *MD);
53081ad6265SDimitry Andric   void visitAccessGroupMetadata(const MDNode *MD);
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric   template <class Ty> bool isValidMetadataArray(const MDTuple &N);
5330b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
5340b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
5350b57cec5SDimitry Andric   void visitDIScope(const DIScope &N);
5360b57cec5SDimitry Andric   void visitDIVariable(const DIVariable &N);
5370b57cec5SDimitry Andric   void visitDILexicalBlockBase(const DILexicalBlockBase &N);
5380b57cec5SDimitry Andric   void visitDITemplateParameter(const DITemplateParameter &N);
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric   void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
5410b57cec5SDimitry Andric 
542*0fca6ea1SDimitry Andric   void visit(DbgLabelRecord &DLR);
543*0fca6ea1SDimitry Andric   void visit(DbgVariableRecord &DVR);
5440b57cec5SDimitry Andric   // InstVisitor overrides...
5450b57cec5SDimitry Andric   using InstVisitor<Verifier>::visit;
546*0fca6ea1SDimitry Andric   void visitDbgRecords(Instruction &I);
5470b57cec5SDimitry Andric   void visit(Instruction &I);
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric   void visitTruncInst(TruncInst &I);
5500b57cec5SDimitry Andric   void visitZExtInst(ZExtInst &I);
5510b57cec5SDimitry Andric   void visitSExtInst(SExtInst &I);
5520b57cec5SDimitry Andric   void visitFPTruncInst(FPTruncInst &I);
5530b57cec5SDimitry Andric   void visitFPExtInst(FPExtInst &I);
5540b57cec5SDimitry Andric   void visitFPToUIInst(FPToUIInst &I);
5550b57cec5SDimitry Andric   void visitFPToSIInst(FPToSIInst &I);
5560b57cec5SDimitry Andric   void visitUIToFPInst(UIToFPInst &I);
5570b57cec5SDimitry Andric   void visitSIToFPInst(SIToFPInst &I);
5580b57cec5SDimitry Andric   void visitIntToPtrInst(IntToPtrInst &I);
5590b57cec5SDimitry Andric   void visitPtrToIntInst(PtrToIntInst &I);
5600b57cec5SDimitry Andric   void visitBitCastInst(BitCastInst &I);
5610b57cec5SDimitry Andric   void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
5620b57cec5SDimitry Andric   void visitPHINode(PHINode &PN);
5630b57cec5SDimitry Andric   void visitCallBase(CallBase &Call);
5640b57cec5SDimitry Andric   void visitUnaryOperator(UnaryOperator &U);
5650b57cec5SDimitry Andric   void visitBinaryOperator(BinaryOperator &B);
5660b57cec5SDimitry Andric   void visitICmpInst(ICmpInst &IC);
5670b57cec5SDimitry Andric   void visitFCmpInst(FCmpInst &FC);
5680b57cec5SDimitry Andric   void visitExtractElementInst(ExtractElementInst &EI);
5690b57cec5SDimitry Andric   void visitInsertElementInst(InsertElementInst &EI);
5700b57cec5SDimitry Andric   void visitShuffleVectorInst(ShuffleVectorInst &EI);
visitVAArgInst(VAArgInst & VAA)5710b57cec5SDimitry Andric   void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
5720b57cec5SDimitry Andric   void visitCallInst(CallInst &CI);
5730b57cec5SDimitry Andric   void visitInvokeInst(InvokeInst &II);
5740b57cec5SDimitry Andric   void visitGetElementPtrInst(GetElementPtrInst &GEP);
5750b57cec5SDimitry Andric   void visitLoadInst(LoadInst &LI);
5760b57cec5SDimitry Andric   void visitStoreInst(StoreInst &SI);
5770b57cec5SDimitry Andric   void verifyDominatesUse(Instruction &I, unsigned i);
5780b57cec5SDimitry Andric   void visitInstruction(Instruction &I);
5790b57cec5SDimitry Andric   void visitTerminator(Instruction &I);
5800b57cec5SDimitry Andric   void visitBranchInst(BranchInst &BI);
5810b57cec5SDimitry Andric   void visitReturnInst(ReturnInst &RI);
5820b57cec5SDimitry Andric   void visitSwitchInst(SwitchInst &SI);
5830b57cec5SDimitry Andric   void visitIndirectBrInst(IndirectBrInst &BI);
5840b57cec5SDimitry Andric   void visitCallBrInst(CallBrInst &CBI);
5850b57cec5SDimitry Andric   void visitSelectInst(SelectInst &SI);
5860b57cec5SDimitry Andric   void visitUserOp1(Instruction &I);
visitUserOp2(Instruction & I)5870b57cec5SDimitry Andric   void visitUserOp2(Instruction &I) { visitUserOp1(I); }
5880b57cec5SDimitry Andric   void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
5890b57cec5SDimitry Andric   void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
59081ad6265SDimitry Andric   void visitVPIntrinsic(VPIntrinsic &VPI);
5910b57cec5SDimitry Andric   void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII);
5920b57cec5SDimitry Andric   void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
5930b57cec5SDimitry Andric   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
5940b57cec5SDimitry Andric   void visitAtomicRMWInst(AtomicRMWInst &RMWI);
5950b57cec5SDimitry Andric   void visitFenceInst(FenceInst &FI);
5960b57cec5SDimitry Andric   void visitAllocaInst(AllocaInst &AI);
5970b57cec5SDimitry Andric   void visitExtractValueInst(ExtractValueInst &EVI);
5980b57cec5SDimitry Andric   void visitInsertValueInst(InsertValueInst &IVI);
5990b57cec5SDimitry Andric   void visitEHPadPredecessors(Instruction &I);
6000b57cec5SDimitry Andric   void visitLandingPadInst(LandingPadInst &LPI);
6010b57cec5SDimitry Andric   void visitResumeInst(ResumeInst &RI);
6020b57cec5SDimitry Andric   void visitCatchPadInst(CatchPadInst &CPI);
6030b57cec5SDimitry Andric   void visitCatchReturnInst(CatchReturnInst &CatchReturn);
6040b57cec5SDimitry Andric   void visitCleanupPadInst(CleanupPadInst &CPI);
6050b57cec5SDimitry Andric   void visitFuncletPadInst(FuncletPadInst &FPI);
6060b57cec5SDimitry Andric   void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
6070b57cec5SDimitry Andric   void visitCleanupReturnInst(CleanupReturnInst &CRI);
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
6100b57cec5SDimitry Andric   void verifySwiftErrorValue(const Value *SwiftErrorVal);
6110eae32dcSDimitry Andric   void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
6120b57cec5SDimitry Andric   void verifyMustTailCall(CallInst &CI);
6130b57cec5SDimitry Andric   bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
614fe6060f1SDimitry Andric   void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
6150b57cec5SDimitry Andric   void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
616fe6060f1SDimitry Andric   void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
617fe6060f1SDimitry Andric                                     const Value *V);
6180b57cec5SDimitry Andric   void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
61904eeddc0SDimitry Andric                            const Value *V, bool IsIntrinsic, bool IsInlineAsm);
6200b57cec5SDimitry Andric   void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   void visitConstantExprsRecursively(const Constant *EntryC);
6230b57cec5SDimitry Andric   void visitConstantExpr(const ConstantExpr *CE);
624*0fca6ea1SDimitry Andric   void visitConstantPtrAuth(const ConstantPtrAuth *CPA);
62504eeddc0SDimitry Andric   void verifyInlineAsmCall(const CallBase &Call);
6260b57cec5SDimitry Andric   void verifyStatepoint(const CallBase &Call);
6270b57cec5SDimitry Andric   void verifyFrameRecoverIndices();
6280b57cec5SDimitry Andric   void verifySiblingFuncletUnwinds();
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric   void verifyFragmentExpression(const DbgVariableIntrinsic &I);
631*0fca6ea1SDimitry Andric   void verifyFragmentExpression(const DbgVariableRecord &I);
6320b57cec5SDimitry Andric   template <typename ValueOrMetadata>
6330b57cec5SDimitry Andric   void verifyFragmentExpression(const DIVariable &V,
6340b57cec5SDimitry Andric                                 DIExpression::FragmentInfo Fragment,
6350b57cec5SDimitry Andric                                 ValueOrMetadata *Desc);
6360b57cec5SDimitry Andric   void verifyFnArgs(const DbgVariableIntrinsic &I);
637*0fca6ea1SDimitry Andric   void verifyFnArgs(const DbgVariableRecord &DVR);
6388bcb0991SDimitry Andric   void verifyNotEntryValue(const DbgVariableIntrinsic &I);
639*0fca6ea1SDimitry Andric   void verifyNotEntryValue(const DbgVariableRecord &I);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   /// Module-level debug info verification...
6420b57cec5SDimitry Andric   void verifyCompileUnits();
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   /// Module-level verification that all @llvm.experimental.deoptimize
6450b57cec5SDimitry Andric   /// declarations share the same calling convention.
6460b57cec5SDimitry Andric   void verifyDeoptimizeCallingConvs();
6470b57cec5SDimitry Andric 
648349cc55cSDimitry Andric   void verifyAttachedCallBundle(const CallBase &Call,
649349cc55cSDimitry Andric                                 const OperandBundleUse &BU);
650349cc55cSDimitry Andric 
651e8d8bef9SDimitry Andric   /// Verify the llvm.experimental.noalias.scope.decl declarations
652e8d8bef9SDimitry Andric   void verifyNoAliasScopeDecl();
6530b57cec5SDimitry Andric };
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric } // end anonymous namespace
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric /// We know that cond should be true, if not print an error message.
65881ad6265SDimitry Andric #define Check(C, ...)                                                          \
65981ad6265SDimitry Andric   do {                                                                         \
66081ad6265SDimitry Andric     if (!(C)) {                                                                \
66181ad6265SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
66281ad6265SDimitry Andric       return;                                                                  \
66381ad6265SDimitry Andric     }                                                                          \
66481ad6265SDimitry Andric   } while (false)
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric /// We know that a debug info condition should be true, if not print
6670b57cec5SDimitry Andric /// an error message.
66881ad6265SDimitry Andric #define CheckDI(C, ...)                                                        \
66981ad6265SDimitry Andric   do {                                                                         \
67081ad6265SDimitry Andric     if (!(C)) {                                                                \
67181ad6265SDimitry Andric       DebugInfoCheckFailed(__VA_ARGS__);                                       \
67281ad6265SDimitry Andric       return;                                                                  \
67381ad6265SDimitry Andric     }                                                                          \
67481ad6265SDimitry Andric   } while (false)
6750b57cec5SDimitry Andric 
visitDbgRecords(Instruction & I)676*0fca6ea1SDimitry Andric void Verifier::visitDbgRecords(Instruction &I) {
677*0fca6ea1SDimitry Andric   if (!I.DebugMarker)
678*0fca6ea1SDimitry Andric     return;
679*0fca6ea1SDimitry Andric   CheckDI(I.DebugMarker->MarkedInstr == &I,
680*0fca6ea1SDimitry Andric           "Instruction has invalid DebugMarker", &I);
681*0fca6ea1SDimitry Andric   CheckDI(!isa<PHINode>(&I) || !I.hasDbgRecords(),
682*0fca6ea1SDimitry Andric           "PHI Node must not have any attached DbgRecords", &I);
683*0fca6ea1SDimitry Andric   for (DbgRecord &DR : I.getDbgRecordRange()) {
684*0fca6ea1SDimitry Andric     CheckDI(DR.getMarker() == I.DebugMarker,
685*0fca6ea1SDimitry Andric             "DbgRecord had invalid DebugMarker", &I, &DR);
686*0fca6ea1SDimitry Andric     if (auto *Loc =
687*0fca6ea1SDimitry Andric             dyn_cast_or_null<DILocation>(DR.getDebugLoc().getAsMDNode()))
688*0fca6ea1SDimitry Andric       visitMDNode(*Loc, AreDebugLocsAllowed::Yes);
689*0fca6ea1SDimitry Andric     if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR)) {
690*0fca6ea1SDimitry Andric       visit(*DVR);
691*0fca6ea1SDimitry Andric       // These have to appear after `visit` for consistency with existing
692*0fca6ea1SDimitry Andric       // intrinsic behaviour.
693*0fca6ea1SDimitry Andric       verifyFragmentExpression(*DVR);
694*0fca6ea1SDimitry Andric       verifyNotEntryValue(*DVR);
695*0fca6ea1SDimitry Andric     } else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
696*0fca6ea1SDimitry Andric       visit(*DLR);
697*0fca6ea1SDimitry Andric     }
698*0fca6ea1SDimitry Andric   }
699*0fca6ea1SDimitry Andric }
700*0fca6ea1SDimitry Andric 
visit(Instruction & I)7010b57cec5SDimitry Andric void Verifier::visit(Instruction &I) {
702*0fca6ea1SDimitry Andric   visitDbgRecords(I);
7030b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
70481ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Operand is null", &I);
7050b57cec5SDimitry Andric   InstVisitor<Verifier>::visit(I);
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
7080eae32dcSDimitry Andric // Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
forEachUser(const Value * User,SmallPtrSet<const Value *,32> & Visited,llvm::function_ref<bool (const Value *)> Callback)7090b57cec5SDimitry Andric static void forEachUser(const Value *User,
7100b57cec5SDimitry Andric                         SmallPtrSet<const Value *, 32> &Visited,
7110b57cec5SDimitry Andric                         llvm::function_ref<bool(const Value *)> Callback) {
7120b57cec5SDimitry Andric   if (!Visited.insert(User).second)
7130b57cec5SDimitry Andric     return;
7140eae32dcSDimitry Andric 
7150eae32dcSDimitry Andric   SmallVector<const Value *> WorkList;
7160eae32dcSDimitry Andric   append_range(WorkList, User->materialized_users());
7170eae32dcSDimitry Andric   while (!WorkList.empty()) {
7180eae32dcSDimitry Andric    const Value *Cur = WorkList.pop_back_val();
7190eae32dcSDimitry Andric     if (!Visited.insert(Cur).second)
7200eae32dcSDimitry Andric       continue;
7210eae32dcSDimitry Andric     if (Callback(Cur))
7220eae32dcSDimitry Andric       append_range(WorkList, Cur->materialized_users());
7230eae32dcSDimitry Andric   }
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
visitGlobalValue(const GlobalValue & GV)7260b57cec5SDimitry Andric void Verifier::visitGlobalValue(const GlobalValue &GV) {
72781ad6265SDimitry Andric   Check(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
7280b57cec5SDimitry Andric         "Global is external, but doesn't have external or weak linkage!", &GV);
7290b57cec5SDimitry Andric 
7300eae32dcSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
7310eae32dcSDimitry Andric 
7320eae32dcSDimitry Andric     if (MaybeAlign A = GO->getAlign()) {
73381ad6265SDimitry Andric       Check(A->value() <= Value::MaximumAlignment,
7345ffd83dbSDimitry Andric             "huge alignment values are unsupported", GO);
7350eae32dcSDimitry Andric     }
73606c3fb27SDimitry Andric 
73706c3fb27SDimitry Andric     if (const MDNode *Associated =
73806c3fb27SDimitry Andric             GO->getMetadata(LLVMContext::MD_associated)) {
73906c3fb27SDimitry Andric       Check(Associated->getNumOperands() == 1,
74006c3fb27SDimitry Andric             "associated metadata must have one operand", &GV, Associated);
74106c3fb27SDimitry Andric       const Metadata *Op = Associated->getOperand(0).get();
74206c3fb27SDimitry Andric       Check(Op, "associated metadata must have a global value", GO, Associated);
74306c3fb27SDimitry Andric 
74406c3fb27SDimitry Andric       const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
74506c3fb27SDimitry Andric       Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
74606c3fb27SDimitry Andric       if (VM) {
74706c3fb27SDimitry Andric         Check(isa<PointerType>(VM->getValue()->getType()),
74806c3fb27SDimitry Andric               "associated value must be pointer typed", GV, Associated);
74906c3fb27SDimitry Andric 
75006c3fb27SDimitry Andric         const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
75106c3fb27SDimitry Andric         Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
75206c3fb27SDimitry Andric               "associated metadata must point to a GlobalObject", GO, Stripped);
75306c3fb27SDimitry Andric         Check(Stripped != GO,
75406c3fb27SDimitry Andric               "global values should not associate to themselves", GO,
75506c3fb27SDimitry Andric               Associated);
7560eae32dcSDimitry Andric       }
75706c3fb27SDimitry Andric     }
75806c3fb27SDimitry Andric 
75906c3fb27SDimitry Andric     // FIXME: Why is getMetadata on GlobalValue protected?
76006c3fb27SDimitry Andric     if (const MDNode *AbsoluteSymbol =
76106c3fb27SDimitry Andric             GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
76206c3fb27SDimitry Andric       verifyRangeMetadata(*GO, AbsoluteSymbol, DL.getIntPtrType(GO->getType()),
76306c3fb27SDimitry Andric                           true);
76406c3fb27SDimitry Andric     }
76506c3fb27SDimitry Andric   }
76606c3fb27SDimitry Andric 
76781ad6265SDimitry Andric   Check(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
7680b57cec5SDimitry Andric         "Only global variables can have appending linkage!", &GV);
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   if (GV.hasAppendingLinkage()) {
7710b57cec5SDimitry Andric     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
77281ad6265SDimitry Andric     Check(GVar && GVar->getValueType()->isArrayTy(),
7730b57cec5SDimitry Andric           "Only global arrays can have appending linkage!", GVar);
7740b57cec5SDimitry Andric   }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   if (GV.isDeclarationForLinker())
77781ad6265SDimitry Andric     Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
7780b57cec5SDimitry Andric 
779bdd1243dSDimitry Andric   if (GV.hasDLLExportStorageClass()) {
780bdd1243dSDimitry Andric     Check(!GV.hasHiddenVisibility(),
781bdd1243dSDimitry Andric           "dllexport GlobalValue must have default or protected visibility",
782bdd1243dSDimitry Andric           &GV);
783bdd1243dSDimitry Andric   }
7840b57cec5SDimitry Andric   if (GV.hasDLLImportStorageClass()) {
785bdd1243dSDimitry Andric     Check(GV.hasDefaultVisibility(),
786bdd1243dSDimitry Andric           "dllimport GlobalValue must have default visibility", &GV);
78781ad6265SDimitry Andric     Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
78881ad6265SDimitry Andric           &GV);
7890b57cec5SDimitry Andric 
79081ad6265SDimitry Andric     Check((GV.isDeclaration() &&
791e8d8bef9SDimitry Andric            (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) ||
7920b57cec5SDimitry Andric               GV.hasAvailableExternallyLinkage(),
7930b57cec5SDimitry Andric           "Global is marked as dllimport, but not external", &GV);
7940b57cec5SDimitry Andric   }
7950b57cec5SDimitry Andric 
7965ffd83dbSDimitry Andric   if (GV.isImplicitDSOLocal())
79781ad6265SDimitry Andric     Check(GV.isDSOLocal(),
7985ffd83dbSDimitry Andric           "GlobalValue with local linkage or non-default "
7995ffd83dbSDimitry Andric           "visibility must be dso_local!",
8000b57cec5SDimitry Andric           &GV);
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
8030b57cec5SDimitry Andric     if (const Instruction *I = dyn_cast<Instruction>(V)) {
8040b57cec5SDimitry Andric       if (!I->getParent() || !I->getParent()->getParent())
8050b57cec5SDimitry Andric         CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
8060b57cec5SDimitry Andric                     I);
8070b57cec5SDimitry Andric       else if (I->getParent()->getParent()->getParent() != &M)
8080b57cec5SDimitry Andric         CheckFailed("Global is referenced in a different module!", &GV, &M, I,
8090b57cec5SDimitry Andric                     I->getParent()->getParent(),
8100b57cec5SDimitry Andric                     I->getParent()->getParent()->getParent());
8110b57cec5SDimitry Andric       return false;
8120b57cec5SDimitry Andric     } else if (const Function *F = dyn_cast<Function>(V)) {
8130b57cec5SDimitry Andric       if (F->getParent() != &M)
8140b57cec5SDimitry Andric         CheckFailed("Global is used by function in a different module", &GV, &M,
8150b57cec5SDimitry Andric                     F, F->getParent());
8160b57cec5SDimitry Andric       return false;
8170b57cec5SDimitry Andric     }
8180b57cec5SDimitry Andric     return true;
8190b57cec5SDimitry Andric   });
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric 
visitGlobalVariable(const GlobalVariable & GV)8220b57cec5SDimitry Andric void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
8230b57cec5SDimitry Andric   if (GV.hasInitializer()) {
82481ad6265SDimitry Andric     Check(GV.getInitializer()->getType() == GV.getValueType(),
8250b57cec5SDimitry Andric           "Global variable initializer type does not match global "
8260b57cec5SDimitry Andric           "variable type!",
8270b57cec5SDimitry Andric           &GV);
8280b57cec5SDimitry Andric     // If the global has common linkage, it must have a zero initializer and
8290b57cec5SDimitry Andric     // cannot be constant.
8300b57cec5SDimitry Andric     if (GV.hasCommonLinkage()) {
83181ad6265SDimitry Andric       Check(GV.getInitializer()->isNullValue(),
8320b57cec5SDimitry Andric             "'common' global must have a zero initializer!", &GV);
83381ad6265SDimitry Andric       Check(!GV.isConstant(), "'common' global may not be marked constant!",
8340b57cec5SDimitry Andric             &GV);
83581ad6265SDimitry Andric       Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
8360b57cec5SDimitry Andric     }
8370b57cec5SDimitry Andric   }
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
8400b57cec5SDimitry Andric                        GV.getName() == "llvm.global_dtors")) {
84181ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
8420b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
84306c3fb27SDimitry Andric     Check(GV.materialized_use_empty(),
84406c3fb27SDimitry Andric           "invalid uses of intrinsic global variable", &GV);
84506c3fb27SDimitry Andric 
8460b57cec5SDimitry Andric     // Don't worry about emitting an error for it not being an array,
8470b57cec5SDimitry Andric     // visitGlobalValue will complain on appending non-array.
8480b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
8490b57cec5SDimitry Andric       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
8500b57cec5SDimitry Andric       PointerType *FuncPtrTy =
8515f757f3fSDimitry Andric           PointerType::get(Context, DL.getProgramAddressSpace());
85281ad6265SDimitry Andric       Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
8530b57cec5SDimitry Andric                 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
8540b57cec5SDimitry Andric                 STy->getTypeAtIndex(1) == FuncPtrTy,
8550b57cec5SDimitry Andric             "wrong type for intrinsic global variable", &GV);
85681ad6265SDimitry Andric       Check(STy->getNumElements() == 3,
8570b57cec5SDimitry Andric             "the third field of the element type is mandatory, "
858bdd1243dSDimitry Andric             "specify ptr null to migrate from the obsoleted 2-field form");
8590b57cec5SDimitry Andric       Type *ETy = STy->getTypeAtIndex(2);
86006c3fb27SDimitry Andric       Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
86106c3fb27SDimitry Andric             &GV);
8620b57cec5SDimitry Andric     }
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   if (GV.hasName() && (GV.getName() == "llvm.used" ||
8660b57cec5SDimitry Andric                        GV.getName() == "llvm.compiler.used")) {
86781ad6265SDimitry Andric     Check(!GV.hasInitializer() || GV.hasAppendingLinkage(),
8680b57cec5SDimitry Andric           "invalid linkage for intrinsic global variable", &GV);
86906c3fb27SDimitry Andric     Check(GV.materialized_use_empty(),
87006c3fb27SDimitry Andric           "invalid uses of intrinsic global variable", &GV);
87106c3fb27SDimitry Andric 
8720b57cec5SDimitry Andric     Type *GVType = GV.getValueType();
8730b57cec5SDimitry Andric     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
8740b57cec5SDimitry Andric       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
87581ad6265SDimitry Andric       Check(PTy, "wrong type for intrinsic global variable", &GV);
8760b57cec5SDimitry Andric       if (GV.hasInitializer()) {
8770b57cec5SDimitry Andric         const Constant *Init = GV.getInitializer();
8780b57cec5SDimitry Andric         const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
87981ad6265SDimitry Andric         Check(InitArray, "wrong initalizer for intrinsic global variable",
8800b57cec5SDimitry Andric               Init);
8810b57cec5SDimitry Andric         for (Value *Op : InitArray->operands()) {
8828bcb0991SDimitry Andric           Value *V = Op->stripPointerCasts();
88381ad6265SDimitry Andric           Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
8840b57cec5SDimitry Andric                     isa<GlobalAlias>(V),
8850eae32dcSDimitry Andric                 Twine("invalid ") + GV.getName() + " member", V);
88681ad6265SDimitry Andric           Check(V->hasName(),
8870eae32dcSDimitry Andric                 Twine("members of ") + GV.getName() + " must be named", V);
8880b57cec5SDimitry Andric         }
8890b57cec5SDimitry Andric       }
8900b57cec5SDimitry Andric     }
8910b57cec5SDimitry Andric   }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // Visit any debug info attachments.
8940b57cec5SDimitry Andric   SmallVector<MDNode *, 1> MDs;
8950b57cec5SDimitry Andric   GV.getMetadata(LLVMContext::MD_dbg, MDs);
8960b57cec5SDimitry Andric   for (auto *MD : MDs) {
8970b57cec5SDimitry Andric     if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
8980b57cec5SDimitry Andric       visitDIGlobalVariableExpression(*GVE);
8990b57cec5SDimitry Andric     else
90081ad6265SDimitry Andric       CheckDI(false, "!dbg attachment of global variable must be a "
9010b57cec5SDimitry Andric                      "DIGlobalVariableExpression");
9020b57cec5SDimitry Andric   }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   // Scalable vectors cannot be global variables, since we don't know
9055f757f3fSDimitry Andric   // the runtime size.
9065f757f3fSDimitry Andric   Check(!GV.getValueType()->isScalableTy(),
9075f757f3fSDimitry Andric         "Globals cannot contain scalable types", &GV);
908e8d8bef9SDimitry Andric 
909bdd1243dSDimitry Andric   // Check if it's a target extension type that disallows being used as a
910bdd1243dSDimitry Andric   // global.
911bdd1243dSDimitry Andric   if (auto *TTy = dyn_cast<TargetExtType>(GV.getValueType()))
912bdd1243dSDimitry Andric     Check(TTy->hasProperty(TargetExtType::CanBeGlobal),
913bdd1243dSDimitry Andric           "Global @" + GV.getName() + " has illegal target extension type",
914bdd1243dSDimitry Andric           TTy);
915bdd1243dSDimitry Andric 
9160b57cec5SDimitry Andric   if (!GV.hasInitializer()) {
9170b57cec5SDimitry Andric     visitGlobalValue(GV);
9180b57cec5SDimitry Andric     return;
9190b57cec5SDimitry Andric   }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric   // Walk any aggregate initializers looking for bitcasts between address spaces
9220b57cec5SDimitry Andric   visitConstantExprsRecursively(GV.getInitializer());
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   visitGlobalValue(GV);
9250b57cec5SDimitry Andric }
9260b57cec5SDimitry Andric 
visitAliaseeSubExpr(const GlobalAlias & GA,const Constant & C)9270b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
9280b57cec5SDimitry Andric   SmallPtrSet<const GlobalAlias*, 4> Visited;
9290b57cec5SDimitry Andric   Visited.insert(&GA);
9300b57cec5SDimitry Andric   visitAliaseeSubExpr(Visited, GA, C);
9310b57cec5SDimitry Andric }
9320b57cec5SDimitry Andric 
visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias * > & Visited,const GlobalAlias & GA,const Constant & C)9330b57cec5SDimitry Andric void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
9340b57cec5SDimitry Andric                                    const GlobalAlias &GA, const Constant &C) {
935bdd1243dSDimitry Andric   if (GA.hasAvailableExternallyLinkage()) {
936bdd1243dSDimitry Andric     Check(isa<GlobalValue>(C) &&
937bdd1243dSDimitry Andric               cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
938bdd1243dSDimitry Andric           "available_externally alias must point to available_externally "
939bdd1243dSDimitry Andric           "global value",
940bdd1243dSDimitry Andric           &GA);
941bdd1243dSDimitry Andric   }
9420b57cec5SDimitry Andric   if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
943bdd1243dSDimitry Andric     if (!GA.hasAvailableExternallyLinkage()) {
94481ad6265SDimitry Andric       Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
9450b57cec5SDimitry Andric             &GA);
946bdd1243dSDimitry Andric     }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
94981ad6265SDimitry Andric       Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
9500b57cec5SDimitry Andric 
95181ad6265SDimitry Andric       Check(!GA2->isInterposable(),
95281ad6265SDimitry Andric             "Alias cannot point to an interposable alias", &GA);
9530b57cec5SDimitry Andric     } else {
9540b57cec5SDimitry Andric       // Only continue verifying subexpressions of GlobalAliases.
9550b57cec5SDimitry Andric       // Do not recurse into global initializers.
9560b57cec5SDimitry Andric       return;
9570b57cec5SDimitry Andric     }
9580b57cec5SDimitry Andric   }
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<ConstantExpr>(&C))
9610b57cec5SDimitry Andric     visitConstantExprsRecursively(CE);
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   for (const Use &U : C.operands()) {
9640b57cec5SDimitry Andric     Value *V = &*U;
9650b57cec5SDimitry Andric     if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
9660b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
9670b57cec5SDimitry Andric     else if (const auto *C2 = dyn_cast<Constant>(V))
9680b57cec5SDimitry Andric       visitAliaseeSubExpr(Visited, GA, *C2);
9690b57cec5SDimitry Andric   }
9700b57cec5SDimitry Andric }
9710b57cec5SDimitry Andric 
visitGlobalAlias(const GlobalAlias & GA)9720b57cec5SDimitry Andric void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
97381ad6265SDimitry Andric   Check(GlobalAlias::isValidLinkage(GA.getLinkage()),
9740b57cec5SDimitry Andric         "Alias should have private, internal, linkonce, weak, linkonce_odr, "
975bdd1243dSDimitry Andric         "weak_odr, external, or available_externally linkage!",
9760b57cec5SDimitry Andric         &GA);
9770b57cec5SDimitry Andric   const Constant *Aliasee = GA.getAliasee();
97881ad6265SDimitry Andric   Check(Aliasee, "Aliasee cannot be NULL!", &GA);
97981ad6265SDimitry Andric   Check(GA.getType() == Aliasee->getType(),
9800b57cec5SDimitry Andric         "Alias and aliasee types should match!", &GA);
9810b57cec5SDimitry Andric 
98281ad6265SDimitry Andric   Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
9830b57cec5SDimitry Andric         "Aliasee should be either GlobalValue or ConstantExpr", &GA);
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   visitAliaseeSubExpr(GA, *Aliasee);
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   visitGlobalValue(GA);
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric 
visitGlobalIFunc(const GlobalIFunc & GI)990349cc55cSDimitry Andric void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
99181ad6265SDimitry Andric   Check(GlobalIFunc::isValidLinkage(GI.getLinkage()),
99281ad6265SDimitry Andric         "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
99381ad6265SDimitry Andric         "weak_odr, or external linkage!",
99481ad6265SDimitry Andric         &GI);
995349cc55cSDimitry Andric   // Pierce through ConstantExprs and GlobalAliases and check that the resolver
99681ad6265SDimitry Andric   // is a Function definition.
997349cc55cSDimitry Andric   const Function *Resolver = GI.getResolverFunction();
99881ad6265SDimitry Andric   Check(Resolver, "IFunc must have a Function resolver", &GI);
99981ad6265SDimitry Andric   Check(!Resolver->isDeclarationForLinker(),
100081ad6265SDimitry Andric         "IFunc resolver must be a definition", &GI);
1001349cc55cSDimitry Andric 
1002349cc55cSDimitry Andric   // Check that the immediate resolver operand (prior to any bitcasts) has the
100381ad6265SDimitry Andric   // correct type.
1004349cc55cSDimitry Andric   const Type *ResolverTy = GI.getResolver()->getType();
1005bdd1243dSDimitry Andric 
1006bdd1243dSDimitry Andric   Check(isa<PointerType>(Resolver->getFunctionType()->getReturnType()),
1007bdd1243dSDimitry Andric         "IFunc resolver must return a pointer", &GI);
1008bdd1243dSDimitry Andric 
1009349cc55cSDimitry Andric   const Type *ResolverFuncTy =
1010349cc55cSDimitry Andric       GlobalIFunc::getResolverFunctionType(GI.getValueType());
1011bdd1243dSDimitry Andric   Check(ResolverTy == ResolverFuncTy->getPointerTo(GI.getAddressSpace()),
1012349cc55cSDimitry Andric         "IFunc resolver has incorrect type", &GI);
1013349cc55cSDimitry Andric }
1014349cc55cSDimitry Andric 
visitNamedMDNode(const NamedMDNode & NMD)10150b57cec5SDimitry Andric void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
10160b57cec5SDimitry Andric   // There used to be various other llvm.dbg.* nodes, but we don't support
10170b57cec5SDimitry Andric   // upgrading them and we want to reserve the namespace for future uses.
10185f757f3fSDimitry Andric   if (NMD.getName().starts_with("llvm.dbg."))
101981ad6265SDimitry Andric     CheckDI(NMD.getName() == "llvm.dbg.cu",
102081ad6265SDimitry Andric             "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
10210b57cec5SDimitry Andric   for (const MDNode *MD : NMD.operands()) {
10220b57cec5SDimitry Andric     if (NMD.getName() == "llvm.dbg.cu")
102381ad6265SDimitry Andric       CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric     if (!MD)
10260b57cec5SDimitry Andric       continue;
10270b57cec5SDimitry Andric 
10285ffd83dbSDimitry Andric     visitMDNode(*MD, AreDebugLocsAllowed::Yes);
10290b57cec5SDimitry Andric   }
10300b57cec5SDimitry Andric }
10310b57cec5SDimitry Andric 
visitMDNode(const MDNode & MD,AreDebugLocsAllowed AllowLocs)10325ffd83dbSDimitry Andric void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
10330b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
10340b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
10350b57cec5SDimitry Andric   if (!MDNodes.insert(&MD).second)
10360b57cec5SDimitry Andric     return;
10370b57cec5SDimitry Andric 
103881ad6265SDimitry Andric   Check(&MD.getContext() == &Context,
1039fe6060f1SDimitry Andric         "MDNode context does not match Module context!", &MD);
1040fe6060f1SDimitry Andric 
10410b57cec5SDimitry Andric   switch (MD.getMetadataID()) {
10420b57cec5SDimitry Andric   default:
10430b57cec5SDimitry Andric     llvm_unreachable("Invalid MDNode subclass");
10440b57cec5SDimitry Andric   case Metadata::MDTupleKind:
10450b57cec5SDimitry Andric     break;
10460b57cec5SDimitry Andric #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
10470b57cec5SDimitry Andric   case Metadata::CLASS##Kind:                                                  \
10480b57cec5SDimitry Andric     visit##CLASS(cast<CLASS>(MD));                                             \
10490b57cec5SDimitry Andric     break;
10500b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
10510b57cec5SDimitry Andric   }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   for (const Metadata *Op : MD.operands()) {
10540b57cec5SDimitry Andric     if (!Op)
10550b57cec5SDimitry Andric       continue;
105681ad6265SDimitry Andric     Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
10570b57cec5SDimitry Andric           &MD, Op);
105881ad6265SDimitry Andric     CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
10595ffd83dbSDimitry Andric             "DILocation not allowed within this metadata node", &MD, Op);
10600b57cec5SDimitry Andric     if (auto *N = dyn_cast<MDNode>(Op)) {
10615ffd83dbSDimitry Andric       visitMDNode(*N, AllowLocs);
10620b57cec5SDimitry Andric       continue;
10630b57cec5SDimitry Andric     }
10640b57cec5SDimitry Andric     if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
10650b57cec5SDimitry Andric       visitValueAsMetadata(*V, nullptr);
10660b57cec5SDimitry Andric       continue;
10670b57cec5SDimitry Andric     }
10680b57cec5SDimitry Andric   }
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   // Check these last, so we diagnose problems in operands first.
107181ad6265SDimitry Andric   Check(!MD.isTemporary(), "Expected no forward declarations!", &MD);
107281ad6265SDimitry Andric   Check(MD.isResolved(), "All nodes should be resolved!", &MD);
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric 
visitValueAsMetadata(const ValueAsMetadata & MD,Function * F)10750b57cec5SDimitry Andric void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
107681ad6265SDimitry Andric   Check(MD.getValue(), "Expected valid value", &MD);
107781ad6265SDimitry Andric   Check(!MD.getValue()->getType()->isMetadataTy(),
10780b57cec5SDimitry Andric         "Unexpected metadata round-trip through values", &MD, MD.getValue());
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   auto *L = dyn_cast<LocalAsMetadata>(&MD);
10810b57cec5SDimitry Andric   if (!L)
10820b57cec5SDimitry Andric     return;
10830b57cec5SDimitry Andric 
108481ad6265SDimitry Andric   Check(F, "function-local metadata used outside a function", L);
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   // If this was an instruction, bb, or argument, verify that it is in the
10870b57cec5SDimitry Andric   // function that we expect.
10880b57cec5SDimitry Andric   Function *ActualF = nullptr;
10890b57cec5SDimitry Andric   if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
109081ad6265SDimitry Andric     Check(I->getParent(), "function-local metadata not in basic block", L, I);
10910b57cec5SDimitry Andric     ActualF = I->getParent()->getParent();
10920b57cec5SDimitry Andric   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
10930b57cec5SDimitry Andric     ActualF = BB->getParent();
10940b57cec5SDimitry Andric   else if (Argument *A = dyn_cast<Argument>(L->getValue()))
10950b57cec5SDimitry Andric     ActualF = A->getParent();
10960b57cec5SDimitry Andric   assert(ActualF && "Unimplemented function local metadata case!");
10970b57cec5SDimitry Andric 
109881ad6265SDimitry Andric   Check(ActualF == F, "function-local metadata used in wrong function", L);
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
visitDIArgList(const DIArgList & AL,Function * F)11015f757f3fSDimitry Andric void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
11025f757f3fSDimitry Andric   for (const ValueAsMetadata *VAM : AL.getArgs())
11035f757f3fSDimitry Andric     visitValueAsMetadata(*VAM, F);
11045f757f3fSDimitry Andric }
11055f757f3fSDimitry Andric 
visitMetadataAsValue(const MetadataAsValue & MDV,Function * F)11060b57cec5SDimitry Andric void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
11070b57cec5SDimitry Andric   Metadata *MD = MDV.getMetadata();
11080b57cec5SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD)) {
11095ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::No);
11100b57cec5SDimitry Andric     return;
11110b57cec5SDimitry Andric   }
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric   // Only visit each node once.  Metadata can be mutually recursive, so this
11140b57cec5SDimitry Andric   // avoids infinite recursion here, as well as being an optimization.
11150b57cec5SDimitry Andric   if (!MDNodes.insert(MD).second)
11160b57cec5SDimitry Andric     return;
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   if (auto *V = dyn_cast<ValueAsMetadata>(MD))
11190b57cec5SDimitry Andric     visitValueAsMetadata(*V, F);
11205f757f3fSDimitry Andric 
11215f757f3fSDimitry Andric   if (auto *AL = dyn_cast<DIArgList>(MD))
11225f757f3fSDimitry Andric     visitDIArgList(*AL, F);
11230b57cec5SDimitry Andric }
11240b57cec5SDimitry Andric 
isType(const Metadata * MD)11250b57cec5SDimitry Andric static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
isScope(const Metadata * MD)11260b57cec5SDimitry Andric static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
isDINode(const Metadata * MD)11270b57cec5SDimitry Andric static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
11280b57cec5SDimitry Andric 
visitDILocation(const DILocation & N)11290b57cec5SDimitry Andric void Verifier::visitDILocation(const DILocation &N) {
113081ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
11310b57cec5SDimitry Andric           "location requires a valid scope", &N, N.getRawScope());
11320b57cec5SDimitry Andric   if (auto *IA = N.getRawInlinedAt())
113381ad6265SDimitry Andric     CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
11340b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
113581ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric 
visitGenericDINode(const GenericDINode & N)11380b57cec5SDimitry Andric void Verifier::visitGenericDINode(const GenericDINode &N) {
113981ad6265SDimitry Andric   CheckDI(N.getTag(), "invalid tag", &N);
11400b57cec5SDimitry Andric }
11410b57cec5SDimitry Andric 
visitDIScope(const DIScope & N)11420b57cec5SDimitry Andric void Verifier::visitDIScope(const DIScope &N) {
11430b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
114481ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric 
visitDISubrange(const DISubrange & N)11470b57cec5SDimitry Andric void Verifier::visitDISubrange(const DISubrange &N) {
114881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
114981ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
11505ffd83dbSDimitry Andric           "Subrange can have any one of count or upperBound", &N);
1151fe6060f1SDimitry Andric   auto *CBound = N.getRawCountNode();
115281ad6265SDimitry Andric   CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1153fe6060f1SDimitry Andric               isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1154fe6060f1SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
11550b57cec5SDimitry Andric   auto Count = N.getCount();
115606c3fb27SDimitry Andric   CheckDI(!Count || !isa<ConstantInt *>(Count) ||
115706c3fb27SDimitry Andric               cast<ConstantInt *>(Count)->getSExtValue() >= -1,
11580b57cec5SDimitry Andric           "invalid subrange count", &N);
11595ffd83dbSDimitry Andric   auto *LBound = N.getRawLowerBound();
116081ad6265SDimitry Andric   CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
11615ffd83dbSDimitry Andric               isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
11625ffd83dbSDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
11635ffd83dbSDimitry Andric           &N);
11645ffd83dbSDimitry Andric   auto *UBound = N.getRawUpperBound();
116581ad6265SDimitry Andric   CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
11665ffd83dbSDimitry Andric               isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
11675ffd83dbSDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
11685ffd83dbSDimitry Andric           &N);
11695ffd83dbSDimitry Andric   auto *Stride = N.getRawStride();
117081ad6265SDimitry Andric   CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
11715ffd83dbSDimitry Andric               isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
11725ffd83dbSDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
11730b57cec5SDimitry Andric }
11740b57cec5SDimitry Andric 
visitDIGenericSubrange(const DIGenericSubrange & N)1175e8d8bef9SDimitry Andric void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
117681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
117781ad6265SDimitry Andric   CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1178e8d8bef9SDimitry Andric           "GenericSubrange can have any one of count or upperBound", &N);
1179e8d8bef9SDimitry Andric   auto *CBound = N.getRawCountNode();
118081ad6265SDimitry Andric   CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1181e8d8bef9SDimitry Andric           "Count must be signed constant or DIVariable or DIExpression", &N);
1182e8d8bef9SDimitry Andric   auto *LBound = N.getRawLowerBound();
118381ad6265SDimitry Andric   CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
118481ad6265SDimitry Andric   CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1185e8d8bef9SDimitry Andric           "LowerBound must be signed constant or DIVariable or DIExpression",
1186e8d8bef9SDimitry Andric           &N);
1187e8d8bef9SDimitry Andric   auto *UBound = N.getRawUpperBound();
118881ad6265SDimitry Andric   CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1189e8d8bef9SDimitry Andric           "UpperBound must be signed constant or DIVariable or DIExpression",
1190e8d8bef9SDimitry Andric           &N);
1191e8d8bef9SDimitry Andric   auto *Stride = N.getRawStride();
119281ad6265SDimitry Andric   CheckDI(Stride, "GenericSubrange must contain stride", &N);
119381ad6265SDimitry Andric   CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1194e8d8bef9SDimitry Andric           "Stride must be signed constant or DIVariable or DIExpression", &N);
1195e8d8bef9SDimitry Andric }
1196e8d8bef9SDimitry Andric 
visitDIEnumerator(const DIEnumerator & N)11970b57cec5SDimitry Andric void Verifier::visitDIEnumerator(const DIEnumerator &N) {
119881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
11990b57cec5SDimitry Andric }
12000b57cec5SDimitry Andric 
visitDIBasicType(const DIBasicType & N)12010b57cec5SDimitry Andric void Verifier::visitDIBasicType(const DIBasicType &N) {
120281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1203e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_unspecified_type ||
1204e8d8bef9SDimitry Andric               N.getTag() == dwarf::DW_TAG_string_type,
12050b57cec5SDimitry Andric           "invalid tag", &N);
1206e8d8bef9SDimitry Andric }
1207e8d8bef9SDimitry Andric 
visitDIStringType(const DIStringType & N)1208e8d8bef9SDimitry Andric void Verifier::visitDIStringType(const DIStringType &N) {
120981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
121081ad6265SDimitry Andric   CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
121181ad6265SDimitry Andric           &N);
12120b57cec5SDimitry Andric }
12130b57cec5SDimitry Andric 
visitDIDerivedType(const DIDerivedType & N)12140b57cec5SDimitry Andric void Verifier::visitDIDerivedType(const DIDerivedType &N) {
12150b57cec5SDimitry Andric   // Common scope checks.
12160b57cec5SDimitry Andric   visitDIScope(N);
12170b57cec5SDimitry Andric 
121881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
12190b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_pointer_type ||
12200b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
12210b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_reference_type ||
12220b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
12230b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_const_type ||
122404eeddc0SDimitry Andric               N.getTag() == dwarf::DW_TAG_immutable_type ||
12250b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_volatile_type ||
12260b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_restrict_type ||
12270b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_atomic_type ||
1228*0fca6ea1SDimitry Andric               N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
12290b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_member ||
12305f757f3fSDimitry Andric               (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
12310b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_inheritance ||
1232fe6060f1SDimitry Andric               N.getTag() == dwarf::DW_TAG_friend ||
1233*0fca6ea1SDimitry Andric               N.getTag() == dwarf::DW_TAG_set_type ||
1234*0fca6ea1SDimitry Andric               N.getTag() == dwarf::DW_TAG_template_alias,
12350b57cec5SDimitry Andric           "invalid tag", &N);
12360b57cec5SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
123781ad6265SDimitry Andric     CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
12380b57cec5SDimitry Andric             N.getRawExtraData());
12390b57cec5SDimitry Andric   }
12400b57cec5SDimitry Andric 
1241fe6060f1SDimitry Andric   if (N.getTag() == dwarf::DW_TAG_set_type) {
1242fe6060f1SDimitry Andric     if (auto *T = N.getRawBaseType()) {
1243fe6060f1SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(T);
1244fe6060f1SDimitry Andric       auto *Basic = dyn_cast_or_null<DIBasicType>(T);
124581ad6265SDimitry Andric       CheckDI(
1246fe6060f1SDimitry Andric           (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1247fe6060f1SDimitry Andric               (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1248fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed ||
1249fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1250fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1251fe6060f1SDimitry Andric                          Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1252fe6060f1SDimitry Andric           "invalid set base type", &N, T);
1253fe6060f1SDimitry Andric     }
1254fe6060f1SDimitry Andric   }
1255fe6060f1SDimitry Andric 
125681ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
125781ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
12580b57cec5SDimitry Andric           N.getRawBaseType());
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric   if (N.getDWARFAddressSpace()) {
126181ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
12620b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_reference_type ||
12630b57cec5SDimitry Andric                 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
12640b57cec5SDimitry Andric             "DWARF address space only applies to pointer or reference types",
12650b57cec5SDimitry Andric             &N);
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric }
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric /// Detect mutually exclusive flags.
hasConflictingReferenceFlags(unsigned Flags)12700b57cec5SDimitry Andric static bool hasConflictingReferenceFlags(unsigned Flags) {
12710b57cec5SDimitry Andric   return ((Flags & DINode::FlagLValueReference) &&
12720b57cec5SDimitry Andric           (Flags & DINode::FlagRValueReference)) ||
12730b57cec5SDimitry Andric          ((Flags & DINode::FlagTypePassByValue) &&
12740b57cec5SDimitry Andric           (Flags & DINode::FlagTypePassByReference));
12750b57cec5SDimitry Andric }
12760b57cec5SDimitry Andric 
visitTemplateParams(const MDNode & N,const Metadata & RawParams)12770b57cec5SDimitry Andric void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
12780b57cec5SDimitry Andric   auto *Params = dyn_cast<MDTuple>(&RawParams);
127981ad6265SDimitry Andric   CheckDI(Params, "invalid template params", &N, &RawParams);
12800b57cec5SDimitry Andric   for (Metadata *Op : Params->operands()) {
128181ad6265SDimitry Andric     CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
12820b57cec5SDimitry Andric             &N, Params, Op);
12830b57cec5SDimitry Andric   }
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric 
visitDICompositeType(const DICompositeType & N)12860b57cec5SDimitry Andric void Verifier::visitDICompositeType(const DICompositeType &N) {
12870b57cec5SDimitry Andric   // Common scope checks.
12880b57cec5SDimitry Andric   visitDIScope(N);
12890b57cec5SDimitry Andric 
129081ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
12910b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_structure_type ||
12920b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_union_type ||
12930b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_enumeration_type ||
12940b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_class_type ||
1295349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_variant_part ||
1296349cc55cSDimitry Andric               N.getTag() == dwarf::DW_TAG_namelist,
12970b57cec5SDimitry Andric           "invalid tag", &N);
12980b57cec5SDimitry Andric 
129981ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
130081ad6265SDimitry Andric   CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
13010b57cec5SDimitry Andric           N.getRawBaseType());
13020b57cec5SDimitry Andric 
130381ad6265SDimitry Andric   CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
13040b57cec5SDimitry Andric           "invalid composite elements", &N, N.getRawElements());
130581ad6265SDimitry Andric   CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
13060b57cec5SDimitry Andric           N.getRawVTableHolder());
130781ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
13080b57cec5SDimitry Andric           "invalid reference flags", &N);
13098bcb0991SDimitry Andric   unsigned DIBlockByRefStruct = 1 << 4;
131081ad6265SDimitry Andric   CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
13118bcb0991SDimitry Andric           "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   if (N.isVector()) {
13140b57cec5SDimitry Andric     const DINodeArray Elements = N.getElements();
131581ad6265SDimitry Andric     CheckDI(Elements.size() == 1 &&
13160b57cec5SDimitry Andric                 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
13170b57cec5SDimitry Andric             "invalid vector, expected one element of type subrange", &N);
13180b57cec5SDimitry Andric   }
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
13210b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric   if (auto *D = N.getRawDiscriminator()) {
132481ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
13250b57cec5SDimitry Andric             "discriminator can only appear on variant part");
13260b57cec5SDimitry Andric   }
13275ffd83dbSDimitry Andric 
13285ffd83dbSDimitry Andric   if (N.getRawDataLocation()) {
132981ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
13305ffd83dbSDimitry Andric             "dataLocation can only appear in array type");
13315ffd83dbSDimitry Andric   }
1332e8d8bef9SDimitry Andric 
1333e8d8bef9SDimitry Andric   if (N.getRawAssociated()) {
133481ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1335e8d8bef9SDimitry Andric             "associated can only appear in array type");
1336e8d8bef9SDimitry Andric   }
1337e8d8bef9SDimitry Andric 
1338e8d8bef9SDimitry Andric   if (N.getRawAllocated()) {
133981ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1340e8d8bef9SDimitry Andric             "allocated can only appear in array type");
1341e8d8bef9SDimitry Andric   }
1342e8d8bef9SDimitry Andric 
1343e8d8bef9SDimitry Andric   if (N.getRawRank()) {
134481ad6265SDimitry Andric     CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1345e8d8bef9SDimitry Andric             "rank can only appear in array type");
1346e8d8bef9SDimitry Andric   }
13475f757f3fSDimitry Andric 
13485f757f3fSDimitry Andric   if (N.getTag() == dwarf::DW_TAG_array_type) {
13495f757f3fSDimitry Andric     CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
13505f757f3fSDimitry Andric   }
13510b57cec5SDimitry Andric }
13520b57cec5SDimitry Andric 
visitDISubroutineType(const DISubroutineType & N)13530b57cec5SDimitry Andric void Verifier::visitDISubroutineType(const DISubroutineType &N) {
135481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
13550b57cec5SDimitry Andric   if (auto *Types = N.getRawTypeArray()) {
135681ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
13570b57cec5SDimitry Andric     for (Metadata *Ty : N.getTypeArray()->operands()) {
135881ad6265SDimitry Andric       CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
13590b57cec5SDimitry Andric     }
13600b57cec5SDimitry Andric   }
136181ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
13620b57cec5SDimitry Andric           "invalid reference flags", &N);
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
visitDIFile(const DIFile & N)13650b57cec5SDimitry Andric void Verifier::visitDIFile(const DIFile &N) {
136681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1367bdd1243dSDimitry Andric   std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
13680b57cec5SDimitry Andric   if (Checksum) {
136981ad6265SDimitry Andric     CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
13700b57cec5SDimitry Andric             "invalid checksum kind", &N);
13710b57cec5SDimitry Andric     size_t Size;
13720b57cec5SDimitry Andric     switch (Checksum->Kind) {
13730b57cec5SDimitry Andric     case DIFile::CSK_MD5:
13740b57cec5SDimitry Andric       Size = 32;
13750b57cec5SDimitry Andric       break;
13760b57cec5SDimitry Andric     case DIFile::CSK_SHA1:
13770b57cec5SDimitry Andric       Size = 40;
13780b57cec5SDimitry Andric       break;
13795ffd83dbSDimitry Andric     case DIFile::CSK_SHA256:
13805ffd83dbSDimitry Andric       Size = 64;
13815ffd83dbSDimitry Andric       break;
13820b57cec5SDimitry Andric     }
138381ad6265SDimitry Andric     CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
138481ad6265SDimitry Andric     CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
13850b57cec5SDimitry Andric             "invalid checksum", &N);
13860b57cec5SDimitry Andric   }
13870b57cec5SDimitry Andric }
13880b57cec5SDimitry Andric 
visitDICompileUnit(const DICompileUnit & N)13890b57cec5SDimitry Andric void Verifier::visitDICompileUnit(const DICompileUnit &N) {
139081ad6265SDimitry Andric   CheckDI(N.isDistinct(), "compile units must be distinct", &N);
139181ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   // Don't bother verifying the compilation directory or producer string
13940b57cec5SDimitry Andric   // as those could be empty.
139581ad6265SDimitry Andric   CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
13960b57cec5SDimitry Andric           N.getRawFile());
139781ad6265SDimitry Andric   CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
13980b57cec5SDimitry Andric           N.getFile());
13990b57cec5SDimitry Andric 
140081ad6265SDimitry Andric   CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
14010b57cec5SDimitry Andric           "invalid emission kind", &N);
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   if (auto *Array = N.getRawEnumTypes()) {
140481ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
14050b57cec5SDimitry Andric     for (Metadata *Op : N.getEnumTypes()->operands()) {
14060b57cec5SDimitry Andric       auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
140781ad6265SDimitry Andric       CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
14080b57cec5SDimitry Andric               "invalid enum type", &N, N.getEnumTypes(), Op);
14090b57cec5SDimitry Andric     }
14100b57cec5SDimitry Andric   }
14110b57cec5SDimitry Andric   if (auto *Array = N.getRawRetainedTypes()) {
141281ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
14130b57cec5SDimitry Andric     for (Metadata *Op : N.getRetainedTypes()->operands()) {
141481ad6265SDimitry Andric       CheckDI(
141581ad6265SDimitry Andric           Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
14160b57cec5SDimitry Andric                                      !cast<DISubprogram>(Op)->isDefinition())),
14170b57cec5SDimitry Andric           "invalid retained type", &N, Op);
14180b57cec5SDimitry Andric     }
14190b57cec5SDimitry Andric   }
14200b57cec5SDimitry Andric   if (auto *Array = N.getRawGlobalVariables()) {
142181ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
14220b57cec5SDimitry Andric     for (Metadata *Op : N.getGlobalVariables()->operands()) {
142381ad6265SDimitry Andric       CheckDI(Op && (isa<DIGlobalVariableExpression>(Op)),
14240b57cec5SDimitry Andric               "invalid global variable ref", &N, Op);
14250b57cec5SDimitry Andric     }
14260b57cec5SDimitry Andric   }
14270b57cec5SDimitry Andric   if (auto *Array = N.getRawImportedEntities()) {
142881ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
14290b57cec5SDimitry Andric     for (Metadata *Op : N.getImportedEntities()->operands()) {
143081ad6265SDimitry Andric       CheckDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
14310b57cec5SDimitry Andric               &N, Op);
14320b57cec5SDimitry Andric     }
14330b57cec5SDimitry Andric   }
14340b57cec5SDimitry Andric   if (auto *Array = N.getRawMacros()) {
143581ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
14360b57cec5SDimitry Andric     for (Metadata *Op : N.getMacros()->operands()) {
143781ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
14380b57cec5SDimitry Andric     }
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric   CUVisited.insert(&N);
14410b57cec5SDimitry Andric }
14420b57cec5SDimitry Andric 
visitDISubprogram(const DISubprogram & N)14430b57cec5SDimitry Andric void Verifier::visitDISubprogram(const DISubprogram &N) {
144481ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
144581ad6265SDimitry Andric   CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
14460b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
144781ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
14480b57cec5SDimitry Andric   else
144981ad6265SDimitry Andric     CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
14500b57cec5SDimitry Andric   if (auto *T = N.getRawType())
145181ad6265SDimitry Andric     CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
145281ad6265SDimitry Andric   CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
14530b57cec5SDimitry Andric           N.getRawContainingType());
14540b57cec5SDimitry Andric   if (auto *Params = N.getRawTemplateParams())
14550b57cec5SDimitry Andric     visitTemplateParams(N, *Params);
14560b57cec5SDimitry Andric   if (auto *S = N.getRawDeclaration())
145781ad6265SDimitry Andric     CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
14580b57cec5SDimitry Andric             "invalid subprogram declaration", &N, S);
14590b57cec5SDimitry Andric   if (auto *RawNode = N.getRawRetainedNodes()) {
14600b57cec5SDimitry Andric     auto *Node = dyn_cast<MDTuple>(RawNode);
146181ad6265SDimitry Andric     CheckDI(Node, "invalid retained nodes list", &N, RawNode);
14620b57cec5SDimitry Andric     for (Metadata *Op : Node->operands()) {
146306c3fb27SDimitry Andric       CheckDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op) ||
146406c3fb27SDimitry Andric                      isa<DIImportedEntity>(Op)),
146506c3fb27SDimitry Andric               "invalid retained nodes, expected DILocalVariable, DILabel or "
146606c3fb27SDimitry Andric               "DIImportedEntity",
146706c3fb27SDimitry Andric               &N, Node, Op);
14680b57cec5SDimitry Andric     }
14690b57cec5SDimitry Andric   }
147081ad6265SDimitry Andric   CheckDI(!hasConflictingReferenceFlags(N.getFlags()),
14710b57cec5SDimitry Andric           "invalid reference flags", &N);
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   auto *Unit = N.getRawUnit();
14740b57cec5SDimitry Andric   if (N.isDefinition()) {
14750b57cec5SDimitry Andric     // Subprogram definitions (not part of the type hierarchy).
147681ad6265SDimitry Andric     CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
147781ad6265SDimitry Andric     CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
147881ad6265SDimitry Andric     CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
14795f757f3fSDimitry Andric     // There's no good way to cross the CU boundary to insert a nested
14805f757f3fSDimitry Andric     // DISubprogram definition in one CU into a type defined in another CU.
14815f757f3fSDimitry Andric     auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
14825f757f3fSDimitry Andric     if (CT && CT->getRawIdentifier() &&
14835f757f3fSDimitry Andric         M.getContext().isODRUniquingDebugTypes())
14845f757f3fSDimitry Andric       CheckDI(N.getDeclaration(),
14855f757f3fSDimitry Andric               "definition subprograms cannot be nested within DICompositeType "
14865f757f3fSDimitry Andric               "when enabling ODR",
14875f757f3fSDimitry Andric               &N);
14880b57cec5SDimitry Andric   } else {
14890b57cec5SDimitry Andric     // Subprogram declarations (part of the type hierarchy).
149081ad6265SDimitry Andric     CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
149106c3fb27SDimitry Andric     CheckDI(!N.getRawDeclaration(),
149206c3fb27SDimitry Andric             "subprogram declaration must not have a declaration field");
14930b57cec5SDimitry Andric   }
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
14960b57cec5SDimitry Andric     auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
149781ad6265SDimitry Andric     CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
14980b57cec5SDimitry Andric     for (Metadata *Op : ThrownTypes->operands())
149981ad6265SDimitry Andric       CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
15000b57cec5SDimitry Andric               Op);
15010b57cec5SDimitry Andric   }
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   if (N.areAllCallsDescribed())
150481ad6265SDimitry Andric     CheckDI(N.isDefinition(),
15050b57cec5SDimitry Andric             "DIFlagAllCallsDescribed must be attached to a definition");
15060b57cec5SDimitry Andric }
15070b57cec5SDimitry Andric 
visitDILexicalBlockBase(const DILexicalBlockBase & N)15080b57cec5SDimitry Andric void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
150981ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
151081ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
15110b57cec5SDimitry Andric           "invalid local scope", &N, N.getRawScope());
15120b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
151381ad6265SDimitry Andric     CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric 
visitDILexicalBlock(const DILexicalBlock & N)15160b57cec5SDimitry Andric void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
15170b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
15180b57cec5SDimitry Andric 
151981ad6265SDimitry Andric   CheckDI(N.getLine() || !N.getColumn(),
15200b57cec5SDimitry Andric           "cannot have column info without line info", &N);
15210b57cec5SDimitry Andric }
15220b57cec5SDimitry Andric 
visitDILexicalBlockFile(const DILexicalBlockFile & N)15230b57cec5SDimitry Andric void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
15240b57cec5SDimitry Andric   visitDILexicalBlockBase(N);
15250b57cec5SDimitry Andric }
15260b57cec5SDimitry Andric 
visitDICommonBlock(const DICommonBlock & N)15270b57cec5SDimitry Andric void Verifier::visitDICommonBlock(const DICommonBlock &N) {
152881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
15290b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
153081ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
15310b57cec5SDimitry Andric   if (auto *S = N.getRawDecl())
153281ad6265SDimitry Andric     CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
15330b57cec5SDimitry Andric }
15340b57cec5SDimitry Andric 
visitDINamespace(const DINamespace & N)15350b57cec5SDimitry Andric void Verifier::visitDINamespace(const DINamespace &N) {
153681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
15370b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
153881ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric 
visitDIMacro(const DIMacro & N)15410b57cec5SDimitry Andric void Verifier::visitDIMacro(const DIMacro &N) {
154281ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
15430b57cec5SDimitry Andric               N.getMacinfoType() == dwarf::DW_MACINFO_undef,
15440b57cec5SDimitry Andric           "invalid macinfo type", &N);
154581ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous macro", &N);
15460b57cec5SDimitry Andric   if (!N.getValue().empty()) {
15470b57cec5SDimitry Andric     assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
15480b57cec5SDimitry Andric   }
15490b57cec5SDimitry Andric }
15500b57cec5SDimitry Andric 
visitDIMacroFile(const DIMacroFile & N)15510b57cec5SDimitry Andric void Verifier::visitDIMacroFile(const DIMacroFile &N) {
155281ad6265SDimitry Andric   CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
15530b57cec5SDimitry Andric           "invalid macinfo type", &N);
15540b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
155581ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   if (auto *Array = N.getRawElements()) {
155881ad6265SDimitry Andric     CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
15590b57cec5SDimitry Andric     for (Metadata *Op : N.getElements()->operands()) {
156081ad6265SDimitry Andric       CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
15610b57cec5SDimitry Andric     }
15620b57cec5SDimitry Andric   }
15630b57cec5SDimitry Andric }
15640b57cec5SDimitry Andric 
visitDIModule(const DIModule & N)15650b57cec5SDimitry Andric void Verifier::visitDIModule(const DIModule &N) {
156681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
156781ad6265SDimitry Andric   CheckDI(!N.getName().empty(), "anonymous module", &N);
15680b57cec5SDimitry Andric }
15690b57cec5SDimitry Andric 
visitDITemplateParameter(const DITemplateParameter & N)15700b57cec5SDimitry Andric void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
157181ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
visitDITemplateTypeParameter(const DITemplateTypeParameter & N)15740b57cec5SDimitry Andric void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
15750b57cec5SDimitry Andric   visitDITemplateParameter(N);
15760b57cec5SDimitry Andric 
157781ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
15780b57cec5SDimitry Andric           &N);
15790b57cec5SDimitry Andric }
15800b57cec5SDimitry Andric 
visitDITemplateValueParameter(const DITemplateValueParameter & N)15810b57cec5SDimitry Andric void Verifier::visitDITemplateValueParameter(
15820b57cec5SDimitry Andric     const DITemplateValueParameter &N) {
15830b57cec5SDimitry Andric   visitDITemplateParameter(N);
15840b57cec5SDimitry Andric 
158581ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
15860b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
15870b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
15880b57cec5SDimitry Andric           "invalid tag", &N);
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
visitDIVariable(const DIVariable & N)15910b57cec5SDimitry Andric void Verifier::visitDIVariable(const DIVariable &N) {
15920b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
159381ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
15940b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
159581ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
15960b57cec5SDimitry Andric }
15970b57cec5SDimitry Andric 
visitDIGlobalVariable(const DIGlobalVariable & N)15980b57cec5SDimitry Andric void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
15990b57cec5SDimitry Andric   // Checks common to all variables.
16000b57cec5SDimitry Andric   visitDIVariable(N);
16010b57cec5SDimitry Andric 
160281ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
160381ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
160481ad6265SDimitry Andric   // Check only if the global variable is not an extern
16055ffd83dbSDimitry Andric   if (N.isDefinition())
160681ad6265SDimitry Andric     CheckDI(N.getType(), "missing global variable type", &N);
16070b57cec5SDimitry Andric   if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
160881ad6265SDimitry Andric     CheckDI(isa<DIDerivedType>(Member),
16090b57cec5SDimitry Andric             "invalid static data member declaration", &N, Member);
16100b57cec5SDimitry Andric   }
16110b57cec5SDimitry Andric }
16120b57cec5SDimitry Andric 
visitDILocalVariable(const DILocalVariable & N)16130b57cec5SDimitry Andric void Verifier::visitDILocalVariable(const DILocalVariable &N) {
16140b57cec5SDimitry Andric   // Checks common to all variables.
16150b57cec5SDimitry Andric   visitDIVariable(N);
16160b57cec5SDimitry Andric 
161781ad6265SDimitry Andric   CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
161881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
161981ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
16200b57cec5SDimitry Andric           "local variable requires a valid scope", &N, N.getRawScope());
16210b57cec5SDimitry Andric   if (auto Ty = N.getType())
162281ad6265SDimitry Andric     CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
16230b57cec5SDimitry Andric }
16240b57cec5SDimitry Andric 
visitDIAssignID(const DIAssignID & N)1625bdd1243dSDimitry Andric void Verifier::visitDIAssignID(const DIAssignID &N) {
1626bdd1243dSDimitry Andric   CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1627bdd1243dSDimitry Andric   CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1628bdd1243dSDimitry Andric }
1629bdd1243dSDimitry Andric 
visitDILabel(const DILabel & N)16300b57cec5SDimitry Andric void Verifier::visitDILabel(const DILabel &N) {
16310b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
163281ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
16330b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
163481ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
16350b57cec5SDimitry Andric 
163681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
163781ad6265SDimitry Andric   CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
16380b57cec5SDimitry Andric           "label requires a valid scope", &N, N.getRawScope());
16390b57cec5SDimitry Andric }
16400b57cec5SDimitry Andric 
visitDIExpression(const DIExpression & N)16410b57cec5SDimitry Andric void Verifier::visitDIExpression(const DIExpression &N) {
164281ad6265SDimitry Andric   CheckDI(N.isValid(), "invalid expression", &N);
16430b57cec5SDimitry Andric }
16440b57cec5SDimitry Andric 
visitDIGlobalVariableExpression(const DIGlobalVariableExpression & GVE)16450b57cec5SDimitry Andric void Verifier::visitDIGlobalVariableExpression(
16460b57cec5SDimitry Andric     const DIGlobalVariableExpression &GVE) {
164781ad6265SDimitry Andric   CheckDI(GVE.getVariable(), "missing variable");
16480b57cec5SDimitry Andric   if (auto *Var = GVE.getVariable())
16490b57cec5SDimitry Andric     visitDIGlobalVariable(*Var);
16500b57cec5SDimitry Andric   if (auto *Expr = GVE.getExpression()) {
16510b57cec5SDimitry Andric     visitDIExpression(*Expr);
16520b57cec5SDimitry Andric     if (auto Fragment = Expr->getFragmentInfo())
16530b57cec5SDimitry Andric       verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
16540b57cec5SDimitry Andric   }
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric 
visitDIObjCProperty(const DIObjCProperty & N)16570b57cec5SDimitry Andric void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
165881ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
16590b57cec5SDimitry Andric   if (auto *T = N.getRawType())
166081ad6265SDimitry Andric     CheckDI(isType(T), "invalid type ref", &N, T);
16610b57cec5SDimitry Andric   if (auto *F = N.getRawFile())
166281ad6265SDimitry Andric     CheckDI(isa<DIFile>(F), "invalid file", &N, F);
16630b57cec5SDimitry Andric }
16640b57cec5SDimitry Andric 
visitDIImportedEntity(const DIImportedEntity & N)16650b57cec5SDimitry Andric void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
166681ad6265SDimitry Andric   CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
16670b57cec5SDimitry Andric               N.getTag() == dwarf::DW_TAG_imported_declaration,
16680b57cec5SDimitry Andric           "invalid tag", &N);
16690b57cec5SDimitry Andric   if (auto *S = N.getRawScope())
167081ad6265SDimitry Andric     CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
167181ad6265SDimitry Andric   CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
16720b57cec5SDimitry Andric           N.getRawEntity());
16730b57cec5SDimitry Andric }
16740b57cec5SDimitry Andric 
visitComdat(const Comdat & C)16750b57cec5SDimitry Andric void Verifier::visitComdat(const Comdat &C) {
16768bcb0991SDimitry Andric   // In COFF the Module is invalid if the GlobalValue has private linkage.
16778bcb0991SDimitry Andric   // Entities with private linkage don't have entries in the symbol table.
16788bcb0991SDimitry Andric   if (TT.isOSBinFormatCOFF())
16790b57cec5SDimitry Andric     if (const GlobalValue *GV = M.getNamedValue(C.getName()))
168081ad6265SDimitry Andric       Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
168181ad6265SDimitry Andric             GV);
16820b57cec5SDimitry Andric }
16830b57cec5SDimitry Andric 
visitModuleIdents()1684349cc55cSDimitry Andric void Verifier::visitModuleIdents() {
16850b57cec5SDimitry Andric   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
16860b57cec5SDimitry Andric   if (!Idents)
16870b57cec5SDimitry Andric     return;
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric   // llvm.ident takes a list of metadata entry. Each entry has only one string.
16900b57cec5SDimitry Andric   // Scan each llvm.ident entry and make sure that this requirement is met.
16910b57cec5SDimitry Andric   for (const MDNode *N : Idents->operands()) {
169281ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
16930b57cec5SDimitry Andric           "incorrect number of operands in llvm.ident metadata", N);
169481ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
16950b57cec5SDimitry Andric           ("invalid value for llvm.ident metadata entry operand"
16960b57cec5SDimitry Andric            "(the operand should be a string)"),
16970b57cec5SDimitry Andric           N->getOperand(0));
16980b57cec5SDimitry Andric   }
16990b57cec5SDimitry Andric }
17000b57cec5SDimitry Andric 
visitModuleCommandLines()1701349cc55cSDimitry Andric void Verifier::visitModuleCommandLines() {
17020b57cec5SDimitry Andric   const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
17030b57cec5SDimitry Andric   if (!CommandLines)
17040b57cec5SDimitry Andric     return;
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric   // llvm.commandline takes a list of metadata entry. Each entry has only one
17070b57cec5SDimitry Andric   // string. Scan each llvm.commandline entry and make sure that this
17080b57cec5SDimitry Andric   // requirement is met.
17090b57cec5SDimitry Andric   for (const MDNode *N : CommandLines->operands()) {
171081ad6265SDimitry Andric     Check(N->getNumOperands() == 1,
17110b57cec5SDimitry Andric           "incorrect number of operands in llvm.commandline metadata", N);
171281ad6265SDimitry Andric     Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
17130b57cec5SDimitry Andric           ("invalid value for llvm.commandline metadata entry operand"
17140b57cec5SDimitry Andric            "(the operand should be a string)"),
17150b57cec5SDimitry Andric           N->getOperand(0));
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric }
17180b57cec5SDimitry Andric 
visitModuleFlags()1719349cc55cSDimitry Andric void Verifier::visitModuleFlags() {
17200b57cec5SDimitry Andric   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
17210b57cec5SDimitry Andric   if (!Flags) return;
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // Scan each flag, and track the flags and requirements.
17240b57cec5SDimitry Andric   DenseMap<const MDString*, const MDNode*> SeenIDs;
17250b57cec5SDimitry Andric   SmallVector<const MDNode*, 16> Requirements;
1726*0fca6ea1SDimitry Andric   uint64_t PAuthABIPlatform = -1;
1727*0fca6ea1SDimitry Andric   uint64_t PAuthABIVersion = -1;
1728*0fca6ea1SDimitry Andric   for (const MDNode *MDN : Flags->operands()) {
17290b57cec5SDimitry Andric     visitModuleFlag(MDN, SeenIDs, Requirements);
1730*0fca6ea1SDimitry Andric     if (MDN->getNumOperands() != 3)
1731*0fca6ea1SDimitry Andric       continue;
1732*0fca6ea1SDimitry Andric     if (const auto *FlagName = dyn_cast_or_null<MDString>(MDN->getOperand(1))) {
1733*0fca6ea1SDimitry Andric       if (FlagName->getString() == "aarch64-elf-pauthabi-platform") {
1734*0fca6ea1SDimitry Andric         if (const auto *PAP =
1735*0fca6ea1SDimitry Andric                 mdconst::dyn_extract_or_null<ConstantInt>(MDN->getOperand(2)))
1736*0fca6ea1SDimitry Andric           PAuthABIPlatform = PAP->getZExtValue();
1737*0fca6ea1SDimitry Andric       } else if (FlagName->getString() == "aarch64-elf-pauthabi-version") {
1738*0fca6ea1SDimitry Andric         if (const auto *PAV =
1739*0fca6ea1SDimitry Andric                 mdconst::dyn_extract_or_null<ConstantInt>(MDN->getOperand(2)))
1740*0fca6ea1SDimitry Andric           PAuthABIVersion = PAV->getZExtValue();
1741*0fca6ea1SDimitry Andric       }
1742*0fca6ea1SDimitry Andric     }
1743*0fca6ea1SDimitry Andric   }
1744*0fca6ea1SDimitry Andric 
1745*0fca6ea1SDimitry Andric   if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
1746*0fca6ea1SDimitry Andric     CheckFailed("either both or no 'aarch64-elf-pauthabi-platform' and "
1747*0fca6ea1SDimitry Andric                 "'aarch64-elf-pauthabi-version' module flags must be present");
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   // Validate that the requirements in the module are valid.
17500b57cec5SDimitry Andric   for (const MDNode *Requirement : Requirements) {
17510b57cec5SDimitry Andric     const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
17520b57cec5SDimitry Andric     const Metadata *ReqValue = Requirement->getOperand(1);
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric     const MDNode *Op = SeenIDs.lookup(Flag);
17550b57cec5SDimitry Andric     if (!Op) {
17560b57cec5SDimitry Andric       CheckFailed("invalid requirement on flag, flag is not present in module",
17570b57cec5SDimitry Andric                   Flag);
17580b57cec5SDimitry Andric       continue;
17590b57cec5SDimitry Andric     }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric     if (Op->getOperand(2) != ReqValue) {
17620b57cec5SDimitry Andric       CheckFailed(("invalid requirement on flag, "
17630b57cec5SDimitry Andric                    "flag does not have the required value"),
17640b57cec5SDimitry Andric                   Flag);
17650b57cec5SDimitry Andric       continue;
17660b57cec5SDimitry Andric     }
17670b57cec5SDimitry Andric   }
17680b57cec5SDimitry Andric }
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric void
visitModuleFlag(const MDNode * Op,DenseMap<const MDString *,const MDNode * > & SeenIDs,SmallVectorImpl<const MDNode * > & Requirements)17710b57cec5SDimitry Andric Verifier::visitModuleFlag(const MDNode *Op,
17720b57cec5SDimitry Andric                           DenseMap<const MDString *, const MDNode *> &SeenIDs,
17730b57cec5SDimitry Andric                           SmallVectorImpl<const MDNode *> &Requirements) {
17740b57cec5SDimitry Andric   // Each module flag should have three arguments, the merge behavior (a
17750b57cec5SDimitry Andric   // constant int), the flag ID (an MDString), and the value.
177681ad6265SDimitry Andric   Check(Op->getNumOperands() == 3,
17770b57cec5SDimitry Andric         "incorrect number of operands in module flag", Op);
17780b57cec5SDimitry Andric   Module::ModFlagBehavior MFB;
17790b57cec5SDimitry Andric   if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
178081ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
17810b57cec5SDimitry Andric           "invalid behavior operand in module flag (expected constant integer)",
17820b57cec5SDimitry Andric           Op->getOperand(0));
178381ad6265SDimitry Andric     Check(false,
17840b57cec5SDimitry Andric           "invalid behavior operand in module flag (unexpected constant)",
17850b57cec5SDimitry Andric           Op->getOperand(0));
17860b57cec5SDimitry Andric   }
17870b57cec5SDimitry Andric   MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
178881ad6265SDimitry Andric   Check(ID, "invalid ID operand in module flag (expected metadata string)",
17890b57cec5SDimitry Andric         Op->getOperand(1));
17900b57cec5SDimitry Andric 
17914824e7fdSDimitry Andric   // Check the values for behaviors with additional requirements.
17920b57cec5SDimitry Andric   switch (MFB) {
17930b57cec5SDimitry Andric   case Module::Error:
17940b57cec5SDimitry Andric   case Module::Warning:
17950b57cec5SDimitry Andric   case Module::Override:
17960b57cec5SDimitry Andric     // These behavior types accept any value.
17970b57cec5SDimitry Andric     break;
17980b57cec5SDimitry Andric 
179981ad6265SDimitry Andric   case Module::Min: {
1800fcaf7f86SDimitry Andric     auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
1801fcaf7f86SDimitry Andric     Check(V && V->getValue().isNonNegative(),
1802fcaf7f86SDimitry Andric           "invalid value for 'min' module flag (expected constant non-negative "
1803fcaf7f86SDimitry Andric           "integer)",
180481ad6265SDimitry Andric           Op->getOperand(2));
180581ad6265SDimitry Andric     break;
180681ad6265SDimitry Andric   }
180781ad6265SDimitry Andric 
18080b57cec5SDimitry Andric   case Module::Max: {
180981ad6265SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)),
18100b57cec5SDimitry Andric           "invalid value for 'max' module flag (expected constant integer)",
18110b57cec5SDimitry Andric           Op->getOperand(2));
18120b57cec5SDimitry Andric     break;
18130b57cec5SDimitry Andric   }
18140b57cec5SDimitry Andric 
18150b57cec5SDimitry Andric   case Module::Require: {
18160b57cec5SDimitry Andric     // The value should itself be an MDNode with two operands, a flag ID (an
18170b57cec5SDimitry Andric     // MDString), and a value.
18180b57cec5SDimitry Andric     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
181981ad6265SDimitry Andric     Check(Value && Value->getNumOperands() == 2,
18200b57cec5SDimitry Andric           "invalid value for 'require' module flag (expected metadata pair)",
18210b57cec5SDimitry Andric           Op->getOperand(2));
182281ad6265SDimitry Andric     Check(isa<MDString>(Value->getOperand(0)),
18230b57cec5SDimitry Andric           ("invalid value for 'require' module flag "
18240b57cec5SDimitry Andric            "(first value operand should be a string)"),
18250b57cec5SDimitry Andric           Value->getOperand(0));
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric     // Append it to the list of requirements, to check once all module flags are
18280b57cec5SDimitry Andric     // scanned.
18290b57cec5SDimitry Andric     Requirements.push_back(Value);
18300b57cec5SDimitry Andric     break;
18310b57cec5SDimitry Andric   }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric   case Module::Append:
18340b57cec5SDimitry Andric   case Module::AppendUnique: {
18350b57cec5SDimitry Andric     // These behavior types require the operand be an MDNode.
183681ad6265SDimitry Andric     Check(isa<MDNode>(Op->getOperand(2)),
18370b57cec5SDimitry Andric           "invalid value for 'append'-type module flag "
18380b57cec5SDimitry Andric           "(expected a metadata node)",
18390b57cec5SDimitry Andric           Op->getOperand(2));
18400b57cec5SDimitry Andric     break;
18410b57cec5SDimitry Andric   }
18420b57cec5SDimitry Andric   }
18430b57cec5SDimitry Andric 
18440b57cec5SDimitry Andric   // Unless this is a "requires" flag, check the ID is unique.
18450b57cec5SDimitry Andric   if (MFB != Module::Require) {
18460b57cec5SDimitry Andric     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
184781ad6265SDimitry Andric     Check(Inserted,
18480b57cec5SDimitry Andric           "module flag identifiers must be unique (or of 'require' type)", ID);
18490b57cec5SDimitry Andric   }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   if (ID->getString() == "wchar_size") {
18520b57cec5SDimitry Andric     ConstantInt *Value
18530b57cec5SDimitry Andric       = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
185481ad6265SDimitry Andric     Check(Value, "wchar_size metadata requires constant integer argument");
18550b57cec5SDimitry Andric   }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric   if (ID->getString() == "Linker Options") {
18580b57cec5SDimitry Andric     // If the llvm.linker.options named metadata exists, we assume that the
18590b57cec5SDimitry Andric     // bitcode reader has upgraded the module flag. Otherwise the flag might
18600b57cec5SDimitry Andric     // have been created by a client directly.
186181ad6265SDimitry Andric     Check(M.getNamedMetadata("llvm.linker.options"),
18620b57cec5SDimitry Andric           "'Linker Options' named metadata no longer supported");
18630b57cec5SDimitry Andric   }
18640b57cec5SDimitry Andric 
18655ffd83dbSDimitry Andric   if (ID->getString() == "SemanticInterposition") {
18665ffd83dbSDimitry Andric     ConstantInt *Value =
18675ffd83dbSDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
186881ad6265SDimitry Andric     Check(Value,
18695ffd83dbSDimitry Andric           "SemanticInterposition metadata requires constant integer argument");
18705ffd83dbSDimitry Andric   }
18715ffd83dbSDimitry Andric 
18720b57cec5SDimitry Andric   if (ID->getString() == "CG Profile") {
18730b57cec5SDimitry Andric     for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
18740b57cec5SDimitry Andric       visitModuleFlagCGProfileEntry(MDO);
18750b57cec5SDimitry Andric   }
18760b57cec5SDimitry Andric }
18770b57cec5SDimitry Andric 
visitModuleFlagCGProfileEntry(const MDOperand & MDO)18780b57cec5SDimitry Andric void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
18790b57cec5SDimitry Andric   auto CheckFunction = [&](const MDOperand &FuncMDO) {
18800b57cec5SDimitry Andric     if (!FuncMDO)
18810b57cec5SDimitry Andric       return;
18820b57cec5SDimitry Andric     auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
188381ad6265SDimitry Andric     Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
1884e8d8bef9SDimitry Andric           "expected a Function or null", FuncMDO);
18850b57cec5SDimitry Andric   };
18860b57cec5SDimitry Andric   auto Node = dyn_cast_or_null<MDNode>(MDO);
188781ad6265SDimitry Andric   Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
18880b57cec5SDimitry Andric   CheckFunction(Node->getOperand(0));
18890b57cec5SDimitry Andric   CheckFunction(Node->getOperand(1));
18900b57cec5SDimitry Andric   auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
189181ad6265SDimitry Andric   Check(Count && Count->getType()->isIntegerTy(),
18920b57cec5SDimitry Andric         "expected an integer constant", Node->getOperand(2));
18930b57cec5SDimitry Andric }
18940b57cec5SDimitry Andric 
verifyAttributeTypes(AttributeSet Attrs,const Value * V)1895fe6060f1SDimitry Andric void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
18960b57cec5SDimitry Andric   for (Attribute A : Attrs) {
1897fe6060f1SDimitry Andric 
1898fe6060f1SDimitry Andric     if (A.isStringAttribute()) {
1899fe6060f1SDimitry Andric #define GET_ATTR_NAMES
1900fe6060f1SDimitry Andric #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1901fe6060f1SDimitry Andric #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME)                             \
1902fe6060f1SDimitry Andric   if (A.getKindAsString() == #DISPLAY_NAME) {                                  \
1903fe6060f1SDimitry Andric     auto V = A.getValueAsString();                                             \
1904fe6060f1SDimitry Andric     if (!(V.empty() || V == "true" || V == "false"))                           \
1905fe6060f1SDimitry Andric       CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V +    \
1906fe6060f1SDimitry Andric                   "");                                                         \
1907fe6060f1SDimitry Andric   }
1908fe6060f1SDimitry Andric 
1909fe6060f1SDimitry Andric #include "llvm/IR/Attributes.inc"
19100b57cec5SDimitry Andric       continue;
1911fe6060f1SDimitry Andric     }
19120b57cec5SDimitry Andric 
1913fe6060f1SDimitry Andric     if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
19145ffd83dbSDimitry Andric       CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
19155ffd83dbSDimitry Andric                   V);
19165ffd83dbSDimitry Andric       return;
19175ffd83dbSDimitry Andric     }
19180b57cec5SDimitry Andric   }
19190b57cec5SDimitry Andric }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric // VerifyParameterAttrs - Check the given attributes for an argument or return
19220b57cec5SDimitry Andric // value of the specified type.  The value V is printed in error messages.
verifyParameterAttrs(AttributeSet Attrs,Type * Ty,const Value * V)19230b57cec5SDimitry Andric void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
19240b57cec5SDimitry Andric                                     const Value *V) {
19250b57cec5SDimitry Andric   if (!Attrs.hasAttributes())
19260b57cec5SDimitry Andric     return;
19270b57cec5SDimitry Andric 
1928fe6060f1SDimitry Andric   verifyAttributeTypes(Attrs, V);
1929fe6060f1SDimitry Andric 
1930fe6060f1SDimitry Andric   for (Attribute Attr : Attrs)
193181ad6265SDimitry Andric     Check(Attr.isStringAttribute() ||
1932fe6060f1SDimitry Andric               Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
193381ad6265SDimitry Andric           "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
1934fe6060f1SDimitry Andric           V);
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric   if (Attrs.hasAttribute(Attribute::ImmArg)) {
193781ad6265SDimitry Andric     Check(Attrs.getNumAttributes() == 1,
19380b57cec5SDimitry Andric           "Attribute 'immarg' is incompatible with other attributes", V);
19390b57cec5SDimitry Andric   }
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   // Check for mutually incompatible attributes.  Only inreg is compatible with
19420b57cec5SDimitry Andric   // sret.
19430b57cec5SDimitry Andric   unsigned AttrCount = 0;
19440b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByVal);
19450b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
19465ffd83dbSDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
19470b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
19480b57cec5SDimitry Andric                Attrs.hasAttribute(Attribute::InReg);
19490b57cec5SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::Nest);
1950e8d8bef9SDimitry Andric   AttrCount += Attrs.hasAttribute(Attribute::ByRef);
195181ad6265SDimitry Andric   Check(AttrCount <= 1,
19525ffd83dbSDimitry Andric         "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1953e8d8bef9SDimitry Andric         "'byref', and 'sret' are incompatible!",
19540b57cec5SDimitry Andric         V);
19550b57cec5SDimitry Andric 
195681ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
19570b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
19580b57cec5SDimitry Andric         "Attributes "
19590b57cec5SDimitry Andric         "'inalloca and readonly' are incompatible!",
19600b57cec5SDimitry Andric         V);
19610b57cec5SDimitry Andric 
196281ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
19630b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::Returned)),
19640b57cec5SDimitry Andric         "Attributes "
19650b57cec5SDimitry Andric         "'sret and returned' are incompatible!",
19660b57cec5SDimitry Andric         V);
19670b57cec5SDimitry Andric 
196881ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
19690b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::SExt)),
19700b57cec5SDimitry Andric         "Attributes "
19710b57cec5SDimitry Andric         "'zeroext and signext' are incompatible!",
19720b57cec5SDimitry Andric         V);
19730b57cec5SDimitry Andric 
197481ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
19750b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
19760b57cec5SDimitry Andric         "Attributes "
19770b57cec5SDimitry Andric         "'readnone and readonly' are incompatible!",
19780b57cec5SDimitry Andric         V);
19790b57cec5SDimitry Andric 
198081ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
19810b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
19820b57cec5SDimitry Andric         "Attributes "
19830b57cec5SDimitry Andric         "'readnone and writeonly' are incompatible!",
19840b57cec5SDimitry Andric         V);
19850b57cec5SDimitry Andric 
198681ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
19870b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::WriteOnly)),
19880b57cec5SDimitry Andric         "Attributes "
19890b57cec5SDimitry Andric         "'readonly and writeonly' are incompatible!",
19900b57cec5SDimitry Andric         V);
19910b57cec5SDimitry Andric 
199281ad6265SDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
19930b57cec5SDimitry Andric           Attrs.hasAttribute(Attribute::AlwaysInline)),
19940b57cec5SDimitry Andric         "Attributes "
19950b57cec5SDimitry Andric         "'noinline and alwaysinline' are incompatible!",
19960b57cec5SDimitry Andric         V);
19970b57cec5SDimitry Andric 
19985f757f3fSDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::Writable) &&
19995f757f3fSDimitry Andric           Attrs.hasAttribute(Attribute::ReadNone)),
20005f757f3fSDimitry Andric         "Attributes writable and readnone are incompatible!", V);
20015f757f3fSDimitry Andric 
20025f757f3fSDimitry Andric   Check(!(Attrs.hasAttribute(Attribute::Writable) &&
20035f757f3fSDimitry Andric           Attrs.hasAttribute(Attribute::ReadOnly)),
20045f757f3fSDimitry Andric         "Attributes writable and readonly are incompatible!", V);
20055f757f3fSDimitry Andric 
200604eeddc0SDimitry Andric   AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
2007fe6060f1SDimitry Andric   for (Attribute Attr : Attrs) {
2008fe6060f1SDimitry Andric     if (!Attr.isStringAttribute() &&
2009fe6060f1SDimitry Andric         IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
2010fe6060f1SDimitry Andric       CheckFailed("Attribute '" + Attr.getAsString() +
2011fe6060f1SDimitry Andric                   "' applied to incompatible type!", V);
2012fe6060f1SDimitry Andric       return;
2013fe6060f1SDimitry Andric     }
2014fe6060f1SDimitry Andric   }
20150b57cec5SDimitry Andric 
201606c3fb27SDimitry Andric   if (isa<PointerType>(Ty)) {
201781ad6265SDimitry Andric     if (Attrs.hasAttribute(Attribute::Alignment)) {
201881ad6265SDimitry Andric       Align AttrAlign = Attrs.getAlignment().valueOrOne();
2019*0fca6ea1SDimitry Andric       Check(AttrAlign.value() <= Value::MaximumAlignment,
2020*0fca6ea1SDimitry Andric             "huge alignment values are unsupported", V);
202181ad6265SDimitry Andric     }
2022*0fca6ea1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByVal)) {
20230b57cec5SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
202481ad6265SDimitry Andric       Check(Attrs.getByValType()->isSized(&Visited),
2025fe6060f1SDimitry Andric             "Attribute 'byval' does not support unsized types!", V);
2026*0fca6ea1SDimitry Andric       Check(DL.getTypeAllocSize(Attrs.getByValType()).getKnownMinValue() <
2027*0fca6ea1SDimitry Andric                 (1ULL << 32),
2028*0fca6ea1SDimitry Andric             "huge 'byval' arguments are unsupported", V);
20290b57cec5SDimitry Andric     }
2030fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::ByRef)) {
2031fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
203281ad6265SDimitry Andric       Check(Attrs.getByRefType()->isSized(&Visited),
2033fe6060f1SDimitry Andric             "Attribute 'byref' does not support unsized types!", V);
2034*0fca6ea1SDimitry Andric       Check(DL.getTypeAllocSize(Attrs.getByRefType()).getKnownMinValue() <
2035*0fca6ea1SDimitry Andric                 (1ULL << 32),
2036*0fca6ea1SDimitry Andric             "huge 'byref' arguments are unsupported", V);
2037fe6060f1SDimitry Andric     }
2038fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::InAlloca)) {
2039fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
204081ad6265SDimitry Andric       Check(Attrs.getInAllocaType()->isSized(&Visited),
2041fe6060f1SDimitry Andric             "Attribute 'inalloca' does not support unsized types!", V);
2042*0fca6ea1SDimitry Andric       Check(DL.getTypeAllocSize(Attrs.getInAllocaType()).getKnownMinValue() <
2043*0fca6ea1SDimitry Andric                 (1ULL << 32),
2044*0fca6ea1SDimitry Andric             "huge 'inalloca' arguments are unsupported", V);
2045fe6060f1SDimitry Andric     }
2046fe6060f1SDimitry Andric     if (Attrs.hasAttribute(Attribute::Preallocated)) {
2047fe6060f1SDimitry Andric       SmallPtrSet<Type *, 4> Visited;
204881ad6265SDimitry Andric       Check(Attrs.getPreallocatedType()->isSized(&Visited),
2049fe6060f1SDimitry Andric             "Attribute 'preallocated' does not support unsized types!", V);
2050*0fca6ea1SDimitry Andric       Check(
2051*0fca6ea1SDimitry Andric           DL.getTypeAllocSize(Attrs.getPreallocatedType()).getKnownMinValue() <
2052*0fca6ea1SDimitry Andric               (1ULL << 32),
2053*0fca6ea1SDimitry Andric           "huge 'preallocated' arguments are unsupported", V);
2054fe6060f1SDimitry Andric     }
205506c3fb27SDimitry Andric   }
205606c3fb27SDimitry Andric 
2057*0fca6ea1SDimitry Andric   if (Attrs.hasAttribute(Attribute::Initializes)) {
2058*0fca6ea1SDimitry Andric     auto Inits = Attrs.getAttribute(Attribute::Initializes).getInitializes();
2059*0fca6ea1SDimitry Andric     Check(!Inits.empty(), "Attribute 'initializes' does not support empty list",
2060*0fca6ea1SDimitry Andric           V);
2061*0fca6ea1SDimitry Andric     Check(ConstantRangeList::isOrderedRanges(Inits),
2062*0fca6ea1SDimitry Andric           "Attribute 'initializes' does not support unordered ranges", V);
2063*0fca6ea1SDimitry Andric   }
2064*0fca6ea1SDimitry Andric 
206506c3fb27SDimitry Andric   if (Attrs.hasAttribute(Attribute::NoFPClass)) {
206606c3fb27SDimitry Andric     uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
206706c3fb27SDimitry Andric     Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
20680b57cec5SDimitry Andric           V);
206906c3fb27SDimitry Andric     Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
207006c3fb27SDimitry Andric           "Invalid value for 'nofpclass' test mask", V);
2071fe6060f1SDimitry Andric   }
2072*0fca6ea1SDimitry Andric   if (Attrs.hasAttribute(Attribute::Range)) {
2073*0fca6ea1SDimitry Andric     const ConstantRange &CR =
2074*0fca6ea1SDimitry Andric         Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2075*0fca6ea1SDimitry Andric     Check(Ty->isIntOrIntVectorTy(CR.getBitWidth()),
2076*0fca6ea1SDimitry Andric           "Range bit width must match type bit width!", V);
2077*0fca6ea1SDimitry Andric   }
2078fe6060f1SDimitry Andric }
2079fe6060f1SDimitry Andric 
checkUnsignedBaseTenFuncAttr(AttributeList Attrs,StringRef Attr,const Value * V)2080fe6060f1SDimitry Andric void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2081fe6060f1SDimitry Andric                                             const Value *V) {
2082349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attr)) {
2083349cc55cSDimitry Andric     StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
2084fe6060f1SDimitry Andric     unsigned N;
2085fe6060f1SDimitry Andric     if (S.getAsInteger(10, N))
2086fe6060f1SDimitry Andric       CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
20870b57cec5SDimitry Andric   }
20880b57cec5SDimitry Andric }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric // Check parameter attributes against a function type.
20910b57cec5SDimitry Andric // The value V is printed in error messages.
verifyFunctionAttrs(FunctionType * FT,AttributeList Attrs,const Value * V,bool IsIntrinsic,bool IsInlineAsm)20920b57cec5SDimitry Andric void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
209304eeddc0SDimitry Andric                                    const Value *V, bool IsIntrinsic,
209404eeddc0SDimitry Andric                                    bool IsInlineAsm) {
20950b57cec5SDimitry Andric   if (Attrs.isEmpty())
20960b57cec5SDimitry Andric     return;
20970b57cec5SDimitry Andric 
2098fe6060f1SDimitry Andric   if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
209981ad6265SDimitry Andric     Check(Attrs.hasParentContext(Context),
2100fe6060f1SDimitry Andric           "Attribute list does not match Module context!", &Attrs, V);
2101fe6060f1SDimitry Andric     for (const auto &AttrSet : Attrs) {
210281ad6265SDimitry Andric       Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2103fe6060f1SDimitry Andric             "Attribute set does not match Module context!", &AttrSet, V);
2104fe6060f1SDimitry Andric       for (const auto &A : AttrSet) {
210581ad6265SDimitry Andric         Check(A.hasParentContext(Context),
2106fe6060f1SDimitry Andric               "Attribute does not match Module context!", &A, V);
2107fe6060f1SDimitry Andric       }
2108fe6060f1SDimitry Andric     }
2109fe6060f1SDimitry Andric   }
2110fe6060f1SDimitry Andric 
21110b57cec5SDimitry Andric   bool SawNest = false;
21120b57cec5SDimitry Andric   bool SawReturned = false;
21130b57cec5SDimitry Andric   bool SawSRet = false;
21140b57cec5SDimitry Andric   bool SawSwiftSelf = false;
2115fe6060f1SDimitry Andric   bool SawSwiftAsync = false;
21160b57cec5SDimitry Andric   bool SawSwiftError = false;
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric   // Verify return value attributes.
2119349cc55cSDimitry Andric   AttributeSet RetAttrs = Attrs.getRetAttrs();
2120fe6060f1SDimitry Andric   for (Attribute RetAttr : RetAttrs)
212181ad6265SDimitry Andric     Check(RetAttr.isStringAttribute() ||
2122fe6060f1SDimitry Andric               Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2123fe6060f1SDimitry Andric           "Attribute '" + RetAttr.getAsString() +
2124fe6060f1SDimitry Andric               "' does not apply to function return values",
21250b57cec5SDimitry Andric           V);
2126fe6060f1SDimitry Andric 
21275f757f3fSDimitry Andric   unsigned MaxParameterWidth = 0;
21285f757f3fSDimitry Andric   auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
21295f757f3fSDimitry Andric     if (Ty->isVectorTy()) {
21305f757f3fSDimitry Andric       if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
21315f757f3fSDimitry Andric         unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
21325f757f3fSDimitry Andric         if (Size > MaxParameterWidth)
21335f757f3fSDimitry Andric           MaxParameterWidth = Size;
21345f757f3fSDimitry Andric       }
21355f757f3fSDimitry Andric     }
21365f757f3fSDimitry Andric   };
21375f757f3fSDimitry Andric   GetMaxParameterWidth(FT->getReturnType());
21380b57cec5SDimitry Andric   verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric   // Verify parameter attributes.
21410b57cec5SDimitry Andric   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
21420b57cec5SDimitry Andric     Type *Ty = FT->getParamType(i);
2143349cc55cSDimitry Andric     AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric     if (!IsIntrinsic) {
214681ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
21470b57cec5SDimitry Andric             "immarg attribute only applies to intrinsics", V);
214804eeddc0SDimitry Andric       if (!IsInlineAsm)
214981ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
215004eeddc0SDimitry Andric               "Attribute 'elementtype' can only be applied to intrinsics"
215181ad6265SDimitry Andric               " and inline asm.",
215281ad6265SDimitry Andric               V);
21530b57cec5SDimitry Andric     }
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     verifyParameterAttrs(ArgAttrs, Ty, V);
21565f757f3fSDimitry Andric     GetMaxParameterWidth(Ty);
21570b57cec5SDimitry Andric 
21580b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Nest)) {
215981ad6265SDimitry Andric       Check(!SawNest, "More than one parameter has attribute nest!", V);
21600b57cec5SDimitry Andric       SawNest = true;
21610b57cec5SDimitry Andric     }
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::Returned)) {
216481ad6265SDimitry Andric       Check(!SawReturned, "More than one parameter has attribute returned!", V);
216581ad6265SDimitry Andric       Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
21660b57cec5SDimitry Andric             "Incompatible argument and return types for 'returned' attribute",
21670b57cec5SDimitry Andric             V);
21680b57cec5SDimitry Andric       SawReturned = true;
21690b57cec5SDimitry Andric     }
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
217281ad6265SDimitry Andric       Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
217381ad6265SDimitry Andric       Check(i == 0 || i == 1,
21740b57cec5SDimitry Andric             "Attribute 'sret' is not on first or second parameter!", V);
21750b57cec5SDimitry Andric       SawSRet = true;
21760b57cec5SDimitry Andric     }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
217981ad6265SDimitry Andric       Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
21800b57cec5SDimitry Andric       SawSwiftSelf = true;
21810b57cec5SDimitry Andric     }
21820b57cec5SDimitry Andric 
2183fe6060f1SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
218481ad6265SDimitry Andric       Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2185fe6060f1SDimitry Andric       SawSwiftAsync = true;
2186fe6060f1SDimitry Andric     }
2187fe6060f1SDimitry Andric 
21880b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
218981ad6265SDimitry Andric       Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
21900b57cec5SDimitry Andric       SawSwiftError = true;
21910b57cec5SDimitry Andric     }
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric     if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
219481ad6265SDimitry Andric       Check(i == FT->getNumParams() - 1,
21950b57cec5SDimitry Andric             "inalloca isn't on the last parameter!", V);
21960b57cec5SDimitry Andric     }
21970b57cec5SDimitry Andric   }
21980b57cec5SDimitry Andric 
2199349cc55cSDimitry Andric   if (!Attrs.hasFnAttrs())
22000b57cec5SDimitry Andric     return;
22010b57cec5SDimitry Andric 
2202349cc55cSDimitry Andric   verifyAttributeTypes(Attrs.getFnAttrs(), V);
2203349cc55cSDimitry Andric   for (Attribute FnAttr : Attrs.getFnAttrs())
220481ad6265SDimitry Andric     Check(FnAttr.isStringAttribute() ||
2205fe6060f1SDimitry Andric               Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2206fe6060f1SDimitry Andric           "Attribute '" + FnAttr.getAsString() +
2207fe6060f1SDimitry Andric               "' does not apply to functions!",
2208fe6060f1SDimitry Andric           V);
22090b57cec5SDimitry Andric 
221081ad6265SDimitry Andric   Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2211349cc55cSDimitry Andric           Attrs.hasFnAttr(Attribute::AlwaysInline)),
22120b57cec5SDimitry Andric         "Attributes 'noinline and alwaysinline' are incompatible!", V);
22130b57cec5SDimitry Andric 
2214349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
221581ad6265SDimitry Andric     Check(Attrs.hasFnAttr(Attribute::NoInline),
22160b57cec5SDimitry Andric           "Attribute 'optnone' requires 'noinline'!", V);
22170b57cec5SDimitry Andric 
221881ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
22190b57cec5SDimitry Andric           "Attributes 'optsize and optnone' are incompatible!", V);
22200b57cec5SDimitry Andric 
222181ad6265SDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
22220b57cec5SDimitry Andric           "Attributes 'minsize and optnone' are incompatible!", V);
22235f757f3fSDimitry Andric 
22245f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
22255f757f3fSDimitry Andric           "Attributes 'optdebug and optnone' are incompatible!", V);
22260b57cec5SDimitry Andric   }
22270b57cec5SDimitry Andric 
22285f757f3fSDimitry Andric   if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
22295f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
22305f757f3fSDimitry Andric           "Attributes 'optsize and optdebug' are incompatible!", V);
22315f757f3fSDimitry Andric 
22325f757f3fSDimitry Andric     Check(!Attrs.hasFnAttr(Attribute::MinSize),
22335f757f3fSDimitry Andric           "Attributes 'minsize and optdebug' are incompatible!", V);
22345f757f3fSDimitry Andric   }
22355f757f3fSDimitry Andric 
22365f757f3fSDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
22375f757f3fSDimitry Andric         isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
22385f757f3fSDimitry Andric         "Attribute writable and memory without argmem: write are incompatible!",
22395f757f3fSDimitry Andric         V);
22405f757f3fSDimitry Andric 
2241bdd1243dSDimitry Andric   if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2242bdd1243dSDimitry Andric     Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2243bdd1243dSDimitry Andric            "Attributes 'aarch64_pstate_sm_enabled and "
2244bdd1243dSDimitry Andric            "aarch64_pstate_sm_compatible' are incompatible!",
2245bdd1243dSDimitry Andric            V);
2246bdd1243dSDimitry Andric   }
2247bdd1243dSDimitry Andric 
2248*0fca6ea1SDimitry Andric   Check((Attrs.hasFnAttr("aarch64_new_za") + Attrs.hasFnAttr("aarch64_in_za") +
2249*0fca6ea1SDimitry Andric          Attrs.hasFnAttr("aarch64_inout_za") +
2250*0fca6ea1SDimitry Andric          Attrs.hasFnAttr("aarch64_out_za") +
2251*0fca6ea1SDimitry Andric          Attrs.hasFnAttr("aarch64_preserves_za")) <= 1,
2252*0fca6ea1SDimitry Andric         "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2253*0fca6ea1SDimitry Andric         "'aarch64_inout_za' and 'aarch64_preserves_za' are mutually exclusive",
2254bdd1243dSDimitry Andric         V);
2255bdd1243dSDimitry Andric 
22567a6dacacSDimitry Andric   Check(
22577a6dacacSDimitry Andric       (Attrs.hasFnAttr("aarch64_new_zt0") + Attrs.hasFnAttr("aarch64_in_zt0") +
22587a6dacacSDimitry Andric        Attrs.hasFnAttr("aarch64_inout_zt0") +
22597a6dacacSDimitry Andric        Attrs.hasFnAttr("aarch64_out_zt0") +
22607a6dacacSDimitry Andric        Attrs.hasFnAttr("aarch64_preserves_zt0")) <= 1,
22617a6dacacSDimitry Andric       "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
22627a6dacacSDimitry Andric       "'aarch64_inout_zt0' and 'aarch64_preserves_zt0' are mutually exclusive",
22637a6dacacSDimitry Andric       V);
22647a6dacacSDimitry Andric 
2265349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::JumpTable)) {
22660b57cec5SDimitry Andric     const GlobalValue *GV = cast<GlobalValue>(V);
226781ad6265SDimitry Andric     Check(GV->hasGlobalUnnamedAddr(),
22680b57cec5SDimitry Andric           "Attribute 'jumptable' requires 'unnamed_addr'", V);
22690b57cec5SDimitry Andric   }
22700b57cec5SDimitry Andric 
2271bdd1243dSDimitry Andric   if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
22720b57cec5SDimitry Andric     auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
22730b57cec5SDimitry Andric       if (ParamNo >= FT->getNumParams()) {
22740b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
22750b57cec5SDimitry Andric         return false;
22760b57cec5SDimitry Andric       }
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric       if (!FT->getParamType(ParamNo)->isIntegerTy()) {
22790b57cec5SDimitry Andric         CheckFailed("'allocsize' " + Name +
22800b57cec5SDimitry Andric                         " argument must refer to an integer parameter",
22810b57cec5SDimitry Andric                     V);
22820b57cec5SDimitry Andric         return false;
22830b57cec5SDimitry Andric       }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric       return true;
22860b57cec5SDimitry Andric     };
22870b57cec5SDimitry Andric 
2288bdd1243dSDimitry Andric     if (!CheckParam("element size", Args->first))
22890b57cec5SDimitry Andric       return;
22900b57cec5SDimitry Andric 
2291bdd1243dSDimitry Andric     if (Args->second && !CheckParam("number of elements", *Args->second))
22920b57cec5SDimitry Andric       return;
22930b57cec5SDimitry Andric   }
2294480093f4SDimitry Andric 
229581ad6265SDimitry Andric   if (Attrs.hasFnAttr(Attribute::AllocKind)) {
229681ad6265SDimitry Andric     AllocFnKind K = Attrs.getAllocKind();
229781ad6265SDimitry Andric     AllocFnKind Type =
229881ad6265SDimitry Andric         K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
229981ad6265SDimitry Andric     if (!is_contained(
230081ad6265SDimitry Andric             {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
230181ad6265SDimitry Andric             Type))
230281ad6265SDimitry Andric       CheckFailed(
230381ad6265SDimitry Andric           "'allockind()' requires exactly one of alloc, realloc, and free");
230481ad6265SDimitry Andric     if ((Type == AllocFnKind::Free) &&
230581ad6265SDimitry Andric         ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
230681ad6265SDimitry Andric                AllocFnKind::Aligned)) != AllocFnKind::Unknown))
230781ad6265SDimitry Andric       CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
230881ad6265SDimitry Andric                   "or aligned modifiers.");
230981ad6265SDimitry Andric     AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
231081ad6265SDimitry Andric     if ((K & ZeroedUninit) == ZeroedUninit)
231181ad6265SDimitry Andric       CheckFailed("'allockind()' can't be both zeroed and uninitialized");
231281ad6265SDimitry Andric   }
231381ad6265SDimitry Andric 
2314349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
23150eae32dcSDimitry Andric     unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
23160eae32dcSDimitry Andric     if (VScaleMin == 0)
23170eae32dcSDimitry Andric       CheckFailed("'vscale_range' minimum must be greater than 0", V);
231806c3fb27SDimitry Andric     else if (!isPowerOf2_32(VScaleMin))
231906c3fb27SDimitry Andric       CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2320bdd1243dSDimitry Andric     std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
23210eae32dcSDimitry Andric     if (VScaleMax && VScaleMin > VScaleMax)
2322fe6060f1SDimitry Andric       CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
232306c3fb27SDimitry Andric     else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
232406c3fb27SDimitry Andric       CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2325fe6060f1SDimitry Andric   }
2326fe6060f1SDimitry Andric 
2327349cc55cSDimitry Andric   if (Attrs.hasFnAttr("frame-pointer")) {
2328349cc55cSDimitry Andric     StringRef FP = Attrs.getFnAttr("frame-pointer").getValueAsString();
2329*0fca6ea1SDimitry Andric     if (FP != "all" && FP != "non-leaf" && FP != "none" && FP != "reserved")
2330480093f4SDimitry Andric       CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2331480093f4SDimitry Andric   }
2332480093f4SDimitry Andric 
23335f757f3fSDimitry Andric   // Check EVEX512 feature.
23345f757f3fSDimitry Andric   if (MaxParameterWidth >= 512 && Attrs.hasFnAttr("target-features") &&
23355f757f3fSDimitry Andric       TT.isX86()) {
23365f757f3fSDimitry Andric     StringRef TF = Attrs.getFnAttr("target-features").getValueAsString();
23375f757f3fSDimitry Andric     Check(!TF.contains("+avx512f") || !TF.contains("-evex512"),
23385f757f3fSDimitry Andric           "512-bit vector arguments require 'evex512' for AVX512", V);
23395f757f3fSDimitry Andric   }
23405f757f3fSDimitry Andric 
2341fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2342fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2343fe6060f1SDimitry Andric   checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
23445f757f3fSDimitry Andric 
23455f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
23465f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
23475f757f3fSDimitry Andric     if (S != "none" && S != "all" && S != "non-leaf")
23485f757f3fSDimitry Andric       CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
23495f757f3fSDimitry Andric   }
23505f757f3fSDimitry Andric 
23515f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
23525f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
23535f757f3fSDimitry Andric     if (S != "a_key" && S != "b_key")
23545f757f3fSDimitry Andric       CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
23555f757f3fSDimitry Andric                   V);
2356*0fca6ea1SDimitry Andric     if (auto AA = Attrs.getFnAttr("sign-return-address"); !AA.isValid()) {
2357*0fca6ea1SDimitry Andric       CheckFailed(
2358*0fca6ea1SDimitry Andric           "'sign-return-address-key' present without `sign-return-address`");
2359*0fca6ea1SDimitry Andric     }
23605f757f3fSDimitry Andric   }
23615f757f3fSDimitry Andric 
23625f757f3fSDimitry Andric   if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
23635f757f3fSDimitry Andric     StringRef S = A.getValueAsString();
2364*0fca6ea1SDimitry Andric     if (S != "" && S != "true" && S != "false")
23655f757f3fSDimitry Andric       CheckFailed(
23665f757f3fSDimitry Andric           "invalid value for 'branch-target-enforcement' attribute: " + S, V);
23675f757f3fSDimitry Andric   }
23687a6dacacSDimitry Andric 
2369*0fca6ea1SDimitry Andric   if (auto A = Attrs.getFnAttr("branch-protection-pauth-lr"); A.isValid()) {
2370*0fca6ea1SDimitry Andric     StringRef S = A.getValueAsString();
2371*0fca6ea1SDimitry Andric     if (S != "" && S != "true" && S != "false")
2372*0fca6ea1SDimitry Andric       CheckFailed(
2373*0fca6ea1SDimitry Andric           "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2374*0fca6ea1SDimitry Andric   }
2375*0fca6ea1SDimitry Andric 
2376*0fca6ea1SDimitry Andric   if (auto A = Attrs.getFnAttr("guarded-control-stack"); A.isValid()) {
2377*0fca6ea1SDimitry Andric     StringRef S = A.getValueAsString();
2378*0fca6ea1SDimitry Andric     if (S != "" && S != "true" && S != "false")
2379*0fca6ea1SDimitry Andric       CheckFailed("invalid value for 'guarded-control-stack' attribute: " + S,
2380*0fca6ea1SDimitry Andric                   V);
2381*0fca6ea1SDimitry Andric   }
2382*0fca6ea1SDimitry Andric 
23837a6dacacSDimitry Andric   if (auto A = Attrs.getFnAttr("vector-function-abi-variant"); A.isValid()) {
23847a6dacacSDimitry Andric     StringRef S = A.getValueAsString();
23857a6dacacSDimitry Andric     const std::optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, FT);
23867a6dacacSDimitry Andric     if (!Info)
23877a6dacacSDimitry Andric       CheckFailed("invalid name for a VFABI variant: " + S, V);
23887a6dacacSDimitry Andric   }
23890b57cec5SDimitry Andric }
23900b57cec5SDimitry Andric 
verifyFunctionMetadata(ArrayRef<std::pair<unsigned,MDNode * >> MDs)23910b57cec5SDimitry Andric void Verifier::verifyFunctionMetadata(
23920b57cec5SDimitry Andric     ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
23930b57cec5SDimitry Andric   for (const auto &Pair : MDs) {
23940b57cec5SDimitry Andric     if (Pair.first == LLVMContext::MD_prof) {
23950b57cec5SDimitry Andric       MDNode *MD = Pair.second;
239681ad6265SDimitry Andric       Check(MD->getNumOperands() >= 2,
23970b57cec5SDimitry Andric             "!prof annotations should have no less than 2 operands", MD);
23980b57cec5SDimitry Andric 
23990b57cec5SDimitry Andric       // Check first operand.
240081ad6265SDimitry Andric       Check(MD->getOperand(0) != nullptr, "first operand should not be null",
24010b57cec5SDimitry Andric             MD);
240281ad6265SDimitry Andric       Check(isa<MDString>(MD->getOperand(0)),
24030b57cec5SDimitry Andric             "expected string with name of the !prof annotation", MD);
24040b57cec5SDimitry Andric       MDString *MDS = cast<MDString>(MD->getOperand(0));
24050b57cec5SDimitry Andric       StringRef ProfName = MDS->getString();
2406*0fca6ea1SDimitry Andric       Check(ProfName == "function_entry_count" ||
2407*0fca6ea1SDimitry Andric                 ProfName == "synthetic_function_entry_count",
24080b57cec5SDimitry Andric             "first operand should be 'function_entry_count'"
24090b57cec5SDimitry Andric             " or 'synthetic_function_entry_count'",
24100b57cec5SDimitry Andric             MD);
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric       // Check second operand.
241381ad6265SDimitry Andric       Check(MD->getOperand(1) != nullptr, "second operand should not be null",
24140b57cec5SDimitry Andric             MD);
241581ad6265SDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(1)),
24160b57cec5SDimitry Andric             "expected integer argument to function_entry_count", MD);
2417bdd1243dSDimitry Andric     } else if (Pair.first == LLVMContext::MD_kcfi_type) {
2418bdd1243dSDimitry Andric       MDNode *MD = Pair.second;
2419bdd1243dSDimitry Andric       Check(MD->getNumOperands() == 1,
2420bdd1243dSDimitry Andric             "!kcfi_type must have exactly one operand", MD);
2421bdd1243dSDimitry Andric       Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
2422bdd1243dSDimitry Andric             MD);
2423bdd1243dSDimitry Andric       Check(isa<ConstantAsMetadata>(MD->getOperand(0)),
2424bdd1243dSDimitry Andric             "expected a constant operand for !kcfi_type", MD);
2425bdd1243dSDimitry Andric       Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
2426cb14a3feSDimitry Andric       Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
2427bdd1243dSDimitry Andric             "expected a constant integer operand for !kcfi_type", MD);
2428cb14a3feSDimitry Andric       Check(cast<ConstantInt>(C)->getBitWidth() == 32,
2429bdd1243dSDimitry Andric             "expected a 32-bit integer constant operand for !kcfi_type", MD);
24300b57cec5SDimitry Andric     }
24310b57cec5SDimitry Andric   }
24320b57cec5SDimitry Andric }
24330b57cec5SDimitry Andric 
visitConstantExprsRecursively(const Constant * EntryC)24340b57cec5SDimitry Andric void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
24350b57cec5SDimitry Andric   if (!ConstantExprVisited.insert(EntryC).second)
24360b57cec5SDimitry Andric     return;
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric   SmallVector<const Constant *, 16> Stack;
24390b57cec5SDimitry Andric   Stack.push_back(EntryC);
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric   while (!Stack.empty()) {
24420b57cec5SDimitry Andric     const Constant *C = Stack.pop_back_val();
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric     // Check this constant expression.
24450b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<ConstantExpr>(C))
24460b57cec5SDimitry Andric       visitConstantExpr(CE);
24470b57cec5SDimitry Andric 
2448*0fca6ea1SDimitry Andric     if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C))
2449*0fca6ea1SDimitry Andric       visitConstantPtrAuth(CPA);
2450*0fca6ea1SDimitry Andric 
24510b57cec5SDimitry Andric     if (const auto *GV = dyn_cast<GlobalValue>(C)) {
24520b57cec5SDimitry Andric       // Global Values get visited separately, but we do need to make sure
24530b57cec5SDimitry Andric       // that the global value is in the correct module
245481ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!",
24550b57cec5SDimitry Andric             EntryC, &M, GV, GV->getParent());
24560b57cec5SDimitry Andric       continue;
24570b57cec5SDimitry Andric     }
24580b57cec5SDimitry Andric 
24590b57cec5SDimitry Andric     // Visit all sub-expressions.
24600b57cec5SDimitry Andric     for (const Use &U : C->operands()) {
24610b57cec5SDimitry Andric       const auto *OpC = dyn_cast<Constant>(U);
24620b57cec5SDimitry Andric       if (!OpC)
24630b57cec5SDimitry Andric         continue;
24640b57cec5SDimitry Andric       if (!ConstantExprVisited.insert(OpC).second)
24650b57cec5SDimitry Andric         continue;
24660b57cec5SDimitry Andric       Stack.push_back(OpC);
24670b57cec5SDimitry Andric     }
24680b57cec5SDimitry Andric   }
24690b57cec5SDimitry Andric }
24700b57cec5SDimitry Andric 
visitConstantExpr(const ConstantExpr * CE)24710b57cec5SDimitry Andric void Verifier::visitConstantExpr(const ConstantExpr *CE) {
24720b57cec5SDimitry Andric   if (CE->getOpcode() == Instruction::BitCast)
247381ad6265SDimitry Andric     Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
24740b57cec5SDimitry Andric                                 CE->getType()),
24750b57cec5SDimitry Andric           "Invalid bitcast", CE);
24760b57cec5SDimitry Andric }
24770b57cec5SDimitry Andric 
visitConstantPtrAuth(const ConstantPtrAuth * CPA)2478*0fca6ea1SDimitry Andric void Verifier::visitConstantPtrAuth(const ConstantPtrAuth *CPA) {
2479*0fca6ea1SDimitry Andric   Check(CPA->getPointer()->getType()->isPointerTy(),
2480*0fca6ea1SDimitry Andric         "signed ptrauth constant base pointer must have pointer type");
2481*0fca6ea1SDimitry Andric 
2482*0fca6ea1SDimitry Andric   Check(CPA->getType() == CPA->getPointer()->getType(),
2483*0fca6ea1SDimitry Andric         "signed ptrauth constant must have same type as its base pointer");
2484*0fca6ea1SDimitry Andric 
2485*0fca6ea1SDimitry Andric   Check(CPA->getKey()->getBitWidth() == 32,
2486*0fca6ea1SDimitry Andric         "signed ptrauth constant key must be i32 constant integer");
2487*0fca6ea1SDimitry Andric 
2488*0fca6ea1SDimitry Andric   Check(CPA->getAddrDiscriminator()->getType()->isPointerTy(),
2489*0fca6ea1SDimitry Andric         "signed ptrauth constant address discriminator must be a pointer");
2490*0fca6ea1SDimitry Andric 
2491*0fca6ea1SDimitry Andric   Check(CPA->getDiscriminator()->getBitWidth() == 64,
2492*0fca6ea1SDimitry Andric         "signed ptrauth constant discriminator must be i64 constant integer");
2493*0fca6ea1SDimitry Andric }
2494*0fca6ea1SDimitry Andric 
verifyAttributeCount(AttributeList Attrs,unsigned Params)24950b57cec5SDimitry Andric bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
24960b57cec5SDimitry Andric   // There shouldn't be more attribute sets than there are parameters plus the
24970b57cec5SDimitry Andric   // function and return value.
24980b57cec5SDimitry Andric   return Attrs.getNumAttrSets() <= Params + 2;
24990b57cec5SDimitry Andric }
25000b57cec5SDimitry Andric 
verifyInlineAsmCall(const CallBase & Call)250104eeddc0SDimitry Andric void Verifier::verifyInlineAsmCall(const CallBase &Call) {
250204eeddc0SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
250304eeddc0SDimitry Andric   unsigned ArgNo = 0;
2504fcaf7f86SDimitry Andric   unsigned LabelNo = 0;
250504eeddc0SDimitry Andric   for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2506fcaf7f86SDimitry Andric     if (CI.Type == InlineAsm::isLabel) {
2507fcaf7f86SDimitry Andric       ++LabelNo;
2508fcaf7f86SDimitry Andric       continue;
2509fcaf7f86SDimitry Andric     }
2510fcaf7f86SDimitry Andric 
251104eeddc0SDimitry Andric     // Only deal with constraints that correspond to call arguments.
251204eeddc0SDimitry Andric     if (!CI.hasArg())
251304eeddc0SDimitry Andric       continue;
251404eeddc0SDimitry Andric 
251504eeddc0SDimitry Andric     if (CI.isIndirect) {
251604eeddc0SDimitry Andric       const Value *Arg = Call.getArgOperand(ArgNo);
251781ad6265SDimitry Andric       Check(Arg->getType()->isPointerTy(),
251881ad6265SDimitry Andric             "Operand for indirect constraint must have pointer type", &Call);
251904eeddc0SDimitry Andric 
252081ad6265SDimitry Andric       Check(Call.getParamElementType(ArgNo),
252104eeddc0SDimitry Andric             "Operand for indirect constraint must have elementtype attribute",
252204eeddc0SDimitry Andric             &Call);
252304eeddc0SDimitry Andric     } else {
252481ad6265SDimitry Andric       Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
252504eeddc0SDimitry Andric             "Elementtype attribute can only be applied for indirect "
252681ad6265SDimitry Andric             "constraints",
252781ad6265SDimitry Andric             &Call);
252804eeddc0SDimitry Andric     }
252904eeddc0SDimitry Andric 
253004eeddc0SDimitry Andric     ArgNo++;
253104eeddc0SDimitry Andric   }
2532fcaf7f86SDimitry Andric 
2533fcaf7f86SDimitry Andric   if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2534fcaf7f86SDimitry Andric     Check(LabelNo == CallBr->getNumIndirectDests(),
2535fcaf7f86SDimitry Andric           "Number of label constraints does not match number of callbr dests",
2536fcaf7f86SDimitry Andric           &Call);
2537fcaf7f86SDimitry Andric   } else {
2538fcaf7f86SDimitry Andric     Check(LabelNo == 0, "Label constraints can only be used with callbr",
2539fcaf7f86SDimitry Andric           &Call);
2540fcaf7f86SDimitry Andric   }
254104eeddc0SDimitry Andric }
254204eeddc0SDimitry Andric 
25430b57cec5SDimitry Andric /// Verify that statepoint intrinsic is well formed.
verifyStatepoint(const CallBase & Call)25440b57cec5SDimitry Andric void Verifier::verifyStatepoint(const CallBase &Call) {
25450b57cec5SDimitry Andric   assert(Call.getCalledFunction() &&
25460b57cec5SDimitry Andric          Call.getCalledFunction()->getIntrinsicID() ==
25470b57cec5SDimitry Andric              Intrinsic::experimental_gc_statepoint);
25480b57cec5SDimitry Andric 
254981ad6265SDimitry Andric   Check(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() &&
25500b57cec5SDimitry Andric             !Call.onlyAccessesArgMemory(),
25510b57cec5SDimitry Andric         "gc.statepoint must read and write all memory to preserve "
25520b57cec5SDimitry Andric         "reordering restrictions required by safepoint semantics",
25530b57cec5SDimitry Andric         Call);
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric   const int64_t NumPatchBytes =
25560b57cec5SDimitry Andric       cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
25570b57cec5SDimitry Andric   assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
255881ad6265SDimitry Andric   Check(NumPatchBytes >= 0,
25590b57cec5SDimitry Andric         "gc.statepoint number of patchable bytes must be "
25600b57cec5SDimitry Andric         "positive",
25610b57cec5SDimitry Andric         Call);
25620b57cec5SDimitry Andric 
256381ad6265SDimitry Andric   Type *TargetElemType = Call.getParamElementType(2);
256481ad6265SDimitry Andric   Check(TargetElemType,
256581ad6265SDimitry Andric         "gc.statepoint callee argument must have elementtype attribute", Call);
256681ad6265SDimitry Andric   FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
256781ad6265SDimitry Andric   Check(TargetFuncType,
256881ad6265SDimitry Andric         "gc.statepoint callee elementtype must be function type", Call);
25690b57cec5SDimitry Andric 
25700b57cec5SDimitry Andric   const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
257181ad6265SDimitry Andric   Check(NumCallArgs >= 0,
25720b57cec5SDimitry Andric         "gc.statepoint number of arguments to underlying call "
25730b57cec5SDimitry Andric         "must be positive",
25740b57cec5SDimitry Andric         Call);
25750b57cec5SDimitry Andric   const int NumParams = (int)TargetFuncType->getNumParams();
25760b57cec5SDimitry Andric   if (TargetFuncType->isVarArg()) {
257781ad6265SDimitry Andric     Check(NumCallArgs >= NumParams,
25780b57cec5SDimitry Andric           "gc.statepoint mismatch in number of vararg call args", Call);
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric     // TODO: Remove this limitation
258181ad6265SDimitry Andric     Check(TargetFuncType->getReturnType()->isVoidTy(),
25820b57cec5SDimitry Andric           "gc.statepoint doesn't support wrapping non-void "
25830b57cec5SDimitry Andric           "vararg functions yet",
25840b57cec5SDimitry Andric           Call);
25850b57cec5SDimitry Andric   } else
258681ad6265SDimitry Andric     Check(NumCallArgs == NumParams,
25870b57cec5SDimitry Andric           "gc.statepoint mismatch in number of call args", Call);
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   const uint64_t Flags
25900b57cec5SDimitry Andric     = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
259181ad6265SDimitry Andric   Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
25920b57cec5SDimitry Andric         "unknown flag used in gc.statepoint flags argument", Call);
25930b57cec5SDimitry Andric 
25940b57cec5SDimitry Andric   // Verify that the types of the call parameter arguments match
25950b57cec5SDimitry Andric   // the type of the wrapped callee.
25960b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
25970b57cec5SDimitry Andric   for (int i = 0; i < NumParams; i++) {
25980b57cec5SDimitry Andric     Type *ParamType = TargetFuncType->getParamType(i);
25990b57cec5SDimitry Andric     Type *ArgType = Call.getArgOperand(5 + i)->getType();
260081ad6265SDimitry Andric     Check(ArgType == ParamType,
26010b57cec5SDimitry Andric           "gc.statepoint call argument does not match wrapped "
26020b57cec5SDimitry Andric           "function type",
26030b57cec5SDimitry Andric           Call);
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric     if (TargetFuncType->isVarArg()) {
2606349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
260781ad6265SDimitry Andric       Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
260881ad6265SDimitry Andric             "Attribute 'sret' cannot be used for vararg call arguments!", Call);
26090b57cec5SDimitry Andric     }
26100b57cec5SDimitry Andric   }
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric   const int EndCallArgsInx = 4 + NumCallArgs;
26130b57cec5SDimitry Andric 
26140b57cec5SDimitry Andric   const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
261581ad6265SDimitry Andric   Check(isa<ConstantInt>(NumTransitionArgsV),
26160b57cec5SDimitry Andric         "gc.statepoint number of transition arguments "
26170b57cec5SDimitry Andric         "must be constant integer",
26180b57cec5SDimitry Andric         Call);
26190b57cec5SDimitry Andric   const int NumTransitionArgs =
26200b57cec5SDimitry Andric       cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
262181ad6265SDimitry Andric   Check(NumTransitionArgs == 0,
2622e8d8bef9SDimitry Andric         "gc.statepoint w/inline transition bundle is deprecated", Call);
2623e8d8bef9SDimitry Andric   const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
26245ffd83dbSDimitry Andric 
26250b57cec5SDimitry Andric   const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
262681ad6265SDimitry Andric   Check(isa<ConstantInt>(NumDeoptArgsV),
26270b57cec5SDimitry Andric         "gc.statepoint number of deoptimization arguments "
26280b57cec5SDimitry Andric         "must be constant integer",
26290b57cec5SDimitry Andric         Call);
26300b57cec5SDimitry Andric   const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
263181ad6265SDimitry Andric   Check(NumDeoptArgs == 0,
2632e8d8bef9SDimitry Andric         "gc.statepoint w/inline deopt operands is deprecated", Call);
26335ffd83dbSDimitry Andric 
2634e8d8bef9SDimitry Andric   const int ExpectedNumArgs = 7 + NumCallArgs;
263581ad6265SDimitry Andric   Check(ExpectedNumArgs == (int)Call.arg_size(),
2636e8d8bef9SDimitry Andric         "gc.statepoint too many arguments", Call);
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric   // Check that the only uses of this gc.statepoint are gc.result or
26390b57cec5SDimitry Andric   // gc.relocate calls which are tied to this statepoint and thus part
26400b57cec5SDimitry Andric   // of the same statepoint sequence
26410b57cec5SDimitry Andric   for (const User *U : Call.users()) {
26420b57cec5SDimitry Andric     const CallInst *UserCall = dyn_cast<const CallInst>(U);
264381ad6265SDimitry Andric     Check(UserCall, "illegal use of statepoint token", Call, U);
26440b57cec5SDimitry Andric     if (!UserCall)
26450b57cec5SDimitry Andric       continue;
264681ad6265SDimitry Andric     Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
26470b57cec5SDimitry Andric           "gc.result or gc.relocate are the only value uses "
26480b57cec5SDimitry Andric           "of a gc.statepoint",
26490b57cec5SDimitry Andric           Call, U);
26500b57cec5SDimitry Andric     if (isa<GCResultInst>(UserCall)) {
265181ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
26520b57cec5SDimitry Andric             "gc.result connected to wrong gc.statepoint", Call, UserCall);
26530b57cec5SDimitry Andric     } else if (isa<GCRelocateInst>(Call)) {
265481ad6265SDimitry Andric       Check(UserCall->getArgOperand(0) == &Call,
26550b57cec5SDimitry Andric             "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
26560b57cec5SDimitry Andric     }
26570b57cec5SDimitry Andric   }
26580b57cec5SDimitry Andric 
26590b57cec5SDimitry Andric   // Note: It is legal for a single derived pointer to be listed multiple
26600b57cec5SDimitry Andric   // times.  It's non-optimal, but it is legal.  It can also happen after
26610b57cec5SDimitry Andric   // insertion if we strip a bitcast away.
26620b57cec5SDimitry Andric   // Note: It is really tempting to check that each base is relocated and
26630b57cec5SDimitry Andric   // that a derived pointer is never reused as a base pointer.  This turns
26640b57cec5SDimitry Andric   // out to be problematic since optimizations run after safepoint insertion
26650b57cec5SDimitry Andric   // can recognize equality properties that the insertion logic doesn't know
26660b57cec5SDimitry Andric   // about.  See example statepoint.ll in the verifier subdirectory
26670b57cec5SDimitry Andric }
26680b57cec5SDimitry Andric 
verifyFrameRecoverIndices()26690b57cec5SDimitry Andric void Verifier::verifyFrameRecoverIndices() {
26700b57cec5SDimitry Andric   for (auto &Counts : FrameEscapeInfo) {
26710b57cec5SDimitry Andric     Function *F = Counts.first;
26720b57cec5SDimitry Andric     unsigned EscapedObjectCount = Counts.second.first;
26730b57cec5SDimitry Andric     unsigned MaxRecoveredIndex = Counts.second.second;
267481ad6265SDimitry Andric     Check(MaxRecoveredIndex <= EscapedObjectCount,
26750b57cec5SDimitry Andric           "all indices passed to llvm.localrecover must be less than the "
26760b57cec5SDimitry Andric           "number of arguments passed to llvm.localescape in the parent "
26770b57cec5SDimitry Andric           "function",
26780b57cec5SDimitry Andric           F);
26790b57cec5SDimitry Andric   }
26800b57cec5SDimitry Andric }
26810b57cec5SDimitry Andric 
getSuccPad(Instruction * Terminator)26820b57cec5SDimitry Andric static Instruction *getSuccPad(Instruction *Terminator) {
26830b57cec5SDimitry Andric   BasicBlock *UnwindDest;
26840b57cec5SDimitry Andric   if (auto *II = dyn_cast<InvokeInst>(Terminator))
26850b57cec5SDimitry Andric     UnwindDest = II->getUnwindDest();
26860b57cec5SDimitry Andric   else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
26870b57cec5SDimitry Andric     UnwindDest = CSI->getUnwindDest();
26880b57cec5SDimitry Andric   else
26890b57cec5SDimitry Andric     UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
26900b57cec5SDimitry Andric   return UnwindDest->getFirstNonPHI();
26910b57cec5SDimitry Andric }
26920b57cec5SDimitry Andric 
verifySiblingFuncletUnwinds()26930b57cec5SDimitry Andric void Verifier::verifySiblingFuncletUnwinds() {
26940b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Visited;
26950b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 8> Active;
26960b57cec5SDimitry Andric   for (const auto &Pair : SiblingFuncletInfo) {
26970b57cec5SDimitry Andric     Instruction *PredPad = Pair.first;
26980b57cec5SDimitry Andric     if (Visited.count(PredPad))
26990b57cec5SDimitry Andric       continue;
27000b57cec5SDimitry Andric     Active.insert(PredPad);
27010b57cec5SDimitry Andric     Instruction *Terminator = Pair.second;
27020b57cec5SDimitry Andric     do {
27030b57cec5SDimitry Andric       Instruction *SuccPad = getSuccPad(Terminator);
27040b57cec5SDimitry Andric       if (Active.count(SuccPad)) {
27050b57cec5SDimitry Andric         // Found a cycle; report error
27060b57cec5SDimitry Andric         Instruction *CyclePad = SuccPad;
27070b57cec5SDimitry Andric         SmallVector<Instruction *, 8> CycleNodes;
27080b57cec5SDimitry Andric         do {
27090b57cec5SDimitry Andric           CycleNodes.push_back(CyclePad);
27100b57cec5SDimitry Andric           Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
27110b57cec5SDimitry Andric           if (CycleTerminator != CyclePad)
27120b57cec5SDimitry Andric             CycleNodes.push_back(CycleTerminator);
27130b57cec5SDimitry Andric           CyclePad = getSuccPad(CycleTerminator);
27140b57cec5SDimitry Andric         } while (CyclePad != SuccPad);
271581ad6265SDimitry Andric         Check(false, "EH pads can't handle each other's exceptions",
27160b57cec5SDimitry Andric               ArrayRef<Instruction *>(CycleNodes));
27170b57cec5SDimitry Andric       }
27180b57cec5SDimitry Andric       // Don't re-walk a node we've already checked
27190b57cec5SDimitry Andric       if (!Visited.insert(SuccPad).second)
27200b57cec5SDimitry Andric         break;
27210b57cec5SDimitry Andric       // Walk to this successor if it has a map entry.
27220b57cec5SDimitry Andric       PredPad = SuccPad;
27230b57cec5SDimitry Andric       auto TermI = SiblingFuncletInfo.find(PredPad);
27240b57cec5SDimitry Andric       if (TermI == SiblingFuncletInfo.end())
27250b57cec5SDimitry Andric         break;
27260b57cec5SDimitry Andric       Terminator = TermI->second;
27270b57cec5SDimitry Andric       Active.insert(PredPad);
27280b57cec5SDimitry Andric     } while (true);
27290b57cec5SDimitry Andric     // Each node only has one successor, so we've walked all the active
27300b57cec5SDimitry Andric     // nodes' successors.
27310b57cec5SDimitry Andric     Active.clear();
27320b57cec5SDimitry Andric   }
27330b57cec5SDimitry Andric }
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric // visitFunction - Verify that a function is ok.
27360b57cec5SDimitry Andric //
visitFunction(const Function & F)27370b57cec5SDimitry Andric void Verifier::visitFunction(const Function &F) {
27380b57cec5SDimitry Andric   visitGlobalValue(F);
27390b57cec5SDimitry Andric 
27400b57cec5SDimitry Andric   // Check function arguments.
27410b57cec5SDimitry Andric   FunctionType *FT = F.getFunctionType();
27420b57cec5SDimitry Andric   unsigned NumArgs = F.arg_size();
27430b57cec5SDimitry Andric 
274481ad6265SDimitry Andric   Check(&Context == &F.getContext(),
27450b57cec5SDimitry Andric         "Function context does not match Module context!", &F);
27460b57cec5SDimitry Andric 
274781ad6265SDimitry Andric   Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
274881ad6265SDimitry Andric   Check(FT->getNumParams() == NumArgs,
27490b57cec5SDimitry Andric         "# formal arguments must match # of arguments for function type!", &F,
27500b57cec5SDimitry Andric         FT);
275181ad6265SDimitry Andric   Check(F.getReturnType()->isFirstClassType() ||
27520b57cec5SDimitry Andric             F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
27530b57cec5SDimitry Andric         "Functions cannot return aggregate values!", &F);
27540b57cec5SDimitry Andric 
275581ad6265SDimitry Andric   Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
27560b57cec5SDimitry Andric         "Invalid struct return type!", &F);
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric   AttributeList Attrs = F.getAttributes();
27590b57cec5SDimitry Andric 
276081ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, FT->getNumParams()),
27610b57cec5SDimitry Andric         "Attribute after last parameter!", &F);
27620b57cec5SDimitry Andric 
2763*0fca6ea1SDimitry Andric   CheckDI(F.IsNewDbgInfoFormat == F.getParent()->IsNewDbgInfoFormat,
2764*0fca6ea1SDimitry Andric           "Function debug format should match parent module", &F,
2765*0fca6ea1SDimitry Andric           F.IsNewDbgInfoFormat, F.getParent(),
2766*0fca6ea1SDimitry Andric           F.getParent()->IsNewDbgInfoFormat);
2767*0fca6ea1SDimitry Andric 
2768fe6060f1SDimitry Andric   bool IsIntrinsic = F.isIntrinsic();
27690b57cec5SDimitry Andric 
27700b57cec5SDimitry Andric   // Check function attributes.
277104eeddc0SDimitry Andric   verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
27720b57cec5SDimitry Andric 
27730b57cec5SDimitry Andric   // On function declarations/definitions, we do not support the builtin
27740b57cec5SDimitry Andric   // attribute. We do not check this in VerifyFunctionAttrs since that is
27750b57cec5SDimitry Andric   // checking for Attributes that can/can not ever be on functions.
277681ad6265SDimitry Andric   Check(!Attrs.hasFnAttr(Attribute::Builtin),
27770b57cec5SDimitry Andric         "Attribute 'builtin' can only be applied to a callsite.", &F);
27780b57cec5SDimitry Andric 
277981ad6265SDimitry Andric   Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
2780fe6060f1SDimitry Andric         "Attribute 'elementtype' can only be applied to a callsite.", &F);
2781fe6060f1SDimitry Andric 
27820b57cec5SDimitry Andric   // Check that this function meets the restrictions on this calling convention.
27830b57cec5SDimitry Andric   // Sometimes varargs is used for perfectly forwarding thunks, so some of these
27840b57cec5SDimitry Andric   // restrictions can be lifted.
27850b57cec5SDimitry Andric   switch (F.getCallingConv()) {
27860b57cec5SDimitry Andric   default:
27870b57cec5SDimitry Andric   case CallingConv::C:
27880b57cec5SDimitry Andric     break;
2789e8d8bef9SDimitry Andric   case CallingConv::X86_INTR: {
279081ad6265SDimitry Andric     Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
2791e8d8bef9SDimitry Andric           "Calling convention parameter requires byval", &F);
2792e8d8bef9SDimitry Andric     break;
2793e8d8bef9SDimitry Andric   }
27940b57cec5SDimitry Andric   case CallingConv::AMDGPU_KERNEL:
27950b57cec5SDimitry Andric   case CallingConv::SPIR_KERNEL:
279606c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_Chain:
279706c3fb27SDimitry Andric   case CallingConv::AMDGPU_CS_ChainPreserve:
279881ad6265SDimitry Andric     Check(F.getReturnType()->isVoidTy(),
27990b57cec5SDimitry Andric           "Calling convention requires void return type", &F);
2800bdd1243dSDimitry Andric     [[fallthrough]];
28010b57cec5SDimitry Andric   case CallingConv::AMDGPU_VS:
28020b57cec5SDimitry Andric   case CallingConv::AMDGPU_HS:
28030b57cec5SDimitry Andric   case CallingConv::AMDGPU_GS:
28040b57cec5SDimitry Andric   case CallingConv::AMDGPU_PS:
28050b57cec5SDimitry Andric   case CallingConv::AMDGPU_CS:
280681ad6265SDimitry Andric     Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
2807e8d8bef9SDimitry Andric     if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
2808e8d8bef9SDimitry Andric       const unsigned StackAS = DL.getAllocaAddrSpace();
2809e8d8bef9SDimitry Andric       unsigned i = 0;
2810e8d8bef9SDimitry Andric       for (const Argument &Arg : F.args()) {
281181ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
2812e8d8bef9SDimitry Andric               "Calling convention disallows byval", &F);
281381ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
2814e8d8bef9SDimitry Andric               "Calling convention disallows preallocated", &F);
281581ad6265SDimitry Andric         Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
2816e8d8bef9SDimitry Andric               "Calling convention disallows inalloca", &F);
2817e8d8bef9SDimitry Andric 
2818349cc55cSDimitry Andric         if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
2819e8d8bef9SDimitry Andric           // FIXME: Should also disallow LDS and GDS, but we don't have the enum
2820e8d8bef9SDimitry Andric           // value here.
282181ad6265SDimitry Andric           Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2822e8d8bef9SDimitry Andric                 "Calling convention disallows stack byref", &F);
2823e8d8bef9SDimitry Andric         }
2824e8d8bef9SDimitry Andric 
2825e8d8bef9SDimitry Andric         ++i;
2826e8d8bef9SDimitry Andric       }
2827e8d8bef9SDimitry Andric     }
2828e8d8bef9SDimitry Andric 
2829bdd1243dSDimitry Andric     [[fallthrough]];
28300b57cec5SDimitry Andric   case CallingConv::Fast:
28310b57cec5SDimitry Andric   case CallingConv::Cold:
28320b57cec5SDimitry Andric   case CallingConv::Intel_OCL_BI:
28330b57cec5SDimitry Andric   case CallingConv::PTX_Kernel:
28340b57cec5SDimitry Andric   case CallingConv::PTX_Device:
283581ad6265SDimitry Andric     Check(!F.isVarArg(),
283681ad6265SDimitry Andric           "Calling convention does not support varargs or "
28370b57cec5SDimitry Andric           "perfect forwarding!",
28380b57cec5SDimitry Andric           &F);
28390b57cec5SDimitry Andric     break;
28400b57cec5SDimitry Andric   }
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   // Check that the argument values match the function type for this function...
28430b57cec5SDimitry Andric   unsigned i = 0;
28440b57cec5SDimitry Andric   for (const Argument &Arg : F.args()) {
284581ad6265SDimitry Andric     Check(Arg.getType() == FT->getParamType(i),
28460b57cec5SDimitry Andric           "Argument value does not match function argument type!", &Arg,
28470b57cec5SDimitry Andric           FT->getParamType(i));
284881ad6265SDimitry Andric     Check(Arg.getType()->isFirstClassType(),
28490b57cec5SDimitry Andric           "Function arguments must have first-class types!", &Arg);
2850fe6060f1SDimitry Andric     if (!IsIntrinsic) {
285181ad6265SDimitry Andric       Check(!Arg.getType()->isMetadataTy(),
28520b57cec5SDimitry Andric             "Function takes metadata but isn't an intrinsic", &Arg, &F);
285381ad6265SDimitry Andric       Check(!Arg.getType()->isTokenTy(),
28540b57cec5SDimitry Andric             "Function takes token but isn't an intrinsic", &Arg, &F);
285581ad6265SDimitry Andric       Check(!Arg.getType()->isX86_AMXTy(),
2856fe6060f1SDimitry Andric             "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
28570b57cec5SDimitry Andric     }
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric     // Check that swifterror argument is only used by loads and stores.
2860349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
28610b57cec5SDimitry Andric       verifySwiftErrorValue(&Arg);
28620b57cec5SDimitry Andric     }
28630b57cec5SDimitry Andric     ++i;
28640b57cec5SDimitry Andric   }
28650b57cec5SDimitry Andric 
2866fe6060f1SDimitry Andric   if (!IsIntrinsic) {
286781ad6265SDimitry Andric     Check(!F.getReturnType()->isTokenTy(),
2868fe6060f1SDimitry Andric           "Function returns a token but isn't an intrinsic", &F);
286981ad6265SDimitry Andric     Check(!F.getReturnType()->isX86_AMXTy(),
2870fe6060f1SDimitry Andric           "Function returns a x86_amx but isn't an intrinsic", &F);
2871fe6060f1SDimitry Andric   }
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric   // Get the function metadata attachments.
28740b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
28750b57cec5SDimitry Andric   F.getAllMetadata(MDs);
28760b57cec5SDimitry Andric   assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
28770b57cec5SDimitry Andric   verifyFunctionMetadata(MDs);
28780b57cec5SDimitry Andric 
28790b57cec5SDimitry Andric   // Check validity of the personality function
28800b57cec5SDimitry Andric   if (F.hasPersonalityFn()) {
28810b57cec5SDimitry Andric     auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
28820b57cec5SDimitry Andric     if (Per)
288381ad6265SDimitry Andric       Check(Per->getParent() == F.getParent(),
288481ad6265SDimitry Andric             "Referencing personality function in another module!", &F,
288581ad6265SDimitry Andric             F.getParent(), Per, Per->getParent());
28860b57cec5SDimitry Andric   }
28870b57cec5SDimitry Andric 
288806c3fb27SDimitry Andric   // EH funclet coloring can be expensive, recompute on-demand
288906c3fb27SDimitry Andric   BlockEHFuncletColors.clear();
289006c3fb27SDimitry Andric 
28910b57cec5SDimitry Andric   if (F.isMaterializable()) {
28920b57cec5SDimitry Andric     // Function has a body somewhere we can't see.
289381ad6265SDimitry Andric     Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
28940b57cec5SDimitry Andric           MDs.empty() ? nullptr : MDs.front().second);
28950b57cec5SDimitry Andric   } else if (F.isDeclaration()) {
28960b57cec5SDimitry Andric     for (const auto &I : MDs) {
28970b57cec5SDimitry Andric       // This is used for call site debug information.
289881ad6265SDimitry Andric       CheckDI(I.first != LLVMContext::MD_dbg ||
28990b57cec5SDimitry Andric                   !cast<DISubprogram>(I.second)->isDistinct(),
29000b57cec5SDimitry Andric               "function declaration may only have a unique !dbg attachment",
29010b57cec5SDimitry Andric               &F);
290281ad6265SDimitry Andric       Check(I.first != LLVMContext::MD_prof,
29030b57cec5SDimitry Andric             "function declaration may not have a !prof attachment", &F);
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric       // Verify the metadata itself.
29065ffd83dbSDimitry Andric       visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
29070b57cec5SDimitry Andric     }
290881ad6265SDimitry Andric     Check(!F.hasPersonalityFn(),
29090b57cec5SDimitry Andric           "Function declaration shouldn't have a personality routine", &F);
29100b57cec5SDimitry Andric   } else {
29110b57cec5SDimitry Andric     // Verify that this function (which has a body) is not named "llvm.*".  It
29120b57cec5SDimitry Andric     // is not legal to define intrinsics.
291381ad6265SDimitry Andric     Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
29140b57cec5SDimitry Andric 
29150b57cec5SDimitry Andric     // Check the entry node
29160b57cec5SDimitry Andric     const BasicBlock *Entry = &F.getEntryBlock();
291781ad6265SDimitry Andric     Check(pred_empty(Entry),
29180b57cec5SDimitry Andric           "Entry block to function must not have predecessors!", Entry);
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric     // The address of the entry block cannot be taken, unless it is dead.
29210b57cec5SDimitry Andric     if (Entry->hasAddressTaken()) {
292281ad6265SDimitry Andric       Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
29230b57cec5SDimitry Andric             "blockaddress may not be used with the entry block!", Entry);
29240b57cec5SDimitry Andric     }
29250b57cec5SDimitry Andric 
2926bdd1243dSDimitry Andric     unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2927bdd1243dSDimitry Andric              NumKCFIAttachments = 0;
29280b57cec5SDimitry Andric     // Visit metadata attachments.
29290b57cec5SDimitry Andric     for (const auto &I : MDs) {
29300b57cec5SDimitry Andric       // Verify that the attachment is legal.
29315ffd83dbSDimitry Andric       auto AllowLocs = AreDebugLocsAllowed::No;
29320b57cec5SDimitry Andric       switch (I.first) {
29330b57cec5SDimitry Andric       default:
29340b57cec5SDimitry Andric         break;
29350b57cec5SDimitry Andric       case LLVMContext::MD_dbg: {
29360b57cec5SDimitry Andric         ++NumDebugAttachments;
293781ad6265SDimitry Andric         CheckDI(NumDebugAttachments == 1,
29380b57cec5SDimitry Andric                 "function must have a single !dbg attachment", &F, I.second);
293981ad6265SDimitry Andric         CheckDI(isa<DISubprogram>(I.second),
29400b57cec5SDimitry Andric                 "function !dbg attachment must be a subprogram", &F, I.second);
294181ad6265SDimitry Andric         CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
2942e8d8bef9SDimitry Andric                 "function definition may only have a distinct !dbg attachment",
2943e8d8bef9SDimitry Andric                 &F);
2944e8d8bef9SDimitry Andric 
29450b57cec5SDimitry Andric         auto *SP = cast<DISubprogram>(I.second);
29460b57cec5SDimitry Andric         const Function *&AttachedTo = DISubprogramAttachments[SP];
294781ad6265SDimitry Andric         CheckDI(!AttachedTo || AttachedTo == &F,
29480b57cec5SDimitry Andric                 "DISubprogram attached to more than one function", SP, &F);
29490b57cec5SDimitry Andric         AttachedTo = &F;
29505ffd83dbSDimitry Andric         AllowLocs = AreDebugLocsAllowed::Yes;
29510b57cec5SDimitry Andric         break;
29520b57cec5SDimitry Andric       }
29530b57cec5SDimitry Andric       case LLVMContext::MD_prof:
29540b57cec5SDimitry Andric         ++NumProfAttachments;
295581ad6265SDimitry Andric         Check(NumProfAttachments == 1,
29560b57cec5SDimitry Andric               "function must have a single !prof attachment", &F, I.second);
29570b57cec5SDimitry Andric         break;
2958bdd1243dSDimitry Andric       case LLVMContext::MD_kcfi_type:
2959bdd1243dSDimitry Andric         ++NumKCFIAttachments;
2960bdd1243dSDimitry Andric         Check(NumKCFIAttachments == 1,
2961bdd1243dSDimitry Andric               "function must have a single !kcfi_type attachment", &F,
2962bdd1243dSDimitry Andric               I.second);
2963bdd1243dSDimitry Andric         break;
29640b57cec5SDimitry Andric       }
29650b57cec5SDimitry Andric 
29660b57cec5SDimitry Andric       // Verify the metadata itself.
29675ffd83dbSDimitry Andric       visitMDNode(*I.second, AllowLocs);
29680b57cec5SDimitry Andric     }
29690b57cec5SDimitry Andric   }
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric   // If this function is actually an intrinsic, verify that it is only used in
29720b57cec5SDimitry Andric   // direct call/invokes, never having its "address taken".
29730b57cec5SDimitry Andric   // Only do this if the module is materialized, otherwise we don't have all the
29740b57cec5SDimitry Andric   // uses.
2975fe6060f1SDimitry Andric   if (F.isIntrinsic() && F.getParent()->isMaterialized()) {
29760b57cec5SDimitry Andric     const User *U;
2977349cc55cSDimitry Andric     if (F.hasAddressTaken(&U, false, true, false,
2978349cc55cSDimitry Andric                           /*IgnoreARCAttachedCall=*/true))
297981ad6265SDimitry Andric       Check(false, "Invalid user of intrinsic instruction!", U);
29800b57cec5SDimitry Andric   }
29810b57cec5SDimitry Andric 
2982fe6060f1SDimitry Andric   // Check intrinsics' signatures.
2983fe6060f1SDimitry Andric   switch (F.getIntrinsicID()) {
2984fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_base: {
2985fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
298681ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
298781ad6265SDimitry Andric     Check(isa<PointerType>(F.getReturnType()),
2988fe6060f1SDimitry Andric           "gc.get.pointer.base must return a pointer", F);
298981ad6265SDimitry Andric     Check(FT->getParamType(0) == F.getReturnType(),
299081ad6265SDimitry Andric           "gc.get.pointer.base operand and result must be of the same type", F);
2991fe6060f1SDimitry Andric     break;
2992fe6060f1SDimitry Andric   }
2993fe6060f1SDimitry Andric   case Intrinsic::experimental_gc_get_pointer_offset: {
2994fe6060f1SDimitry Andric     FunctionType *FT = F.getFunctionType();
299581ad6265SDimitry Andric     Check(FT->getNumParams() == 1, "wrong number of parameters", F);
299681ad6265SDimitry Andric     Check(isa<PointerType>(FT->getParamType(0)),
2997fe6060f1SDimitry Andric           "gc.get.pointer.offset operand must be a pointer", F);
299881ad6265SDimitry Andric     Check(F.getReturnType()->isIntegerTy(),
2999fe6060f1SDimitry Andric           "gc.get.pointer.offset must return integer", F);
3000fe6060f1SDimitry Andric     break;
3001fe6060f1SDimitry Andric   }
3002fe6060f1SDimitry Andric   }
3003fe6060f1SDimitry Andric 
30040b57cec5SDimitry Andric   auto *N = F.getSubprogram();
30050b57cec5SDimitry Andric   HasDebugInfo = (N != nullptr);
30060b57cec5SDimitry Andric   if (!HasDebugInfo)
30070b57cec5SDimitry Andric     return;
30080b57cec5SDimitry Andric 
30095ffd83dbSDimitry Andric   // Check that all !dbg attachments lead to back to N.
30100b57cec5SDimitry Andric   //
30110b57cec5SDimitry Andric   // FIXME: Check this incrementally while visiting !dbg attachments.
30120b57cec5SDimitry Andric   // FIXME: Only check when N is the canonical subprogram for F.
30130b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 32> Seen;
30140b57cec5SDimitry Andric   auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
30150b57cec5SDimitry Andric     // Be careful about using DILocation here since we might be dealing with
30160b57cec5SDimitry Andric     // broken code (this is the Verifier after all).
30170b57cec5SDimitry Andric     const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
30180b57cec5SDimitry Andric     if (!DL)
30190b57cec5SDimitry Andric       return;
30200b57cec5SDimitry Andric     if (!Seen.insert(DL).second)
30210b57cec5SDimitry Andric       return;
30220b57cec5SDimitry Andric 
30230b57cec5SDimitry Andric     Metadata *Parent = DL->getRawScope();
302481ad6265SDimitry Andric     CheckDI(Parent && isa<DILocalScope>(Parent),
302581ad6265SDimitry Andric             "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
30265ffd83dbSDimitry Andric 
30270b57cec5SDimitry Andric     DILocalScope *Scope = DL->getInlinedAtScope();
302881ad6265SDimitry Andric     Check(Scope, "Failed to find DILocalScope", DL);
30295ffd83dbSDimitry Andric 
30305ffd83dbSDimitry Andric     if (!Seen.insert(Scope).second)
30310b57cec5SDimitry Andric       return;
30320b57cec5SDimitry Andric 
30335ffd83dbSDimitry Andric     DISubprogram *SP = Scope->getSubprogram();
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric     // Scope and SP could be the same MDNode and we don't want to skip
30360b57cec5SDimitry Andric     // validation in that case
30370b57cec5SDimitry Andric     if (SP && ((Scope != SP) && !Seen.insert(SP).second))
30380b57cec5SDimitry Andric       return;
30390b57cec5SDimitry Andric 
304081ad6265SDimitry Andric     CheckDI(SP->describes(&F),
30410b57cec5SDimitry Andric             "!dbg attachment points at wrong subprogram for function", N, &F,
30420b57cec5SDimitry Andric             &I, DL, Scope, SP);
30430b57cec5SDimitry Andric   };
30440b57cec5SDimitry Andric   for (auto &BB : F)
30450b57cec5SDimitry Andric     for (auto &I : BB) {
30460b57cec5SDimitry Andric       VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
30470b57cec5SDimitry Andric       // The llvm.loop annotations also contain two DILocations.
30480b57cec5SDimitry Andric       if (auto MD = I.getMetadata(LLVMContext::MD_loop))
30490b57cec5SDimitry Andric         for (unsigned i = 1; i < MD->getNumOperands(); ++i)
30500b57cec5SDimitry Andric           VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
30510b57cec5SDimitry Andric       if (BrokenDebugInfo)
30520b57cec5SDimitry Andric         return;
30530b57cec5SDimitry Andric     }
30540b57cec5SDimitry Andric }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric // verifyBasicBlock - Verify that a basic block is well formed...
30570b57cec5SDimitry Andric //
visitBasicBlock(BasicBlock & BB)30580b57cec5SDimitry Andric void Verifier::visitBasicBlock(BasicBlock &BB) {
30590b57cec5SDimitry Andric   InstsInThisBlock.clear();
30605f757f3fSDimitry Andric   ConvergenceVerifyHelper.visit(BB);
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric   // Ensure that basic blocks have terminators!
306381ad6265SDimitry Andric   Check(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric   // Check constraints that this basic block imposes on all of the PHI nodes in
30660b57cec5SDimitry Andric   // it.
30670b57cec5SDimitry Andric   if (isa<PHINode>(BB.front())) {
3068e8d8bef9SDimitry Andric     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
30690b57cec5SDimitry Andric     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
30700b57cec5SDimitry Andric     llvm::sort(Preds);
30710b57cec5SDimitry Andric     for (const PHINode &PN : BB.phis()) {
307281ad6265SDimitry Andric       Check(PN.getNumIncomingValues() == Preds.size(),
30730b57cec5SDimitry Andric             "PHINode should have one entry for each predecessor of its "
30740b57cec5SDimitry Andric             "parent basic block!",
30750b57cec5SDimitry Andric             &PN);
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric       // Get and sort all incoming values in the PHI node...
30780b57cec5SDimitry Andric       Values.clear();
30790b57cec5SDimitry Andric       Values.reserve(PN.getNumIncomingValues());
30800b57cec5SDimitry Andric       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
30810b57cec5SDimitry Andric         Values.push_back(
30820b57cec5SDimitry Andric             std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
30830b57cec5SDimitry Andric       llvm::sort(Values);
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
30860b57cec5SDimitry Andric         // Check to make sure that if there is more than one entry for a
30870b57cec5SDimitry Andric         // particular basic block in this PHI node, that the incoming values are
30880b57cec5SDimitry Andric         // all identical.
30890b57cec5SDimitry Andric         //
309081ad6265SDimitry Andric         Check(i == 0 || Values[i].first != Values[i - 1].first ||
30910b57cec5SDimitry Andric                   Values[i].second == Values[i - 1].second,
30920b57cec5SDimitry Andric               "PHI node has multiple entries for the same basic block with "
30930b57cec5SDimitry Andric               "different incoming values!",
30940b57cec5SDimitry Andric               &PN, Values[i].first, Values[i].second, Values[i - 1].second);
30950b57cec5SDimitry Andric 
30960b57cec5SDimitry Andric         // Check to make sure that the predecessors and PHI node entries are
30970b57cec5SDimitry Andric         // matched up.
309881ad6265SDimitry Andric         Check(Values[i].first == Preds[i],
30990b57cec5SDimitry Andric               "PHI node entries do not match predecessors!", &PN,
31000b57cec5SDimitry Andric               Values[i].first, Preds[i]);
31010b57cec5SDimitry Andric       }
31020b57cec5SDimitry Andric     }
31030b57cec5SDimitry Andric   }
31040b57cec5SDimitry Andric 
31050b57cec5SDimitry Andric   // Check that all instructions have their parent pointers set up correctly.
31060b57cec5SDimitry Andric   for (auto &I : BB)
31070b57cec5SDimitry Andric   {
310881ad6265SDimitry Andric     Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
31090b57cec5SDimitry Andric   }
31105f757f3fSDimitry Andric 
3111*0fca6ea1SDimitry Andric   CheckDI(BB.IsNewDbgInfoFormat == BB.getParent()->IsNewDbgInfoFormat,
3112*0fca6ea1SDimitry Andric           "BB debug format should match parent function", &BB,
3113*0fca6ea1SDimitry Andric           BB.IsNewDbgInfoFormat, BB.getParent(),
3114*0fca6ea1SDimitry Andric           BB.getParent()->IsNewDbgInfoFormat);
3115*0fca6ea1SDimitry Andric 
31165f757f3fSDimitry Andric   // Confirm that no issues arise from the debug program.
3117*0fca6ea1SDimitry Andric   if (BB.IsNewDbgInfoFormat)
3118*0fca6ea1SDimitry Andric     CheckDI(!BB.getTrailingDbgRecords(), "Basic Block has trailing DbgRecords!",
3119*0fca6ea1SDimitry Andric             &BB);
31200b57cec5SDimitry Andric }
31210b57cec5SDimitry Andric 
visitTerminator(Instruction & I)31220b57cec5SDimitry Andric void Verifier::visitTerminator(Instruction &I) {
31230b57cec5SDimitry Andric   // Ensure that terminators only exist at the end of the basic block.
312481ad6265SDimitry Andric   Check(&I == I.getParent()->getTerminator(),
31250b57cec5SDimitry Andric         "Terminator found in the middle of a basic block!", I.getParent());
31260b57cec5SDimitry Andric   visitInstruction(I);
31270b57cec5SDimitry Andric }
31280b57cec5SDimitry Andric 
visitBranchInst(BranchInst & BI)31290b57cec5SDimitry Andric void Verifier::visitBranchInst(BranchInst &BI) {
31300b57cec5SDimitry Andric   if (BI.isConditional()) {
313181ad6265SDimitry Andric     Check(BI.getCondition()->getType()->isIntegerTy(1),
31320b57cec5SDimitry Andric           "Branch condition is not 'i1' type!", &BI, BI.getCondition());
31330b57cec5SDimitry Andric   }
31340b57cec5SDimitry Andric   visitTerminator(BI);
31350b57cec5SDimitry Andric }
31360b57cec5SDimitry Andric 
visitReturnInst(ReturnInst & RI)31370b57cec5SDimitry Andric void Verifier::visitReturnInst(ReturnInst &RI) {
31380b57cec5SDimitry Andric   Function *F = RI.getParent()->getParent();
31390b57cec5SDimitry Andric   unsigned N = RI.getNumOperands();
31400b57cec5SDimitry Andric   if (F->getReturnType()->isVoidTy())
314181ad6265SDimitry Andric     Check(N == 0,
31420b57cec5SDimitry Andric           "Found return instr that returns non-void in Function of void "
31430b57cec5SDimitry Andric           "return type!",
31440b57cec5SDimitry Andric           &RI, F->getReturnType());
31450b57cec5SDimitry Andric   else
314681ad6265SDimitry Andric     Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
31470b57cec5SDimitry Andric           "Function return type does not match operand "
31480b57cec5SDimitry Andric           "type of return inst!",
31490b57cec5SDimitry Andric           &RI, F->getReturnType());
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric   // Check to make sure that the return value has necessary properties for
31520b57cec5SDimitry Andric   // terminators...
31530b57cec5SDimitry Andric   visitTerminator(RI);
31540b57cec5SDimitry Andric }
31550b57cec5SDimitry Andric 
visitSwitchInst(SwitchInst & SI)31560b57cec5SDimitry Andric void Verifier::visitSwitchInst(SwitchInst &SI) {
315781ad6265SDimitry Andric   Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
31580b57cec5SDimitry Andric   // Check to make sure that all of the constants in the switch instruction
31590b57cec5SDimitry Andric   // have the same type as the switched-on value.
31600b57cec5SDimitry Andric   Type *SwitchTy = SI.getCondition()->getType();
31610b57cec5SDimitry Andric   SmallPtrSet<ConstantInt*, 32> Constants;
31620b57cec5SDimitry Andric   for (auto &Case : SI.cases()) {
3163bdd1243dSDimitry Andric     Check(isa<ConstantInt>(SI.getOperand(Case.getCaseIndex() * 2 + 2)),
3164bdd1243dSDimitry Andric           "Case value is not a constant integer.", &SI);
316581ad6265SDimitry Andric     Check(Case.getCaseValue()->getType() == SwitchTy,
31660b57cec5SDimitry Andric           "Switch constants must all be same type as switch value!", &SI);
316781ad6265SDimitry Andric     Check(Constants.insert(Case.getCaseValue()).second,
31680b57cec5SDimitry Andric           "Duplicate integer as switch case", &SI, Case.getCaseValue());
31690b57cec5SDimitry Andric   }
31700b57cec5SDimitry Andric 
31710b57cec5SDimitry Andric   visitTerminator(SI);
31720b57cec5SDimitry Andric }
31730b57cec5SDimitry Andric 
visitIndirectBrInst(IndirectBrInst & BI)31740b57cec5SDimitry Andric void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
317581ad6265SDimitry Andric   Check(BI.getAddress()->getType()->isPointerTy(),
31760b57cec5SDimitry Andric         "Indirectbr operand must have pointer type!", &BI);
31770b57cec5SDimitry Andric   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
317881ad6265SDimitry Andric     Check(BI.getDestination(i)->getType()->isLabelTy(),
31790b57cec5SDimitry Andric           "Indirectbr destinations must all have pointer type!", &BI);
31800b57cec5SDimitry Andric 
31810b57cec5SDimitry Andric   visitTerminator(BI);
31820b57cec5SDimitry Andric }
31830b57cec5SDimitry Andric 
visitCallBrInst(CallBrInst & CBI)31840b57cec5SDimitry Andric void Verifier::visitCallBrInst(CallBrInst &CBI) {
318581ad6265SDimitry Andric   Check(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", &CBI);
3186fe6060f1SDimitry Andric   const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
318781ad6265SDimitry Andric   Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
31880b57cec5SDimitry Andric 
318904eeddc0SDimitry Andric   verifyInlineAsmCall(CBI);
31900b57cec5SDimitry Andric   visitTerminator(CBI);
31910b57cec5SDimitry Andric }
31920b57cec5SDimitry Andric 
visitSelectInst(SelectInst & SI)31930b57cec5SDimitry Andric void Verifier::visitSelectInst(SelectInst &SI) {
319481ad6265SDimitry Andric   Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
31950b57cec5SDimitry Andric                                         SI.getOperand(2)),
31960b57cec5SDimitry Andric         "Invalid operands for select instruction!", &SI);
31970b57cec5SDimitry Andric 
319881ad6265SDimitry Andric   Check(SI.getTrueValue()->getType() == SI.getType(),
31990b57cec5SDimitry Andric         "Select values must have same type as select instruction!", &SI);
32000b57cec5SDimitry Andric   visitInstruction(SI);
32010b57cec5SDimitry Andric }
32020b57cec5SDimitry Andric 
32030b57cec5SDimitry Andric /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
32040b57cec5SDimitry Andric /// a pass, if any exist, it's an error.
32050b57cec5SDimitry Andric ///
visitUserOp1(Instruction & I)32060b57cec5SDimitry Andric void Verifier::visitUserOp1(Instruction &I) {
320781ad6265SDimitry Andric   Check(false, "User-defined operators should not live outside of a pass!", &I);
32080b57cec5SDimitry Andric }
32090b57cec5SDimitry Andric 
visitTruncInst(TruncInst & I)32100b57cec5SDimitry Andric void Verifier::visitTruncInst(TruncInst &I) {
32110b57cec5SDimitry Andric   // Get the source and destination types
32120b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32130b57cec5SDimitry Andric   Type *DestTy = I.getType();
32140b57cec5SDimitry Andric 
32150b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
32160b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
32170b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
32180b57cec5SDimitry Andric 
321981ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
322081ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
322181ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
32220b57cec5SDimitry Andric         "trunc source and destination must both be a vector or neither", &I);
322381ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
32240b57cec5SDimitry Andric 
32250b57cec5SDimitry Andric   visitInstruction(I);
32260b57cec5SDimitry Andric }
32270b57cec5SDimitry Andric 
visitZExtInst(ZExtInst & I)32280b57cec5SDimitry Andric void Verifier::visitZExtInst(ZExtInst &I) {
32290b57cec5SDimitry Andric   // Get the source and destination types
32300b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32310b57cec5SDimitry Andric   Type *DestTy = I.getType();
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
323481ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
323581ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
323681ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
32370b57cec5SDimitry Andric         "zext source and destination must both be a vector or neither", &I);
32380b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
32390b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
32400b57cec5SDimitry Andric 
324181ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric   visitInstruction(I);
32440b57cec5SDimitry Andric }
32450b57cec5SDimitry Andric 
visitSExtInst(SExtInst & I)32460b57cec5SDimitry Andric void Verifier::visitSExtInst(SExtInst &I) {
32470b57cec5SDimitry Andric   // Get the source and destination types
32480b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32490b57cec5SDimitry Andric   Type *DestTy = I.getType();
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
32520b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
32530b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
32540b57cec5SDimitry Andric 
325581ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
325681ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
325781ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
32580b57cec5SDimitry Andric         "sext source and destination must both be a vector or neither", &I);
325981ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric   visitInstruction(I);
32620b57cec5SDimitry Andric }
32630b57cec5SDimitry Andric 
visitFPTruncInst(FPTruncInst & I)32640b57cec5SDimitry Andric void Verifier::visitFPTruncInst(FPTruncInst &I) {
32650b57cec5SDimitry Andric   // Get the source and destination types
32660b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32670b57cec5SDimitry Andric   Type *DestTy = I.getType();
32680b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
32690b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
32700b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
32710b57cec5SDimitry Andric 
327281ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
327381ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
327481ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
32750b57cec5SDimitry Andric         "fptrunc source and destination must both be a vector or neither", &I);
327681ad6265SDimitry Andric   Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
32770b57cec5SDimitry Andric 
32780b57cec5SDimitry Andric   visitInstruction(I);
32790b57cec5SDimitry Andric }
32800b57cec5SDimitry Andric 
visitFPExtInst(FPExtInst & I)32810b57cec5SDimitry Andric void Verifier::visitFPExtInst(FPExtInst &I) {
32820b57cec5SDimitry Andric   // Get the source and destination types
32830b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
32840b57cec5SDimitry Andric   Type *DestTy = I.getType();
32850b57cec5SDimitry Andric 
32860b57cec5SDimitry Andric   // Get the size of the types in bits, we'll need this later
32870b57cec5SDimitry Andric   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
32880b57cec5SDimitry Andric   unsigned DestBitSize = DestTy->getScalarSizeInBits();
32890b57cec5SDimitry Andric 
329081ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
329181ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
329281ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
32930b57cec5SDimitry Andric         "fpext source and destination must both be a vector or neither", &I);
329481ad6265SDimitry Andric   Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
32950b57cec5SDimitry Andric 
32960b57cec5SDimitry Andric   visitInstruction(I);
32970b57cec5SDimitry Andric }
32980b57cec5SDimitry Andric 
visitUIToFPInst(UIToFPInst & I)32990b57cec5SDimitry Andric void Verifier::visitUIToFPInst(UIToFPInst &I) {
33000b57cec5SDimitry Andric   // Get the source and destination types
33010b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
33020b57cec5SDimitry Andric   Type *DestTy = I.getType();
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
33050b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
33060b57cec5SDimitry Andric 
330781ad6265SDimitry Andric   Check(SrcVec == DstVec,
33080b57cec5SDimitry Andric         "UIToFP source and dest must both be vector or scalar", &I);
330981ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
33100b57cec5SDimitry Andric         "UIToFP source must be integer or integer vector", &I);
331181ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
33120b57cec5SDimitry Andric         &I);
33130b57cec5SDimitry Andric 
33140b57cec5SDimitry Andric   if (SrcVec && DstVec)
331581ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
33165ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
33170b57cec5SDimitry Andric           "UIToFP source and dest vector length mismatch", &I);
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric   visitInstruction(I);
33200b57cec5SDimitry Andric }
33210b57cec5SDimitry Andric 
visitSIToFPInst(SIToFPInst & I)33220b57cec5SDimitry Andric void Verifier::visitSIToFPInst(SIToFPInst &I) {
33230b57cec5SDimitry Andric   // Get the source and destination types
33240b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
33250b57cec5SDimitry Andric   Type *DestTy = I.getType();
33260b57cec5SDimitry Andric 
33270b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
33280b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
33290b57cec5SDimitry Andric 
333081ad6265SDimitry Andric   Check(SrcVec == DstVec,
33310b57cec5SDimitry Andric         "SIToFP source and dest must both be vector or scalar", &I);
333281ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(),
33330b57cec5SDimitry Andric         "SIToFP source must be integer or integer vector", &I);
333481ad6265SDimitry Andric   Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
33350b57cec5SDimitry Andric         &I);
33360b57cec5SDimitry Andric 
33370b57cec5SDimitry Andric   if (SrcVec && DstVec)
333881ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
33395ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
33400b57cec5SDimitry Andric           "SIToFP source and dest vector length mismatch", &I);
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   visitInstruction(I);
33430b57cec5SDimitry Andric }
33440b57cec5SDimitry Andric 
visitFPToUIInst(FPToUIInst & I)33450b57cec5SDimitry Andric void Verifier::visitFPToUIInst(FPToUIInst &I) {
33460b57cec5SDimitry Andric   // Get the source and destination types
33470b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
33480b57cec5SDimitry Andric   Type *DestTy = I.getType();
33490b57cec5SDimitry Andric 
33500b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
33510b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
33520b57cec5SDimitry Andric 
335381ad6265SDimitry Andric   Check(SrcVec == DstVec,
33540b57cec5SDimitry Andric         "FPToUI source and dest must both be vector or scalar", &I);
335581ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
335681ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
33570b57cec5SDimitry Andric         "FPToUI result must be integer or integer vector", &I);
33580b57cec5SDimitry Andric 
33590b57cec5SDimitry Andric   if (SrcVec && DstVec)
336081ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
33615ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
33620b57cec5SDimitry Andric           "FPToUI source and dest vector length mismatch", &I);
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric   visitInstruction(I);
33650b57cec5SDimitry Andric }
33660b57cec5SDimitry Andric 
visitFPToSIInst(FPToSIInst & I)33670b57cec5SDimitry Andric void Verifier::visitFPToSIInst(FPToSIInst &I) {
33680b57cec5SDimitry Andric   // Get the source and destination types
33690b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
33700b57cec5SDimitry Andric   Type *DestTy = I.getType();
33710b57cec5SDimitry Andric 
33720b57cec5SDimitry Andric   bool SrcVec = SrcTy->isVectorTy();
33730b57cec5SDimitry Andric   bool DstVec = DestTy->isVectorTy();
33740b57cec5SDimitry Andric 
337581ad6265SDimitry Andric   Check(SrcVec == DstVec,
33760b57cec5SDimitry Andric         "FPToSI source and dest must both be vector or scalar", &I);
337781ad6265SDimitry Andric   Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
337881ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(),
33790b57cec5SDimitry Andric         "FPToSI result must be integer or integer vector", &I);
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric   if (SrcVec && DstVec)
338281ad6265SDimitry Andric     Check(cast<VectorType>(SrcTy)->getElementCount() ==
33835ffd83dbSDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
33840b57cec5SDimitry Andric           "FPToSI source and dest vector length mismatch", &I);
33850b57cec5SDimitry Andric 
33860b57cec5SDimitry Andric   visitInstruction(I);
33870b57cec5SDimitry Andric }
33880b57cec5SDimitry Andric 
visitPtrToIntInst(PtrToIntInst & I)33890b57cec5SDimitry Andric void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
33900b57cec5SDimitry Andric   // Get the source and destination types
33910b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
33920b57cec5SDimitry Andric   Type *DestTy = I.getType();
33930b57cec5SDimitry Andric 
339481ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
33950b57cec5SDimitry Andric 
339681ad6265SDimitry Andric   Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
339781ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
33980b57cec5SDimitry Andric         &I);
33990b57cec5SDimitry Andric 
34000b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
34015ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
34025ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
340381ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
34040b57cec5SDimitry Andric           "PtrToInt Vector width mismatch", &I);
34050b57cec5SDimitry Andric   }
34060b57cec5SDimitry Andric 
34070b57cec5SDimitry Andric   visitInstruction(I);
34080b57cec5SDimitry Andric }
34090b57cec5SDimitry Andric 
visitIntToPtrInst(IntToPtrInst & I)34100b57cec5SDimitry Andric void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
34110b57cec5SDimitry Andric   // Get the source and destination types
34120b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
34130b57cec5SDimitry Andric   Type *DestTy = I.getType();
34140b57cec5SDimitry Andric 
341581ad6265SDimitry Andric   Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
341681ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
34170b57cec5SDimitry Andric 
341881ad6265SDimitry Andric   Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
34190b57cec5SDimitry Andric         &I);
34200b57cec5SDimitry Andric   if (SrcTy->isVectorTy()) {
34215ffd83dbSDimitry Andric     auto *VSrc = cast<VectorType>(SrcTy);
34225ffd83dbSDimitry Andric     auto *VDest = cast<VectorType>(DestTy);
342381ad6265SDimitry Andric     Check(VSrc->getElementCount() == VDest->getElementCount(),
34240b57cec5SDimitry Andric           "IntToPtr Vector width mismatch", &I);
34250b57cec5SDimitry Andric   }
34260b57cec5SDimitry Andric   visitInstruction(I);
34270b57cec5SDimitry Andric }
34280b57cec5SDimitry Andric 
visitBitCastInst(BitCastInst & I)34290b57cec5SDimitry Andric void Verifier::visitBitCastInst(BitCastInst &I) {
343081ad6265SDimitry Andric   Check(
34310b57cec5SDimitry Andric       CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
34320b57cec5SDimitry Andric       "Invalid bitcast", &I);
34330b57cec5SDimitry Andric   visitInstruction(I);
34340b57cec5SDimitry Andric }
34350b57cec5SDimitry Andric 
visitAddrSpaceCastInst(AddrSpaceCastInst & I)34360b57cec5SDimitry Andric void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
34370b57cec5SDimitry Andric   Type *SrcTy = I.getOperand(0)->getType();
34380b57cec5SDimitry Andric   Type *DestTy = I.getType();
34390b57cec5SDimitry Andric 
344081ad6265SDimitry Andric   Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
34410b57cec5SDimitry Andric         &I);
344281ad6265SDimitry Andric   Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
34430b57cec5SDimitry Andric         &I);
344481ad6265SDimitry Andric   Check(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
34450b57cec5SDimitry Andric         "AddrSpaceCast must be between different address spaces", &I);
34465ffd83dbSDimitry Andric   if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
344781ad6265SDimitry Andric     Check(SrcVTy->getElementCount() ==
3448e8d8bef9SDimitry Andric               cast<VectorType>(DestTy)->getElementCount(),
34490b57cec5SDimitry Andric           "AddrSpaceCast vector pointer number of elements mismatch", &I);
34500b57cec5SDimitry Andric   visitInstruction(I);
34510b57cec5SDimitry Andric }
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric /// visitPHINode - Ensure that a PHI node is well formed.
34540b57cec5SDimitry Andric ///
visitPHINode(PHINode & PN)34550b57cec5SDimitry Andric void Verifier::visitPHINode(PHINode &PN) {
34560b57cec5SDimitry Andric   // Ensure that the PHI nodes are all grouped together at the top of the block.
34570b57cec5SDimitry Andric   // This can be tested by checking whether the instruction before this is
34580b57cec5SDimitry Andric   // either nonexistent (because this is begin()) or is a PHI node.  If not,
34590b57cec5SDimitry Andric   // then there is some other instruction before a PHI.
346081ad6265SDimitry Andric   Check(&PN == &PN.getParent()->front() ||
34610b57cec5SDimitry Andric             isa<PHINode>(--BasicBlock::iterator(&PN)),
34620b57cec5SDimitry Andric         "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
34630b57cec5SDimitry Andric 
34640b57cec5SDimitry Andric   // Check that a PHI doesn't yield a Token.
346581ad6265SDimitry Andric   Check(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
34660b57cec5SDimitry Andric 
34670b57cec5SDimitry Andric   // Check that all of the values of the PHI node have the same type as the
3468*0fca6ea1SDimitry Andric   // result.
34690b57cec5SDimitry Andric   for (Value *IncValue : PN.incoming_values()) {
347081ad6265SDimitry Andric     Check(PN.getType() == IncValue->getType(),
34710b57cec5SDimitry Andric           "PHI node operands are not the same type as the result!", &PN);
34720b57cec5SDimitry Andric   }
34730b57cec5SDimitry Andric 
34740b57cec5SDimitry Andric   // All other PHI node constraints are checked in the visitBasicBlock method.
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric   visitInstruction(PN);
34770b57cec5SDimitry Andric }
34780b57cec5SDimitry Andric 
visitCallBase(CallBase & Call)34790b57cec5SDimitry Andric void Verifier::visitCallBase(CallBase &Call) {
348081ad6265SDimitry Andric   Check(Call.getCalledOperand()->getType()->isPointerTy(),
34810b57cec5SDimitry Andric         "Called function must be a pointer!", Call);
34820b57cec5SDimitry Andric   FunctionType *FTy = Call.getFunctionType();
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric   // Verify that the correct number of arguments are being passed
34850b57cec5SDimitry Andric   if (FTy->isVarArg())
348681ad6265SDimitry Andric     Check(Call.arg_size() >= FTy->getNumParams(),
348781ad6265SDimitry Andric           "Called function requires more parameters than were provided!", Call);
34880b57cec5SDimitry Andric   else
348981ad6265SDimitry Andric     Check(Call.arg_size() == FTy->getNumParams(),
34900b57cec5SDimitry Andric           "Incorrect number of arguments passed to called function!", Call);
34910b57cec5SDimitry Andric 
34920b57cec5SDimitry Andric   // Verify that all arguments to the call match the function type.
34930b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
349481ad6265SDimitry Andric     Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
34950b57cec5SDimitry Andric           "Call parameter type does not match function signature!",
34960b57cec5SDimitry Andric           Call.getArgOperand(i), FTy->getParamType(i), Call);
34970b57cec5SDimitry Andric 
34980b57cec5SDimitry Andric   AttributeList Attrs = Call.getAttributes();
34990b57cec5SDimitry Andric 
350081ad6265SDimitry Andric   Check(verifyAttributeCount(Attrs, Call.arg_size()),
35010b57cec5SDimitry Andric         "Attribute after last parameter!", Call);
35020b57cec5SDimitry Andric 
3503bdd1243dSDimitry Andric   Function *Callee =
3504bdd1243dSDimitry Andric       dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts());
3505bdd1243dSDimitry Andric   bool IsIntrinsic = Callee && Callee->isIntrinsic();
3506bdd1243dSDimitry Andric   if (IsIntrinsic)
3507bdd1243dSDimitry Andric     Check(Callee->getValueType() == FTy,
3508bdd1243dSDimitry Andric           "Intrinsic called with incompatible signature", Call);
3509bdd1243dSDimitry Andric 
351006c3fb27SDimitry Andric   // Disallow calls to functions with the amdgpu_cs_chain[_preserve] calling
351106c3fb27SDimitry Andric   // convention.
351206c3fb27SDimitry Andric   auto CC = Call.getCallingConv();
351306c3fb27SDimitry Andric   Check(CC != CallingConv::AMDGPU_CS_Chain &&
351406c3fb27SDimitry Andric             CC != CallingConv::AMDGPU_CS_ChainPreserve,
351506c3fb27SDimitry Andric         "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
351606c3fb27SDimitry Andric         "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
351706c3fb27SDimitry Andric         Call);
351806c3fb27SDimitry Andric 
3519*0fca6ea1SDimitry Andric   // Disallow passing/returning values with alignment higher than we can
3520*0fca6ea1SDimitry Andric   // represent.
3521*0fca6ea1SDimitry Andric   // FIXME: Consider making DataLayout cap the alignment, so this isn't
3522*0fca6ea1SDimitry Andric   // necessary.
352381ad6265SDimitry Andric   auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
352481ad6265SDimitry Andric     if (!Ty->isSized())
352581ad6265SDimitry Andric       return;
352681ad6265SDimitry Andric     Align ABIAlign = DL.getABITypeAlign(Ty);
3527*0fca6ea1SDimitry Andric     Check(ABIAlign.value() <= Value::MaximumAlignment,
352881ad6265SDimitry Andric           "Incorrect alignment of " + Message + " to called function!", Call);
352981ad6265SDimitry Andric   };
353081ad6265SDimitry Andric 
3531bdd1243dSDimitry Andric   if (!IsIntrinsic) {
353281ad6265SDimitry Andric     VerifyTypeAlign(FTy->getReturnType(), "return type");
353381ad6265SDimitry Andric     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
353481ad6265SDimitry Andric       Type *Ty = FTy->getParamType(i);
353581ad6265SDimitry Andric       VerifyTypeAlign(Ty, "argument passed");
353681ad6265SDimitry Andric     }
3537bdd1243dSDimitry Andric   }
35380b57cec5SDimitry Andric 
3539349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Speculatable)) {
35400b57cec5SDimitry Andric     // Don't allow speculatable on call sites, unless the underlying function
35410b57cec5SDimitry Andric     // declaration is also speculatable.
354281ad6265SDimitry Andric     Check(Callee && Callee->isSpeculatable(),
35430b57cec5SDimitry Andric           "speculatable attribute may not apply to call sites", Call);
35440b57cec5SDimitry Andric   }
35450b57cec5SDimitry Andric 
3546349cc55cSDimitry Andric   if (Attrs.hasFnAttr(Attribute::Preallocated)) {
354781ad6265SDimitry Andric     Check(Call.getCalledFunction()->getIntrinsicID() ==
35485ffd83dbSDimitry Andric               Intrinsic::call_preallocated_arg,
35495ffd83dbSDimitry Andric           "preallocated as a call site attribute can only be on "
35505ffd83dbSDimitry Andric           "llvm.call.preallocated.arg");
35515ffd83dbSDimitry Andric   }
35525ffd83dbSDimitry Andric 
35530b57cec5SDimitry Andric   // Verify call attributes.
355404eeddc0SDimitry Andric   verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
35550b57cec5SDimitry Andric 
35560b57cec5SDimitry Andric   // Conservatively check the inalloca argument.
35570b57cec5SDimitry Andric   // We have a bug if we can find that there is an underlying alloca without
35580b57cec5SDimitry Andric   // inalloca.
35590b57cec5SDimitry Andric   if (Call.hasInAllocaArgument()) {
35600b57cec5SDimitry Andric     Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
35610b57cec5SDimitry Andric     if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
356281ad6265SDimitry Andric       Check(AI->isUsedWithInAlloca(),
35630b57cec5SDimitry Andric             "inalloca argument for call has mismatched alloca", AI, Call);
35640b57cec5SDimitry Andric   }
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric   // For each argument of the callsite, if it has the swifterror argument,
35670b57cec5SDimitry Andric   // make sure the underlying alloca/parameter it comes from has a swifterror as
35680b57cec5SDimitry Andric   // well.
35690b57cec5SDimitry Andric   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
35700b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::SwiftError)) {
35710b57cec5SDimitry Andric       Value *SwiftErrorArg = Call.getArgOperand(i);
35720b57cec5SDimitry Andric       if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
357381ad6265SDimitry Andric         Check(AI->isSwiftError(),
35740b57cec5SDimitry Andric               "swifterror argument for call has mismatched alloca", AI, Call);
35750b57cec5SDimitry Andric         continue;
35760b57cec5SDimitry Andric       }
35770b57cec5SDimitry Andric       auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
357881ad6265SDimitry Andric       Check(ArgI, "swifterror argument should come from an alloca or parameter",
35790b57cec5SDimitry Andric             SwiftErrorArg, Call);
358081ad6265SDimitry Andric       Check(ArgI->hasSwiftErrorAttr(),
35810b57cec5SDimitry Andric             "swifterror argument for call has mismatched parameter", ArgI,
35820b57cec5SDimitry Andric             Call);
35830b57cec5SDimitry Andric     }
35840b57cec5SDimitry Andric 
3585349cc55cSDimitry Andric     if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
35860b57cec5SDimitry Andric       // Don't allow immarg on call sites, unless the underlying declaration
35870b57cec5SDimitry Andric       // also has the matching immarg.
358881ad6265SDimitry Andric       Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
358981ad6265SDimitry Andric             "immarg may not apply only to call sites", Call.getArgOperand(i),
359081ad6265SDimitry Andric             Call);
35910b57cec5SDimitry Andric     }
35920b57cec5SDimitry Andric 
35930b57cec5SDimitry Andric     if (Call.paramHasAttr(i, Attribute::ImmArg)) {
35940b57cec5SDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
359581ad6265SDimitry Andric       Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
35960b57cec5SDimitry Andric             "immarg operand has non-immediate parameter", ArgVal, Call);
35970b57cec5SDimitry Andric     }
35985ffd83dbSDimitry Andric 
35995ffd83dbSDimitry Andric     if (Call.paramHasAttr(i, Attribute::Preallocated)) {
36005ffd83dbSDimitry Andric       Value *ArgVal = Call.getArgOperand(i);
36015ffd83dbSDimitry Andric       bool hasOB =
36025ffd83dbSDimitry Andric           Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0;
36035ffd83dbSDimitry Andric       bool isMustTail = Call.isMustTailCall();
360481ad6265SDimitry Andric       Check(hasOB != isMustTail,
36055ffd83dbSDimitry Andric             "preallocated operand either requires a preallocated bundle or "
36065ffd83dbSDimitry Andric             "the call to be musttail (but not both)",
36075ffd83dbSDimitry Andric             ArgVal, Call);
36085ffd83dbSDimitry Andric     }
36090b57cec5SDimitry Andric   }
36100b57cec5SDimitry Andric 
36110b57cec5SDimitry Andric   if (FTy->isVarArg()) {
36120b57cec5SDimitry Andric     // FIXME? is 'nest' even legal here?
36130b57cec5SDimitry Andric     bool SawNest = false;
36140b57cec5SDimitry Andric     bool SawReturned = false;
36150b57cec5SDimitry Andric 
36160b57cec5SDimitry Andric     for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3617349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Nest))
36180b57cec5SDimitry Andric         SawNest = true;
3619349cc55cSDimitry Andric       if (Attrs.hasParamAttr(Idx, Attribute::Returned))
36200b57cec5SDimitry Andric         SawReturned = true;
36210b57cec5SDimitry Andric     }
36220b57cec5SDimitry Andric 
36230b57cec5SDimitry Andric     // Check attributes on the varargs part.
36240b57cec5SDimitry Andric     for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
36250b57cec5SDimitry Andric       Type *Ty = Call.getArgOperand(Idx)->getType();
3626349cc55cSDimitry Andric       AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
36270b57cec5SDimitry Andric       verifyParameterAttrs(ArgAttrs, Ty, &Call);
36280b57cec5SDimitry Andric 
36290b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Nest)) {
363081ad6265SDimitry Andric         Check(!SawNest, "More than one parameter has attribute nest!", Call);
36310b57cec5SDimitry Andric         SawNest = true;
36320b57cec5SDimitry Andric       }
36330b57cec5SDimitry Andric 
36340b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::Returned)) {
363581ad6265SDimitry Andric         Check(!SawReturned, "More than one parameter has attribute returned!",
36360b57cec5SDimitry Andric               Call);
363781ad6265SDimitry Andric         Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
36380b57cec5SDimitry Andric               "Incompatible argument and return types for 'returned' "
36390b57cec5SDimitry Andric               "attribute",
36400b57cec5SDimitry Andric               Call);
36410b57cec5SDimitry Andric         SawReturned = true;
36420b57cec5SDimitry Andric       }
36430b57cec5SDimitry Andric 
36440b57cec5SDimitry Andric       // Statepoint intrinsic is vararg but the wrapped function may be not.
36450b57cec5SDimitry Andric       // Allow sret here and check the wrapped function in verifyStatepoint.
36460b57cec5SDimitry Andric       if (!Call.getCalledFunction() ||
36470b57cec5SDimitry Andric           Call.getCalledFunction()->getIntrinsicID() !=
36480b57cec5SDimitry Andric               Intrinsic::experimental_gc_statepoint)
364981ad6265SDimitry Andric         Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
36500b57cec5SDimitry Andric               "Attribute 'sret' cannot be used for vararg call arguments!",
36510b57cec5SDimitry Andric               Call);
36520b57cec5SDimitry Andric 
36530b57cec5SDimitry Andric       if (ArgAttrs.hasAttribute(Attribute::InAlloca))
365481ad6265SDimitry Andric         Check(Idx == Call.arg_size() - 1,
36550b57cec5SDimitry Andric               "inalloca isn't on the last argument!", Call);
36560b57cec5SDimitry Andric     }
36570b57cec5SDimitry Andric   }
36580b57cec5SDimitry Andric 
36590b57cec5SDimitry Andric   // Verify that there's no metadata unless it's a direct call to an intrinsic.
36600b57cec5SDimitry Andric   if (!IsIntrinsic) {
36610b57cec5SDimitry Andric     for (Type *ParamTy : FTy->params()) {
366281ad6265SDimitry Andric       Check(!ParamTy->isMetadataTy(),
36630b57cec5SDimitry Andric             "Function has metadata parameter but isn't an intrinsic", Call);
366481ad6265SDimitry Andric       Check(!ParamTy->isTokenTy(),
36650b57cec5SDimitry Andric             "Function has token parameter but isn't an intrinsic", Call);
36660b57cec5SDimitry Andric     }
36670b57cec5SDimitry Andric   }
36680b57cec5SDimitry Andric 
36690b57cec5SDimitry Andric   // Verify that indirect calls don't return tokens.
3670fe6060f1SDimitry Andric   if (!Call.getCalledFunction()) {
367181ad6265SDimitry Andric     Check(!FTy->getReturnType()->isTokenTy(),
36720b57cec5SDimitry Andric           "Return type cannot be token for indirect call!");
367381ad6265SDimitry Andric     Check(!FTy->getReturnType()->isX86_AMXTy(),
3674fe6060f1SDimitry Andric           "Return type cannot be x86_amx for indirect call!");
3675fe6060f1SDimitry Andric   }
36760b57cec5SDimitry Andric 
36770b57cec5SDimitry Andric   if (Function *F = Call.getCalledFunction())
36780b57cec5SDimitry Andric     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
36790b57cec5SDimitry Andric       visitIntrinsicCall(ID, Call);
36800b57cec5SDimitry Andric 
3681480093f4SDimitry Andric   // Verify that a callsite has at most one "deopt", at most one "funclet", at
368281ad6265SDimitry Andric   // most one "gc-transition", at most one "cfguardtarget", at most one
368381ad6265SDimitry Andric   // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
36840b57cec5SDimitry Andric   bool FoundDeoptBundle = false, FoundFuncletBundle = false,
36855ffd83dbSDimitry Andric        FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
3686fe6060f1SDimitry Andric        FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
3687bdd1243dSDimitry Andric        FoundPtrauthBundle = false, FoundKCFIBundle = false,
3688fe6060f1SDimitry Andric        FoundAttachedCallBundle = false;
36890b57cec5SDimitry Andric   for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
36900b57cec5SDimitry Andric     OperandBundleUse BU = Call.getOperandBundleAt(i);
36910b57cec5SDimitry Andric     uint32_t Tag = BU.getTagID();
36920b57cec5SDimitry Andric     if (Tag == LLVMContext::OB_deopt) {
369381ad6265SDimitry Andric       Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
36940b57cec5SDimitry Andric       FoundDeoptBundle = true;
36950b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_gc_transition) {
369681ad6265SDimitry Andric       Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
36970b57cec5SDimitry Andric             Call);
36980b57cec5SDimitry Andric       FoundGCTransitionBundle = true;
36990b57cec5SDimitry Andric     } else if (Tag == LLVMContext::OB_funclet) {
370081ad6265SDimitry Andric       Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
37010b57cec5SDimitry Andric       FoundFuncletBundle = true;
370281ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
37030b57cec5SDimitry Andric             "Expected exactly one funclet bundle operand", Call);
370481ad6265SDimitry Andric       Check(isa<FuncletPadInst>(BU.Inputs.front()),
37050b57cec5SDimitry Andric             "Funclet bundle operands should correspond to a FuncletPadInst",
37060b57cec5SDimitry Andric             Call);
3707480093f4SDimitry Andric     } else if (Tag == LLVMContext::OB_cfguardtarget) {
370881ad6265SDimitry Andric       Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
370981ad6265SDimitry Andric             Call);
3710480093f4SDimitry Andric       FoundCFGuardTargetBundle = true;
371181ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
3712480093f4SDimitry Andric             "Expected exactly one cfguardtarget bundle operand", Call);
371381ad6265SDimitry Andric     } else if (Tag == LLVMContext::OB_ptrauth) {
371481ad6265SDimitry Andric       Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
371581ad6265SDimitry Andric       FoundPtrauthBundle = true;
371681ad6265SDimitry Andric       Check(BU.Inputs.size() == 2,
371781ad6265SDimitry Andric             "Expected exactly two ptrauth bundle operands", Call);
371881ad6265SDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
371981ad6265SDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
372081ad6265SDimitry Andric             "Ptrauth bundle key operand must be an i32 constant", Call);
372181ad6265SDimitry Andric       Check(BU.Inputs[1]->getType()->isIntegerTy(64),
372281ad6265SDimitry Andric             "Ptrauth bundle discriminator operand must be an i64", Call);
3723bdd1243dSDimitry Andric     } else if (Tag == LLVMContext::OB_kcfi) {
3724bdd1243dSDimitry Andric       Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
3725bdd1243dSDimitry Andric       FoundKCFIBundle = true;
3726bdd1243dSDimitry Andric       Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
3727bdd1243dSDimitry Andric             Call);
3728bdd1243dSDimitry Andric       Check(isa<ConstantInt>(BU.Inputs[0]) &&
3729bdd1243dSDimitry Andric                 BU.Inputs[0]->getType()->isIntegerTy(32),
3730bdd1243dSDimitry Andric             "Kcfi bundle operand must be an i32 constant", Call);
37315ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_preallocated) {
373281ad6265SDimitry Andric       Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
37335ffd83dbSDimitry Andric             Call);
37345ffd83dbSDimitry Andric       FoundPreallocatedBundle = true;
373581ad6265SDimitry Andric       Check(BU.Inputs.size() == 1,
37365ffd83dbSDimitry Andric             "Expected exactly one preallocated bundle operand", Call);
37375ffd83dbSDimitry Andric       auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
373881ad6265SDimitry Andric       Check(Input &&
37395ffd83dbSDimitry Andric                 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
37405ffd83dbSDimitry Andric             "\"preallocated\" argument must be a token from "
37415ffd83dbSDimitry Andric             "llvm.call.preallocated.setup",
37425ffd83dbSDimitry Andric             Call);
37435ffd83dbSDimitry Andric     } else if (Tag == LLVMContext::OB_gc_live) {
374481ad6265SDimitry Andric       Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
37455ffd83dbSDimitry Andric       FoundGCLiveBundle = true;
3746fe6060f1SDimitry Andric     } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) {
374781ad6265SDimitry Andric       Check(!FoundAttachedCallBundle,
3748fe6060f1SDimitry Andric             "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3749fe6060f1SDimitry Andric       FoundAttachedCallBundle = true;
3750349cc55cSDimitry Andric       verifyAttachedCallBundle(Call, BU);
37510b57cec5SDimitry Andric     }
37520b57cec5SDimitry Andric   }
37530b57cec5SDimitry Andric 
375481ad6265SDimitry Andric   // Verify that callee and callsite agree on whether to use pointer auth.
375581ad6265SDimitry Andric   Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
375681ad6265SDimitry Andric         "Direct call cannot have a ptrauth bundle", Call);
375781ad6265SDimitry Andric 
37580b57cec5SDimitry Andric   // Verify that each inlinable callsite of a debug-info-bearing function in a
37590b57cec5SDimitry Andric   // debug-info-bearing function has a debug location attached to it. Failure to
3760bdd1243dSDimitry Andric   // do so causes assertion failures when the inliner sets up inline scope info
3761bdd1243dSDimitry Andric   // (Interposable functions are not inlinable, neither are functions without
3762bdd1243dSDimitry Andric   //  definitions.)
37630b57cec5SDimitry Andric   if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() &&
3764bdd1243dSDimitry Andric       !Call.getCalledFunction()->isInterposable() &&
3765bdd1243dSDimitry Andric       !Call.getCalledFunction()->isDeclaration() &&
37660b57cec5SDimitry Andric       Call.getCalledFunction()->getSubprogram())
376781ad6265SDimitry Andric     CheckDI(Call.getDebugLoc(),
37680b57cec5SDimitry Andric             "inlinable function call in a function with "
37690b57cec5SDimitry Andric             "debug info must have a !dbg location",
37700b57cec5SDimitry Andric             Call);
37710b57cec5SDimitry Andric 
377204eeddc0SDimitry Andric   if (Call.isInlineAsm())
377304eeddc0SDimitry Andric     verifyInlineAsmCall(Call);
377404eeddc0SDimitry Andric 
37755f757f3fSDimitry Andric   ConvergenceVerifyHelper.visit(Call);
377606c3fb27SDimitry Andric 
37770b57cec5SDimitry Andric   visitInstruction(Call);
37780b57cec5SDimitry Andric }
37790b57cec5SDimitry Andric 
verifyTailCCMustTailAttrs(const AttrBuilder & Attrs,StringRef Context)37800eae32dcSDimitry Andric void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
3781fe6060f1SDimitry Andric                                          StringRef Context) {
378281ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InAlloca),
3783fe6060f1SDimitry Andric         Twine("inalloca attribute not allowed in ") + Context);
378481ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::InReg),
3785fe6060f1SDimitry Andric         Twine("inreg attribute not allowed in ") + Context);
378681ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::SwiftError),
3787fe6060f1SDimitry Andric         Twine("swifterror attribute not allowed in ") + Context);
378881ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::Preallocated),
3789fe6060f1SDimitry Andric         Twine("preallocated attribute not allowed in ") + Context);
379081ad6265SDimitry Andric   Check(!Attrs.contains(Attribute::ByRef),
3791fe6060f1SDimitry Andric         Twine("byref attribute not allowed in ") + Context);
3792fe6060f1SDimitry Andric }
3793fe6060f1SDimitry Andric 
37940b57cec5SDimitry Andric /// Two types are "congruent" if they are identical, or if they are both pointer
37950b57cec5SDimitry Andric /// types with different pointee types and the same address space.
isTypeCongruent(Type * L,Type * R)37960b57cec5SDimitry Andric static bool isTypeCongruent(Type *L, Type *R) {
37970b57cec5SDimitry Andric   if (L == R)
37980b57cec5SDimitry Andric     return true;
37990b57cec5SDimitry Andric   PointerType *PL = dyn_cast<PointerType>(L);
38000b57cec5SDimitry Andric   PointerType *PR = dyn_cast<PointerType>(R);
38010b57cec5SDimitry Andric   if (!PL || !PR)
38020b57cec5SDimitry Andric     return false;
38030b57cec5SDimitry Andric   return PL->getAddressSpace() == PR->getAddressSpace();
38040b57cec5SDimitry Andric }
38050b57cec5SDimitry Andric 
getParameterABIAttributes(LLVMContext & C,unsigned I,AttributeList Attrs)380604eeddc0SDimitry Andric static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
38070b57cec5SDimitry Andric   static const Attribute::AttrKind ABIAttrs[] = {
38080b57cec5SDimitry Andric       Attribute::StructRet,  Attribute::ByVal,          Attribute::InAlloca,
3809fe6060f1SDimitry Andric       Attribute::InReg,      Attribute::StackAlignment, Attribute::SwiftSelf,
3810fe6060f1SDimitry Andric       Attribute::SwiftAsync, Attribute::SwiftError,     Attribute::Preallocated,
3811fe6060f1SDimitry Andric       Attribute::ByRef};
381204eeddc0SDimitry Andric   AttrBuilder Copy(C);
38130b57cec5SDimitry Andric   for (auto AK : ABIAttrs) {
3814349cc55cSDimitry Andric     Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
3815fe6060f1SDimitry Andric     if (Attr.isValid())
3816fe6060f1SDimitry Andric       Copy.addAttribute(Attr);
38170b57cec5SDimitry Andric   }
3818e8d8bef9SDimitry Andric 
3819e8d8bef9SDimitry Andric   // `align` is ABI-affecting only in combination with `byval` or `byref`.
3820349cc55cSDimitry Andric   if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
3821349cc55cSDimitry Andric       (Attrs.hasParamAttr(I, Attribute::ByVal) ||
3822349cc55cSDimitry Andric        Attrs.hasParamAttr(I, Attribute::ByRef)))
38230b57cec5SDimitry Andric     Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
38240b57cec5SDimitry Andric   return Copy;
38250b57cec5SDimitry Andric }
38260b57cec5SDimitry Andric 
verifyMustTailCall(CallInst & CI)38270b57cec5SDimitry Andric void Verifier::verifyMustTailCall(CallInst &CI) {
382881ad6265SDimitry Andric   Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric   Function *F = CI.getParent()->getParent();
38310b57cec5SDimitry Andric   FunctionType *CallerTy = F->getFunctionType();
38320b57cec5SDimitry Andric   FunctionType *CalleeTy = CI.getFunctionType();
383381ad6265SDimitry Andric   Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
38340b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched varargs", &CI);
383581ad6265SDimitry Andric   Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
38360b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched return types", &CI);
38370b57cec5SDimitry Andric 
38380b57cec5SDimitry Andric   // - The calling conventions of the caller and callee must match.
383981ad6265SDimitry Andric   Check(F->getCallingConv() == CI.getCallingConv(),
38400b57cec5SDimitry Andric         "cannot guarantee tail call due to mismatched calling conv", &CI);
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
38430b57cec5SDimitry Andric   //   or a pointer bitcast followed by a ret instruction.
38440b57cec5SDimitry Andric   // - The ret instruction must return the (possibly bitcasted) value
38450b57cec5SDimitry Andric   //   produced by the call or void.
38460b57cec5SDimitry Andric   Value *RetVal = &CI;
38470b57cec5SDimitry Andric   Instruction *Next = CI.getNextNode();
38480b57cec5SDimitry Andric 
38490b57cec5SDimitry Andric   // Handle the optional bitcast.
38500b57cec5SDimitry Andric   if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
385181ad6265SDimitry Andric     Check(BI->getOperand(0) == RetVal,
38520b57cec5SDimitry Andric           "bitcast following musttail call must use the call", BI);
38530b57cec5SDimitry Andric     RetVal = BI;
38540b57cec5SDimitry Andric     Next = BI->getNextNode();
38550b57cec5SDimitry Andric   }
38560b57cec5SDimitry Andric 
38570b57cec5SDimitry Andric   // Check the return.
38580b57cec5SDimitry Andric   ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
385981ad6265SDimitry Andric   Check(Ret, "musttail call must precede a ret with an optional bitcast", &CI);
386081ad6265SDimitry Andric   Check(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal ||
3861fe6060f1SDimitry Andric             isa<UndefValue>(Ret->getReturnValue()),
38620b57cec5SDimitry Andric         "musttail call result must be returned", Ret);
3863fe6060f1SDimitry Andric 
3864fe6060f1SDimitry Andric   AttributeList CallerAttrs = F->getAttributes();
3865fe6060f1SDimitry Andric   AttributeList CalleeAttrs = CI.getAttributes();
3866fe6060f1SDimitry Andric   if (CI.getCallingConv() == CallingConv::SwiftTail ||
3867fe6060f1SDimitry Andric       CI.getCallingConv() == CallingConv::Tail) {
3868fe6060f1SDimitry Andric     StringRef CCName =
3869fe6060f1SDimitry Andric         CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
3870fe6060f1SDimitry Andric 
3871fe6060f1SDimitry Andric     // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
3872fe6060f1SDimitry Andric     //   are allowed in swifttailcc call
3873349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
387404eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
3875fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail caller")};
3876fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3877fe6060f1SDimitry Andric     }
3878349cc55cSDimitry Andric     for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
387904eeddc0SDimitry Andric       AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
3880fe6060f1SDimitry Andric       SmallString<32> Context{CCName, StringRef(" musttail callee")};
3881fe6060f1SDimitry Andric       verifyTailCCMustTailAttrs(ABIAttrs, Context);
3882fe6060f1SDimitry Andric     }
3883fe6060f1SDimitry Andric     // - Varargs functions are not allowed
388481ad6265SDimitry Andric     Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
3885fe6060f1SDimitry Andric                                      " tail call for varargs function");
3886fe6060f1SDimitry Andric     return;
3887fe6060f1SDimitry Andric   }
3888fe6060f1SDimitry Andric 
3889fe6060f1SDimitry Andric   // - The caller and callee prototypes must match.  Pointer types of
3890fe6060f1SDimitry Andric   //   parameters or return types may differ in pointee type, but not
3891fe6060f1SDimitry Andric   //   address space.
3892fe6060f1SDimitry Andric   if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) {
389381ad6265SDimitry Andric     Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
389481ad6265SDimitry Andric           "cannot guarantee tail call due to mismatched parameter counts", &CI);
3895349cc55cSDimitry Andric     for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
389681ad6265SDimitry Andric       Check(
3897fe6060f1SDimitry Andric           isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
3898fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched parameter types", &CI);
3899fe6060f1SDimitry Andric     }
3900fe6060f1SDimitry Andric   }
3901fe6060f1SDimitry Andric 
3902fe6060f1SDimitry Andric   // - All ABI-impacting function attributes, such as sret, byval, inreg,
3903fe6060f1SDimitry Andric   //   returned, preallocated, and inalloca, must match.
3904349cc55cSDimitry Andric   for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
390504eeddc0SDimitry Andric     AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
390604eeddc0SDimitry Andric     AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
390781ad6265SDimitry Andric     Check(CallerABIAttrs == CalleeABIAttrs,
3908fe6060f1SDimitry Andric           "cannot guarantee tail call due to mismatched ABI impacting "
3909fe6060f1SDimitry Andric           "function attributes",
3910fe6060f1SDimitry Andric           &CI, CI.getOperand(I));
3911fe6060f1SDimitry Andric   }
39120b57cec5SDimitry Andric }
39130b57cec5SDimitry Andric 
visitCallInst(CallInst & CI)39140b57cec5SDimitry Andric void Verifier::visitCallInst(CallInst &CI) {
39150b57cec5SDimitry Andric   visitCallBase(CI);
39160b57cec5SDimitry Andric 
39170b57cec5SDimitry Andric   if (CI.isMustTailCall())
39180b57cec5SDimitry Andric     verifyMustTailCall(CI);
39190b57cec5SDimitry Andric }
39200b57cec5SDimitry Andric 
visitInvokeInst(InvokeInst & II)39210b57cec5SDimitry Andric void Verifier::visitInvokeInst(InvokeInst &II) {
39220b57cec5SDimitry Andric   visitCallBase(II);
39230b57cec5SDimitry Andric 
39240b57cec5SDimitry Andric   // Verify that the first non-PHI instruction of the unwind destination is an
39250b57cec5SDimitry Andric   // exception handling instruction.
392681ad6265SDimitry Andric   Check(
39270b57cec5SDimitry Andric       II.getUnwindDest()->isEHPad(),
39280b57cec5SDimitry Andric       "The unwind destination does not have an exception handling instruction!",
39290b57cec5SDimitry Andric       &II);
39300b57cec5SDimitry Andric 
39310b57cec5SDimitry Andric   visitTerminator(II);
39320b57cec5SDimitry Andric }
39330b57cec5SDimitry Andric 
39340b57cec5SDimitry Andric /// visitUnaryOperator - Check the argument to the unary operator.
39350b57cec5SDimitry Andric ///
visitUnaryOperator(UnaryOperator & U)39360b57cec5SDimitry Andric void Verifier::visitUnaryOperator(UnaryOperator &U) {
393781ad6265SDimitry Andric   Check(U.getType() == U.getOperand(0)->getType(),
39380b57cec5SDimitry Andric         "Unary operators must have same type for"
39390b57cec5SDimitry Andric         "operands and result!",
39400b57cec5SDimitry Andric         &U);
39410b57cec5SDimitry Andric 
39420b57cec5SDimitry Andric   switch (U.getOpcode()) {
39430b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
39440b57cec5SDimitry Andric   // floating-point operands.
39450b57cec5SDimitry Andric   case Instruction::FNeg:
394681ad6265SDimitry Andric     Check(U.getType()->isFPOrFPVectorTy(),
39470b57cec5SDimitry Andric           "FNeg operator only works with float types!", &U);
39480b57cec5SDimitry Andric     break;
39490b57cec5SDimitry Andric   default:
39500b57cec5SDimitry Andric     llvm_unreachable("Unknown UnaryOperator opcode!");
39510b57cec5SDimitry Andric   }
39520b57cec5SDimitry Andric 
39530b57cec5SDimitry Andric   visitInstruction(U);
39540b57cec5SDimitry Andric }
39550b57cec5SDimitry Andric 
39560b57cec5SDimitry Andric /// visitBinaryOperator - Check that both arguments to the binary operator are
39570b57cec5SDimitry Andric /// of the same type!
39580b57cec5SDimitry Andric ///
visitBinaryOperator(BinaryOperator & B)39590b57cec5SDimitry Andric void Verifier::visitBinaryOperator(BinaryOperator &B) {
396081ad6265SDimitry Andric   Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
39610b57cec5SDimitry Andric         "Both operands to a binary operator are not of the same type!", &B);
39620b57cec5SDimitry Andric 
39630b57cec5SDimitry Andric   switch (B.getOpcode()) {
39640b57cec5SDimitry Andric   // Check that integer arithmetic operators are only used with
39650b57cec5SDimitry Andric   // integral operands.
39660b57cec5SDimitry Andric   case Instruction::Add:
39670b57cec5SDimitry Andric   case Instruction::Sub:
39680b57cec5SDimitry Andric   case Instruction::Mul:
39690b57cec5SDimitry Andric   case Instruction::SDiv:
39700b57cec5SDimitry Andric   case Instruction::UDiv:
39710b57cec5SDimitry Andric   case Instruction::SRem:
39720b57cec5SDimitry Andric   case Instruction::URem:
397381ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
39740b57cec5SDimitry Andric           "Integer arithmetic operators only work with integral types!", &B);
397581ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
39760b57cec5SDimitry Andric           "Integer arithmetic operators must have same type "
39770b57cec5SDimitry Andric           "for operands and result!",
39780b57cec5SDimitry Andric           &B);
39790b57cec5SDimitry Andric     break;
39800b57cec5SDimitry Andric   // Check that floating-point arithmetic operators are only used with
39810b57cec5SDimitry Andric   // floating-point operands.
39820b57cec5SDimitry Andric   case Instruction::FAdd:
39830b57cec5SDimitry Andric   case Instruction::FSub:
39840b57cec5SDimitry Andric   case Instruction::FMul:
39850b57cec5SDimitry Andric   case Instruction::FDiv:
39860b57cec5SDimitry Andric   case Instruction::FRem:
398781ad6265SDimitry Andric     Check(B.getType()->isFPOrFPVectorTy(),
39880b57cec5SDimitry Andric           "Floating-point arithmetic operators only work with "
39890b57cec5SDimitry Andric           "floating-point types!",
39900b57cec5SDimitry Andric           &B);
399181ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
39920b57cec5SDimitry Andric           "Floating-point arithmetic operators must have same type "
39930b57cec5SDimitry Andric           "for operands and result!",
39940b57cec5SDimitry Andric           &B);
39950b57cec5SDimitry Andric     break;
39960b57cec5SDimitry Andric   // Check that logical operators are only used with integral operands.
39970b57cec5SDimitry Andric   case Instruction::And:
39980b57cec5SDimitry Andric   case Instruction::Or:
39990b57cec5SDimitry Andric   case Instruction::Xor:
400081ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
40010b57cec5SDimitry Andric           "Logical operators only work with integral types!", &B);
400281ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
400381ad6265SDimitry Andric           "Logical operators must have same type for operands and result!", &B);
40040b57cec5SDimitry Andric     break;
40050b57cec5SDimitry Andric   case Instruction::Shl:
40060b57cec5SDimitry Andric   case Instruction::LShr:
40070b57cec5SDimitry Andric   case Instruction::AShr:
400881ad6265SDimitry Andric     Check(B.getType()->isIntOrIntVectorTy(),
40090b57cec5SDimitry Andric           "Shifts only work with integral types!", &B);
401081ad6265SDimitry Andric     Check(B.getType() == B.getOperand(0)->getType(),
40110b57cec5SDimitry Andric           "Shift return type must be same as operands!", &B);
40120b57cec5SDimitry Andric     break;
40130b57cec5SDimitry Andric   default:
40140b57cec5SDimitry Andric     llvm_unreachable("Unknown BinaryOperator opcode!");
40150b57cec5SDimitry Andric   }
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric   visitInstruction(B);
40180b57cec5SDimitry Andric }
40190b57cec5SDimitry Andric 
visitICmpInst(ICmpInst & IC)40200b57cec5SDimitry Andric void Verifier::visitICmpInst(ICmpInst &IC) {
40210b57cec5SDimitry Andric   // Check that the operands are the same type
40220b57cec5SDimitry Andric   Type *Op0Ty = IC.getOperand(0)->getType();
40230b57cec5SDimitry Andric   Type *Op1Ty = IC.getOperand(1)->getType();
402481ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
40250b57cec5SDimitry Andric         "Both operands to ICmp instruction are not of the same type!", &IC);
40260b57cec5SDimitry Andric   // Check that the operands are the right type
402781ad6265SDimitry Andric   Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
40280b57cec5SDimitry Andric         "Invalid operand types for ICmp instruction", &IC);
40290b57cec5SDimitry Andric   // Check that the predicate is valid.
403081ad6265SDimitry Andric   Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
40310b57cec5SDimitry Andric 
40320b57cec5SDimitry Andric   visitInstruction(IC);
40330b57cec5SDimitry Andric }
40340b57cec5SDimitry Andric 
visitFCmpInst(FCmpInst & FC)40350b57cec5SDimitry Andric void Verifier::visitFCmpInst(FCmpInst &FC) {
40360b57cec5SDimitry Andric   // Check that the operands are the same type
40370b57cec5SDimitry Andric   Type *Op0Ty = FC.getOperand(0)->getType();
40380b57cec5SDimitry Andric   Type *Op1Ty = FC.getOperand(1)->getType();
403981ad6265SDimitry Andric   Check(Op0Ty == Op1Ty,
40400b57cec5SDimitry Andric         "Both operands to FCmp instruction are not of the same type!", &FC);
40410b57cec5SDimitry Andric   // Check that the operands are the right type
404281ad6265SDimitry Andric   Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
404381ad6265SDimitry Andric         &FC);
40440b57cec5SDimitry Andric   // Check that the predicate is valid.
404581ad6265SDimitry Andric   Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
40460b57cec5SDimitry Andric 
40470b57cec5SDimitry Andric   visitInstruction(FC);
40480b57cec5SDimitry Andric }
40490b57cec5SDimitry Andric 
visitExtractElementInst(ExtractElementInst & EI)40500b57cec5SDimitry Andric void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
405181ad6265SDimitry Andric   Check(ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
40520b57cec5SDimitry Andric         "Invalid extractelement operands!", &EI);
40530b57cec5SDimitry Andric   visitInstruction(EI);
40540b57cec5SDimitry Andric }
40550b57cec5SDimitry Andric 
visitInsertElementInst(InsertElementInst & IE)40560b57cec5SDimitry Andric void Verifier::visitInsertElementInst(InsertElementInst &IE) {
405781ad6265SDimitry Andric   Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
40580b57cec5SDimitry Andric                                            IE.getOperand(2)),
40590b57cec5SDimitry Andric         "Invalid insertelement operands!", &IE);
40600b57cec5SDimitry Andric   visitInstruction(IE);
40610b57cec5SDimitry Andric }
40620b57cec5SDimitry Andric 
visitShuffleVectorInst(ShuffleVectorInst & SV)40630b57cec5SDimitry Andric void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
406481ad6265SDimitry Andric   Check(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
40655ffd83dbSDimitry Andric                                            SV.getShuffleMask()),
40660b57cec5SDimitry Andric         "Invalid shufflevector operands!", &SV);
40670b57cec5SDimitry Andric   visitInstruction(SV);
40680b57cec5SDimitry Andric }
40690b57cec5SDimitry Andric 
visitGetElementPtrInst(GetElementPtrInst & GEP)40700b57cec5SDimitry Andric void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
40710b57cec5SDimitry Andric   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
40720b57cec5SDimitry Andric 
407381ad6265SDimitry Andric   Check(isa<PointerType>(TargetTy),
40740b57cec5SDimitry Andric         "GEP base pointer is not a vector or a vector of pointers", &GEP);
407581ad6265SDimitry Andric   Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
40760b57cec5SDimitry Andric 
407706c3fb27SDimitry Andric   if (auto *STy = dyn_cast<StructType>(GEP.getSourceElementType())) {
407806c3fb27SDimitry Andric     SmallPtrSet<Type *, 4> Visited;
407906c3fb27SDimitry Andric     Check(!STy->containsScalableVectorType(&Visited),
408006c3fb27SDimitry Andric           "getelementptr cannot target structure that contains scalable vector"
408106c3fb27SDimitry Andric           "type",
408206c3fb27SDimitry Andric           &GEP);
408306c3fb27SDimitry Andric   }
408406c3fb27SDimitry Andric 
4085e8d8bef9SDimitry Andric   SmallVector<Value *, 16> Idxs(GEP.indices());
408681ad6265SDimitry Andric   Check(
408781ad6265SDimitry Andric       all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
40880b57cec5SDimitry Andric       "GEP indexes must be integers", &GEP);
40890b57cec5SDimitry Andric   Type *ElTy =
40900b57cec5SDimitry Andric       GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
409181ad6265SDimitry Andric   Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
40920b57cec5SDimitry Andric 
409381ad6265SDimitry Andric   Check(GEP.getType()->isPtrOrPtrVectorTy() &&
40940b57cec5SDimitry Andric             GEP.getResultElementType() == ElTy,
40950b57cec5SDimitry Andric         "GEP is not of right type for indices!", &GEP, ElTy);
40960b57cec5SDimitry Andric 
40975ffd83dbSDimitry Andric   if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
40980b57cec5SDimitry Andric     // Additional checks for vector GEPs.
40995ffd83dbSDimitry Andric     ElementCount GEPWidth = GEPVTy->getElementCount();
41000b57cec5SDimitry Andric     if (GEP.getPointerOperandType()->isVectorTy())
410181ad6265SDimitry Andric       Check(
41025ffd83dbSDimitry Andric           GEPWidth ==
41035ffd83dbSDimitry Andric               cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
41040b57cec5SDimitry Andric           "Vector GEP result width doesn't match operand's", &GEP);
41050b57cec5SDimitry Andric     for (Value *Idx : Idxs) {
41060b57cec5SDimitry Andric       Type *IndexTy = Idx->getType();
41075ffd83dbSDimitry Andric       if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
41085ffd83dbSDimitry Andric         ElementCount IndexWidth = IndexVTy->getElementCount();
410981ad6265SDimitry Andric         Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
41100b57cec5SDimitry Andric       }
411181ad6265SDimitry Andric       Check(IndexTy->isIntOrIntVectorTy(),
41120b57cec5SDimitry Andric             "All GEP indices should be of integer type");
41130b57cec5SDimitry Andric     }
41140b57cec5SDimitry Andric   }
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
411781ad6265SDimitry Andric     Check(GEP.getAddressSpace() == PTy->getAddressSpace(),
41180b57cec5SDimitry Andric           "GEP address space doesn't match type", &GEP);
41190b57cec5SDimitry Andric   }
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric   visitInstruction(GEP);
41220b57cec5SDimitry Andric }
41230b57cec5SDimitry Andric 
isContiguous(const ConstantRange & A,const ConstantRange & B)41240b57cec5SDimitry Andric static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
41250b57cec5SDimitry Andric   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
41260b57cec5SDimitry Andric }
41270b57cec5SDimitry Andric 
412806c3fb27SDimitry Andric /// Verify !range and !absolute_symbol metadata. These have the same
412906c3fb27SDimitry Andric /// restrictions, except !absolute_symbol allows the full set.
verifyRangeMetadata(const Value & I,const MDNode * Range,Type * Ty,bool IsAbsoluteSymbol)413006c3fb27SDimitry Andric void Verifier::verifyRangeMetadata(const Value &I, const MDNode *Range,
413106c3fb27SDimitry Andric                                    Type *Ty, bool IsAbsoluteSymbol) {
41320b57cec5SDimitry Andric   unsigned NumOperands = Range->getNumOperands();
413381ad6265SDimitry Andric   Check(NumOperands % 2 == 0, "Unfinished range!", Range);
41340b57cec5SDimitry Andric   unsigned NumRanges = NumOperands / 2;
413581ad6265SDimitry Andric   Check(NumRanges >= 1, "It should have at least one range!", Range);
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric   ConstantRange LastRange(1, true); // Dummy initial value
41380b57cec5SDimitry Andric   for (unsigned i = 0; i < NumRanges; ++i) {
41390b57cec5SDimitry Andric     ConstantInt *Low =
41400b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
414181ad6265SDimitry Andric     Check(Low, "The lower limit must be an integer!", Low);
41420b57cec5SDimitry Andric     ConstantInt *High =
41430b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
414481ad6265SDimitry Andric     Check(High, "The upper limit must be an integer!", High);
414506c3fb27SDimitry Andric     Check(High->getType() == Low->getType() &&
414606c3fb27SDimitry Andric           High->getType() == Ty->getScalarType(),
41470b57cec5SDimitry Andric           "Range types must match instruction type!", &I);
41480b57cec5SDimitry Andric 
41490b57cec5SDimitry Andric     APInt HighV = High->getValue();
41500b57cec5SDimitry Andric     APInt LowV = Low->getValue();
415106c3fb27SDimitry Andric 
415206c3fb27SDimitry Andric     // ConstantRange asserts if the ranges are the same except for the min/max
415306c3fb27SDimitry Andric     // value. Leave the cases it tolerates for the empty range error below.
415406c3fb27SDimitry Andric     Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
415506c3fb27SDimitry Andric           "The upper and lower limits cannot be the same value", &I);
415606c3fb27SDimitry Andric 
41570b57cec5SDimitry Andric     ConstantRange CurRange(LowV, HighV);
415806c3fb27SDimitry Andric     Check(!CurRange.isEmptySet() && (IsAbsoluteSymbol || !CurRange.isFullSet()),
41590b57cec5SDimitry Andric           "Range must not be empty!", Range);
41600b57cec5SDimitry Andric     if (i != 0) {
416181ad6265SDimitry Andric       Check(CurRange.intersectWith(LastRange).isEmptySet(),
41620b57cec5SDimitry Andric             "Intervals are overlapping", Range);
416381ad6265SDimitry Andric       Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
41640b57cec5SDimitry Andric             Range);
416581ad6265SDimitry Andric       Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
41660b57cec5SDimitry Andric             Range);
41670b57cec5SDimitry Andric     }
41680b57cec5SDimitry Andric     LastRange = ConstantRange(LowV, HighV);
41690b57cec5SDimitry Andric   }
41700b57cec5SDimitry Andric   if (NumRanges > 2) {
41710b57cec5SDimitry Andric     APInt FirstLow =
41720b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
41730b57cec5SDimitry Andric     APInt FirstHigh =
41740b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
41750b57cec5SDimitry Andric     ConstantRange FirstRange(FirstLow, FirstHigh);
417681ad6265SDimitry Andric     Check(FirstRange.intersectWith(LastRange).isEmptySet(),
41770b57cec5SDimitry Andric           "Intervals are overlapping", Range);
417881ad6265SDimitry Andric     Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
41790b57cec5SDimitry Andric           Range);
41800b57cec5SDimitry Andric   }
41810b57cec5SDimitry Andric }
41820b57cec5SDimitry Andric 
visitRangeMetadata(Instruction & I,MDNode * Range,Type * Ty)418306c3fb27SDimitry Andric void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
418406c3fb27SDimitry Andric   assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
418506c3fb27SDimitry Andric          "precondition violation");
418606c3fb27SDimitry Andric   verifyRangeMetadata(I, Range, Ty, false);
418706c3fb27SDimitry Andric }
418806c3fb27SDimitry Andric 
checkAtomicMemAccessSize(Type * Ty,const Instruction * I)41890b57cec5SDimitry Andric void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
41900b57cec5SDimitry Andric   unsigned Size = DL.getTypeSizeInBits(Ty);
419181ad6265SDimitry Andric   Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
419281ad6265SDimitry Andric   Check(!(Size & (Size - 1)),
41930b57cec5SDimitry Andric         "atomic memory access' operand must have a power-of-two size", Ty, I);
41940b57cec5SDimitry Andric }
41950b57cec5SDimitry Andric 
visitLoadInst(LoadInst & LI)41960b57cec5SDimitry Andric void Verifier::visitLoadInst(LoadInst &LI) {
41970b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
419881ad6265SDimitry Andric   Check(PTy, "Load operand must be a pointer.", &LI);
41990b57cec5SDimitry Andric   Type *ElTy = LI.getType();
42000eae32dcSDimitry Andric   if (MaybeAlign A = LI.getAlign()) {
420181ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
42020b57cec5SDimitry Andric           "huge alignment values are unsupported", &LI);
42030eae32dcSDimitry Andric   }
420481ad6265SDimitry Andric   Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
42050b57cec5SDimitry Andric   if (LI.isAtomic()) {
420681ad6265SDimitry Andric     Check(LI.getOrdering() != AtomicOrdering::Release &&
42070b57cec5SDimitry Andric               LI.getOrdering() != AtomicOrdering::AcquireRelease,
42080b57cec5SDimitry Andric           "Load cannot have Release ordering", &LI);
420981ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
42100b57cec5SDimitry Andric           "atomic load operand must have integer, pointer, or floating point "
42110b57cec5SDimitry Andric           "type!",
42120b57cec5SDimitry Andric           ElTy, &LI);
42130b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &LI);
42140b57cec5SDimitry Andric   } else {
421581ad6265SDimitry Andric     Check(LI.getSyncScopeID() == SyncScope::System,
42160b57cec5SDimitry Andric           "Non-atomic load cannot have SynchronizationScope specified", &LI);
42170b57cec5SDimitry Andric   }
42180b57cec5SDimitry Andric 
42190b57cec5SDimitry Andric   visitInstruction(LI);
42200b57cec5SDimitry Andric }
42210b57cec5SDimitry Andric 
visitStoreInst(StoreInst & SI)42220b57cec5SDimitry Andric void Verifier::visitStoreInst(StoreInst &SI) {
42230b57cec5SDimitry Andric   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
422481ad6265SDimitry Andric   Check(PTy, "Store operand must be a pointer.", &SI);
4225fe6060f1SDimitry Andric   Type *ElTy = SI.getOperand(0)->getType();
42260eae32dcSDimitry Andric   if (MaybeAlign A = SI.getAlign()) {
422781ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
42280b57cec5SDimitry Andric           "huge alignment values are unsupported", &SI);
42290eae32dcSDimitry Andric   }
423081ad6265SDimitry Andric   Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
42310b57cec5SDimitry Andric   if (SI.isAtomic()) {
423281ad6265SDimitry Andric     Check(SI.getOrdering() != AtomicOrdering::Acquire &&
42330b57cec5SDimitry Andric               SI.getOrdering() != AtomicOrdering::AcquireRelease,
42340b57cec5SDimitry Andric           "Store cannot have Acquire ordering", &SI);
423581ad6265SDimitry Andric     Check(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(),
42360b57cec5SDimitry Andric           "atomic store operand must have integer, pointer, or floating point "
42370b57cec5SDimitry Andric           "type!",
42380b57cec5SDimitry Andric           ElTy, &SI);
42390b57cec5SDimitry Andric     checkAtomicMemAccessSize(ElTy, &SI);
42400b57cec5SDimitry Andric   } else {
424181ad6265SDimitry Andric     Check(SI.getSyncScopeID() == SyncScope::System,
42420b57cec5SDimitry Andric           "Non-atomic store cannot have SynchronizationScope specified", &SI);
42430b57cec5SDimitry Andric   }
42440b57cec5SDimitry Andric   visitInstruction(SI);
42450b57cec5SDimitry Andric }
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric /// Check that SwiftErrorVal is used as a swifterror argument in CS.
verifySwiftErrorCall(CallBase & Call,const Value * SwiftErrorVal)42480b57cec5SDimitry Andric void Verifier::verifySwiftErrorCall(CallBase &Call,
42490b57cec5SDimitry Andric                                     const Value *SwiftErrorVal) {
4250fe6060f1SDimitry Andric   for (const auto &I : llvm::enumerate(Call.args())) {
4251fe6060f1SDimitry Andric     if (I.value() == SwiftErrorVal) {
425281ad6265SDimitry Andric       Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
42530b57cec5SDimitry Andric             "swifterror value when used in a callsite should be marked "
42540b57cec5SDimitry Andric             "with swifterror attribute",
42550b57cec5SDimitry Andric             SwiftErrorVal, Call);
42560b57cec5SDimitry Andric     }
42570b57cec5SDimitry Andric   }
42580b57cec5SDimitry Andric }
42590b57cec5SDimitry Andric 
verifySwiftErrorValue(const Value * SwiftErrorVal)42600b57cec5SDimitry Andric void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
42610b57cec5SDimitry Andric   // Check that swifterror value is only used by loads, stores, or as
42620b57cec5SDimitry Andric   // a swifterror argument.
42630b57cec5SDimitry Andric   for (const User *U : SwiftErrorVal->users()) {
426481ad6265SDimitry Andric     Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
42650b57cec5SDimitry Andric               isa<InvokeInst>(U),
42660b57cec5SDimitry Andric           "swifterror value can only be loaded and stored from, or "
42670b57cec5SDimitry Andric           "as a swifterror argument!",
42680b57cec5SDimitry Andric           SwiftErrorVal, U);
42690b57cec5SDimitry Andric     // If it is used by a store, check it is the second operand.
42700b57cec5SDimitry Andric     if (auto StoreI = dyn_cast<StoreInst>(U))
427181ad6265SDimitry Andric       Check(StoreI->getOperand(1) == SwiftErrorVal,
42720b57cec5SDimitry Andric             "swifterror value should be the second operand when used "
427381ad6265SDimitry Andric             "by stores",
427481ad6265SDimitry Andric             SwiftErrorVal, U);
42750b57cec5SDimitry Andric     if (auto *Call = dyn_cast<CallBase>(U))
42760b57cec5SDimitry Andric       verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
42770b57cec5SDimitry Andric   }
42780b57cec5SDimitry Andric }
42790b57cec5SDimitry Andric 
visitAllocaInst(AllocaInst & AI)42800b57cec5SDimitry Andric void Verifier::visitAllocaInst(AllocaInst &AI) {
42810b57cec5SDimitry Andric   SmallPtrSet<Type*, 4> Visited;
428281ad6265SDimitry Andric   Check(AI.getAllocatedType()->isSized(&Visited),
42830b57cec5SDimitry Andric         "Cannot allocate unsized type", &AI);
428481ad6265SDimitry Andric   Check(AI.getArraySize()->getType()->isIntegerTy(),
42850b57cec5SDimitry Andric         "Alloca array size must have integer type", &AI);
42860eae32dcSDimitry Andric   if (MaybeAlign A = AI.getAlign()) {
428781ad6265SDimitry Andric     Check(A->value() <= Value::MaximumAlignment,
42880b57cec5SDimitry Andric           "huge alignment values are unsupported", &AI);
42890eae32dcSDimitry Andric   }
42900b57cec5SDimitry Andric 
42910b57cec5SDimitry Andric   if (AI.isSwiftError()) {
429281ad6265SDimitry Andric     Check(AI.getAllocatedType()->isPointerTy(),
429381ad6265SDimitry Andric           "swifterror alloca must have pointer type", &AI);
429481ad6265SDimitry Andric     Check(!AI.isArrayAllocation(),
429581ad6265SDimitry Andric           "swifterror alloca must not be array allocation", &AI);
42960b57cec5SDimitry Andric     verifySwiftErrorValue(&AI);
42970b57cec5SDimitry Andric   }
42980b57cec5SDimitry Andric 
42990b57cec5SDimitry Andric   visitInstruction(AI);
43000b57cec5SDimitry Andric }
43010b57cec5SDimitry Andric 
visitAtomicCmpXchgInst(AtomicCmpXchgInst & CXI)43020b57cec5SDimitry Andric void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4303fe6060f1SDimitry Andric   Type *ElTy = CXI.getOperand(1)->getType();
430481ad6265SDimitry Andric   Check(ElTy->isIntOrPtrTy(),
43050b57cec5SDimitry Andric         "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
43060b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &CXI);
43070b57cec5SDimitry Andric   visitInstruction(CXI);
43080b57cec5SDimitry Andric }
43090b57cec5SDimitry Andric 
visitAtomicRMWInst(AtomicRMWInst & RMWI)43100b57cec5SDimitry Andric void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
431181ad6265SDimitry Andric   Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
43120b57cec5SDimitry Andric         "atomicrmw instructions cannot be unordered.", &RMWI);
43130b57cec5SDimitry Andric   auto Op = RMWI.getOperation();
4314fe6060f1SDimitry Andric   Type *ElTy = RMWI.getOperand(1)->getType();
43150b57cec5SDimitry Andric   if (Op == AtomicRMWInst::Xchg) {
431681ad6265SDimitry Andric     Check(ElTy->isIntegerTy() || ElTy->isFloatingPointTy() ||
431781ad6265SDimitry Andric               ElTy->isPointerTy(),
431881ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
43190b57cec5SDimitry Andric               " operand must have integer or floating point type!",
43200b57cec5SDimitry Andric           &RMWI, ElTy);
43210b57cec5SDimitry Andric   } else if (AtomicRMWInst::isFPOperation(Op)) {
4322*0fca6ea1SDimitry Andric     Check(ElTy->isFPOrFPVectorTy() && !isa<ScalableVectorType>(ElTy),
432381ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
4324*0fca6ea1SDimitry Andric               " operand must have floating-point or fixed vector of floating-point "
4325*0fca6ea1SDimitry Andric               "type!",
43260b57cec5SDimitry Andric           &RMWI, ElTy);
43270b57cec5SDimitry Andric   } else {
432881ad6265SDimitry Andric     Check(ElTy->isIntegerTy(),
432981ad6265SDimitry Andric           "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
43300b57cec5SDimitry Andric               " operand must have integer type!",
43310b57cec5SDimitry Andric           &RMWI, ElTy);
43320b57cec5SDimitry Andric   }
43330b57cec5SDimitry Andric   checkAtomicMemAccessSize(ElTy, &RMWI);
433481ad6265SDimitry Andric   Check(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP,
43350b57cec5SDimitry Andric         "Invalid binary operation!", &RMWI);
43360b57cec5SDimitry Andric   visitInstruction(RMWI);
43370b57cec5SDimitry Andric }
43380b57cec5SDimitry Andric 
visitFenceInst(FenceInst & FI)43390b57cec5SDimitry Andric void Verifier::visitFenceInst(FenceInst &FI) {
43400b57cec5SDimitry Andric   const AtomicOrdering Ordering = FI.getOrdering();
434181ad6265SDimitry Andric   Check(Ordering == AtomicOrdering::Acquire ||
43420b57cec5SDimitry Andric             Ordering == AtomicOrdering::Release ||
43430b57cec5SDimitry Andric             Ordering == AtomicOrdering::AcquireRelease ||
43440b57cec5SDimitry Andric             Ordering == AtomicOrdering::SequentiallyConsistent,
43450b57cec5SDimitry Andric         "fence instructions may only have acquire, release, acq_rel, or "
43460b57cec5SDimitry Andric         "seq_cst ordering.",
43470b57cec5SDimitry Andric         &FI);
43480b57cec5SDimitry Andric   visitInstruction(FI);
43490b57cec5SDimitry Andric }
43500b57cec5SDimitry Andric 
visitExtractValueInst(ExtractValueInst & EVI)43510b57cec5SDimitry Andric void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
435281ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
43530b57cec5SDimitry Andric                                          EVI.getIndices()) == EVI.getType(),
43540b57cec5SDimitry Andric         "Invalid ExtractValueInst operands!", &EVI);
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric   visitInstruction(EVI);
43570b57cec5SDimitry Andric }
43580b57cec5SDimitry Andric 
visitInsertValueInst(InsertValueInst & IVI)43590b57cec5SDimitry Andric void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
436081ad6265SDimitry Andric   Check(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
43610b57cec5SDimitry Andric                                          IVI.getIndices()) ==
43620b57cec5SDimitry Andric             IVI.getOperand(1)->getType(),
43630b57cec5SDimitry Andric         "Invalid InsertValueInst operands!", &IVI);
43640b57cec5SDimitry Andric 
43650b57cec5SDimitry Andric   visitInstruction(IVI);
43660b57cec5SDimitry Andric }
43670b57cec5SDimitry Andric 
getParentPad(Value * EHPad)43680b57cec5SDimitry Andric static Value *getParentPad(Value *EHPad) {
43690b57cec5SDimitry Andric   if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
43700b57cec5SDimitry Andric     return FPI->getParentPad();
43710b57cec5SDimitry Andric 
43720b57cec5SDimitry Andric   return cast<CatchSwitchInst>(EHPad)->getParentPad();
43730b57cec5SDimitry Andric }
43740b57cec5SDimitry Andric 
visitEHPadPredecessors(Instruction & I)43750b57cec5SDimitry Andric void Verifier::visitEHPadPredecessors(Instruction &I) {
43760b57cec5SDimitry Andric   assert(I.isEHPad());
43770b57cec5SDimitry Andric 
43780b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
43790b57cec5SDimitry Andric   Function *F = BB->getParent();
43800b57cec5SDimitry Andric 
438181ad6265SDimitry Andric   Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
43820b57cec5SDimitry Andric 
43830b57cec5SDimitry Andric   if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
43840b57cec5SDimitry Andric     // The landingpad instruction defines its parent as a landing pad block. The
43850b57cec5SDimitry Andric     // landing pad block may be branched to only by the unwind edge of an
43860b57cec5SDimitry Andric     // invoke.
43870b57cec5SDimitry Andric     for (BasicBlock *PredBB : predecessors(BB)) {
43880b57cec5SDimitry Andric       const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
438981ad6265SDimitry Andric       Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
43900b57cec5SDimitry Andric             "Block containing LandingPadInst must be jumped to "
43910b57cec5SDimitry Andric             "only by the unwind edge of an invoke.",
43920b57cec5SDimitry Andric             LPI);
43930b57cec5SDimitry Andric     }
43940b57cec5SDimitry Andric     return;
43950b57cec5SDimitry Andric   }
43960b57cec5SDimitry Andric   if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
43970b57cec5SDimitry Andric     if (!pred_empty(BB))
439881ad6265SDimitry Andric       Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
43990b57cec5SDimitry Andric             "Block containg CatchPadInst must be jumped to "
44000b57cec5SDimitry Andric             "only by its catchswitch.",
44010b57cec5SDimitry Andric             CPI);
440281ad6265SDimitry Andric     Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
44030b57cec5SDimitry Andric           "Catchswitch cannot unwind to one of its catchpads",
44040b57cec5SDimitry Andric           CPI->getCatchSwitch(), CPI);
44050b57cec5SDimitry Andric     return;
44060b57cec5SDimitry Andric   }
44070b57cec5SDimitry Andric 
44080b57cec5SDimitry Andric   // Verify that each pred has a legal terminator with a legal to/from EH
44090b57cec5SDimitry Andric   // pad relationship.
44100b57cec5SDimitry Andric   Instruction *ToPad = &I;
44110b57cec5SDimitry Andric   Value *ToPadParent = getParentPad(ToPad);
44120b57cec5SDimitry Andric   for (BasicBlock *PredBB : predecessors(BB)) {
44130b57cec5SDimitry Andric     Instruction *TI = PredBB->getTerminator();
44140b57cec5SDimitry Andric     Value *FromPad;
44150b57cec5SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(TI)) {
441681ad6265SDimitry Andric       Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
44170b57cec5SDimitry Andric             "EH pad must be jumped to via an unwind edge", ToPad, II);
4418*0fca6ea1SDimitry Andric       auto *CalledFn =
4419*0fca6ea1SDimitry Andric           dyn_cast<Function>(II->getCalledOperand()->stripPointerCasts());
4420*0fca6ea1SDimitry Andric       if (CalledFn && CalledFn->isIntrinsic() && II->doesNotThrow() &&
4421*0fca6ea1SDimitry Andric           !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
4422*0fca6ea1SDimitry Andric         continue;
44230b57cec5SDimitry Andric       if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
44240b57cec5SDimitry Andric         FromPad = Bundle->Inputs[0];
44250b57cec5SDimitry Andric       else
44260b57cec5SDimitry Andric         FromPad = ConstantTokenNone::get(II->getContext());
44270b57cec5SDimitry Andric     } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
44280b57cec5SDimitry Andric       FromPad = CRI->getOperand(0);
442981ad6265SDimitry Andric       Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
44300b57cec5SDimitry Andric     } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
44310b57cec5SDimitry Andric       FromPad = CSI;
44320b57cec5SDimitry Andric     } else {
443381ad6265SDimitry Andric       Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
44340b57cec5SDimitry Andric     }
44350b57cec5SDimitry Andric 
44360b57cec5SDimitry Andric     // The edge may exit from zero or more nested pads.
44370b57cec5SDimitry Andric     SmallSet<Value *, 8> Seen;
44380b57cec5SDimitry Andric     for (;; FromPad = getParentPad(FromPad)) {
443981ad6265SDimitry Andric       Check(FromPad != ToPad,
44400b57cec5SDimitry Andric             "EH pad cannot handle exceptions raised within it", FromPad, TI);
44410b57cec5SDimitry Andric       if (FromPad == ToPadParent) {
44420b57cec5SDimitry Andric         // This is a legal unwind edge.
44430b57cec5SDimitry Andric         break;
44440b57cec5SDimitry Andric       }
444581ad6265SDimitry Andric       Check(!isa<ConstantTokenNone>(FromPad),
44460b57cec5SDimitry Andric             "A single unwind edge may only enter one EH pad", TI);
444781ad6265SDimitry Andric       Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
444881ad6265SDimitry Andric             FromPad);
444904eeddc0SDimitry Andric 
445004eeddc0SDimitry Andric       // This will be diagnosed on the corresponding instruction already. We
445104eeddc0SDimitry Andric       // need the extra check here to make sure getParentPad() works.
445281ad6265SDimitry Andric       Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
445304eeddc0SDimitry Andric             "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
44540b57cec5SDimitry Andric     }
44550b57cec5SDimitry Andric   }
44560b57cec5SDimitry Andric }
44570b57cec5SDimitry Andric 
visitLandingPadInst(LandingPadInst & LPI)44580b57cec5SDimitry Andric void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
44590b57cec5SDimitry Andric   // The landingpad instruction is ill-formed if it doesn't have any clauses and
44600b57cec5SDimitry Andric   // isn't a cleanup.
446181ad6265SDimitry Andric   Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
44620b57cec5SDimitry Andric         "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
44630b57cec5SDimitry Andric 
44640b57cec5SDimitry Andric   visitEHPadPredecessors(LPI);
44650b57cec5SDimitry Andric 
44660b57cec5SDimitry Andric   if (!LandingPadResultTy)
44670b57cec5SDimitry Andric     LandingPadResultTy = LPI.getType();
44680b57cec5SDimitry Andric   else
446981ad6265SDimitry Andric     Check(LandingPadResultTy == LPI.getType(),
44700b57cec5SDimitry Andric           "The landingpad instruction should have a consistent result type "
44710b57cec5SDimitry Andric           "inside a function.",
44720b57cec5SDimitry Andric           &LPI);
44730b57cec5SDimitry Andric 
44740b57cec5SDimitry Andric   Function *F = LPI.getParent()->getParent();
447581ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
44760b57cec5SDimitry Andric         "LandingPadInst needs to be in a function with a personality.", &LPI);
44770b57cec5SDimitry Andric 
44780b57cec5SDimitry Andric   // The landingpad instruction must be the first non-PHI instruction in the
44790b57cec5SDimitry Andric   // block.
448081ad6265SDimitry Andric   Check(LPI.getParent()->getLandingPadInst() == &LPI,
448181ad6265SDimitry Andric         "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
44820b57cec5SDimitry Andric 
44830b57cec5SDimitry Andric   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
44840b57cec5SDimitry Andric     Constant *Clause = LPI.getClause(i);
44850b57cec5SDimitry Andric     if (LPI.isCatch(i)) {
448681ad6265SDimitry Andric       Check(isa<PointerType>(Clause->getType()),
44870b57cec5SDimitry Andric             "Catch operand does not have pointer type!", &LPI);
44880b57cec5SDimitry Andric     } else {
448981ad6265SDimitry Andric       Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
449081ad6265SDimitry Andric       Check(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
44910b57cec5SDimitry Andric             "Filter operand is not an array of constants!", &LPI);
44920b57cec5SDimitry Andric     }
44930b57cec5SDimitry Andric   }
44940b57cec5SDimitry Andric 
44950b57cec5SDimitry Andric   visitInstruction(LPI);
44960b57cec5SDimitry Andric }
44970b57cec5SDimitry Andric 
visitResumeInst(ResumeInst & RI)44980b57cec5SDimitry Andric void Verifier::visitResumeInst(ResumeInst &RI) {
449981ad6265SDimitry Andric   Check(RI.getFunction()->hasPersonalityFn(),
45000b57cec5SDimitry Andric         "ResumeInst needs to be in a function with a personality.", &RI);
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric   if (!LandingPadResultTy)
45030b57cec5SDimitry Andric     LandingPadResultTy = RI.getValue()->getType();
45040b57cec5SDimitry Andric   else
450581ad6265SDimitry Andric     Check(LandingPadResultTy == RI.getValue()->getType(),
45060b57cec5SDimitry Andric           "The resume instruction should have a consistent result type "
45070b57cec5SDimitry Andric           "inside a function.",
45080b57cec5SDimitry Andric           &RI);
45090b57cec5SDimitry Andric 
45100b57cec5SDimitry Andric   visitTerminator(RI);
45110b57cec5SDimitry Andric }
45120b57cec5SDimitry Andric 
visitCatchPadInst(CatchPadInst & CPI)45130b57cec5SDimitry Andric void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
45140b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
45150b57cec5SDimitry Andric 
45160b57cec5SDimitry Andric   Function *F = BB->getParent();
451781ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
45180b57cec5SDimitry Andric         "CatchPadInst needs to be in a function with a personality.", &CPI);
45190b57cec5SDimitry Andric 
452081ad6265SDimitry Andric   Check(isa<CatchSwitchInst>(CPI.getParentPad()),
45210b57cec5SDimitry Andric         "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
45220b57cec5SDimitry Andric         CPI.getParentPad());
45230b57cec5SDimitry Andric 
45240b57cec5SDimitry Andric   // The catchpad instruction must be the first non-PHI instruction in the
45250b57cec5SDimitry Andric   // block.
452681ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
45270b57cec5SDimitry Andric         "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
45280b57cec5SDimitry Andric 
45290b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
45300b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
45310b57cec5SDimitry Andric }
45320b57cec5SDimitry Andric 
visitCatchReturnInst(CatchReturnInst & CatchReturn)45330b57cec5SDimitry Andric void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
453481ad6265SDimitry Andric   Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
45350b57cec5SDimitry Andric         "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
45360b57cec5SDimitry Andric         CatchReturn.getOperand(0));
45370b57cec5SDimitry Andric 
45380b57cec5SDimitry Andric   visitTerminator(CatchReturn);
45390b57cec5SDimitry Andric }
45400b57cec5SDimitry Andric 
visitCleanupPadInst(CleanupPadInst & CPI)45410b57cec5SDimitry Andric void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
45420b57cec5SDimitry Andric   BasicBlock *BB = CPI.getParent();
45430b57cec5SDimitry Andric 
45440b57cec5SDimitry Andric   Function *F = BB->getParent();
454581ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
45460b57cec5SDimitry Andric         "CleanupPadInst needs to be in a function with a personality.", &CPI);
45470b57cec5SDimitry Andric 
45480b57cec5SDimitry Andric   // The cleanuppad instruction must be the first non-PHI instruction in the
45490b57cec5SDimitry Andric   // block.
455081ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CPI,
455181ad6265SDimitry Andric         "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
45520b57cec5SDimitry Andric 
45530b57cec5SDimitry Andric   auto *ParentPad = CPI.getParentPad();
455481ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
45550b57cec5SDimitry Andric         "CleanupPadInst has an invalid parent.", &CPI);
45560b57cec5SDimitry Andric 
45570b57cec5SDimitry Andric   visitEHPadPredecessors(CPI);
45580b57cec5SDimitry Andric   visitFuncletPadInst(CPI);
45590b57cec5SDimitry Andric }
45600b57cec5SDimitry Andric 
visitFuncletPadInst(FuncletPadInst & FPI)45610b57cec5SDimitry Andric void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
45620b57cec5SDimitry Andric   User *FirstUser = nullptr;
45630b57cec5SDimitry Andric   Value *FirstUnwindPad = nullptr;
45640b57cec5SDimitry Andric   SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
45650b57cec5SDimitry Andric   SmallSet<FuncletPadInst *, 8> Seen;
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric   while (!Worklist.empty()) {
45680b57cec5SDimitry Andric     FuncletPadInst *CurrentPad = Worklist.pop_back_val();
456981ad6265SDimitry Andric     Check(Seen.insert(CurrentPad).second,
45700b57cec5SDimitry Andric           "FuncletPadInst must not be nested within itself", CurrentPad);
45710b57cec5SDimitry Andric     Value *UnresolvedAncestorPad = nullptr;
45720b57cec5SDimitry Andric     for (User *U : CurrentPad->users()) {
45730b57cec5SDimitry Andric       BasicBlock *UnwindDest;
45740b57cec5SDimitry Andric       if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
45750b57cec5SDimitry Andric         UnwindDest = CRI->getUnwindDest();
45760b57cec5SDimitry Andric       } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
45770b57cec5SDimitry Andric         // We allow catchswitch unwind to caller to nest
45780b57cec5SDimitry Andric         // within an outer pad that unwinds somewhere else,
45790b57cec5SDimitry Andric         // because catchswitch doesn't have a nounwind variant.
45800b57cec5SDimitry Andric         // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
45810b57cec5SDimitry Andric         if (CSI->unwindsToCaller())
45820b57cec5SDimitry Andric           continue;
45830b57cec5SDimitry Andric         UnwindDest = CSI->getUnwindDest();
45840b57cec5SDimitry Andric       } else if (auto *II = dyn_cast<InvokeInst>(U)) {
45850b57cec5SDimitry Andric         UnwindDest = II->getUnwindDest();
45860b57cec5SDimitry Andric       } else if (isa<CallInst>(U)) {
45870b57cec5SDimitry Andric         // Calls which don't unwind may be found inside funclet
45880b57cec5SDimitry Andric         // pads that unwind somewhere else.  We don't *require*
45890b57cec5SDimitry Andric         // such calls to be annotated nounwind.
45900b57cec5SDimitry Andric         continue;
45910b57cec5SDimitry Andric       } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
45920b57cec5SDimitry Andric         // The unwind dest for a cleanup can only be found by
45930b57cec5SDimitry Andric         // recursive search.  Add it to the worklist, and we'll
45940b57cec5SDimitry Andric         // search for its first use that determines where it unwinds.
45950b57cec5SDimitry Andric         Worklist.push_back(CPI);
45960b57cec5SDimitry Andric         continue;
45970b57cec5SDimitry Andric       } else {
459881ad6265SDimitry Andric         Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
45990b57cec5SDimitry Andric         continue;
46000b57cec5SDimitry Andric       }
46010b57cec5SDimitry Andric 
46020b57cec5SDimitry Andric       Value *UnwindPad;
46030b57cec5SDimitry Andric       bool ExitsFPI;
46040b57cec5SDimitry Andric       if (UnwindDest) {
46050b57cec5SDimitry Andric         UnwindPad = UnwindDest->getFirstNonPHI();
46060b57cec5SDimitry Andric         if (!cast<Instruction>(UnwindPad)->isEHPad())
46070b57cec5SDimitry Andric           continue;
46080b57cec5SDimitry Andric         Value *UnwindParent = getParentPad(UnwindPad);
46090b57cec5SDimitry Andric         // Ignore unwind edges that don't exit CurrentPad.
46100b57cec5SDimitry Andric         if (UnwindParent == CurrentPad)
46110b57cec5SDimitry Andric           continue;
46120b57cec5SDimitry Andric         // Determine whether the original funclet pad is exited,
46130b57cec5SDimitry Andric         // and if we are scanning nested pads determine how many
46140b57cec5SDimitry Andric         // of them are exited so we can stop searching their
46150b57cec5SDimitry Andric         // children.
46160b57cec5SDimitry Andric         Value *ExitedPad = CurrentPad;
46170b57cec5SDimitry Andric         ExitsFPI = false;
46180b57cec5SDimitry Andric         do {
46190b57cec5SDimitry Andric           if (ExitedPad == &FPI) {
46200b57cec5SDimitry Andric             ExitsFPI = true;
46210b57cec5SDimitry Andric             // Now we can resolve any ancestors of CurrentPad up to
46220b57cec5SDimitry Andric             // FPI, but not including FPI since we need to make sure
46230b57cec5SDimitry Andric             // to check all direct users of FPI for consistency.
46240b57cec5SDimitry Andric             UnresolvedAncestorPad = &FPI;
46250b57cec5SDimitry Andric             break;
46260b57cec5SDimitry Andric           }
46270b57cec5SDimitry Andric           Value *ExitedParent = getParentPad(ExitedPad);
46280b57cec5SDimitry Andric           if (ExitedParent == UnwindParent) {
46290b57cec5SDimitry Andric             // ExitedPad is the ancestor-most pad which this unwind
46300b57cec5SDimitry Andric             // edge exits, so we can resolve up to it, meaning that
46310b57cec5SDimitry Andric             // ExitedParent is the first ancestor still unresolved.
46320b57cec5SDimitry Andric             UnresolvedAncestorPad = ExitedParent;
46330b57cec5SDimitry Andric             break;
46340b57cec5SDimitry Andric           }
46350b57cec5SDimitry Andric           ExitedPad = ExitedParent;
46360b57cec5SDimitry Andric         } while (!isa<ConstantTokenNone>(ExitedPad));
46370b57cec5SDimitry Andric       } else {
46380b57cec5SDimitry Andric         // Unwinding to caller exits all pads.
46390b57cec5SDimitry Andric         UnwindPad = ConstantTokenNone::get(FPI.getContext());
46400b57cec5SDimitry Andric         ExitsFPI = true;
46410b57cec5SDimitry Andric         UnresolvedAncestorPad = &FPI;
46420b57cec5SDimitry Andric       }
46430b57cec5SDimitry Andric 
46440b57cec5SDimitry Andric       if (ExitsFPI) {
46450b57cec5SDimitry Andric         // This unwind edge exits FPI.  Make sure it agrees with other
46460b57cec5SDimitry Andric         // such edges.
46470b57cec5SDimitry Andric         if (FirstUser) {
464881ad6265SDimitry Andric           Check(UnwindPad == FirstUnwindPad,
464981ad6265SDimitry Andric                 "Unwind edges out of a funclet "
46500b57cec5SDimitry Andric                 "pad must have the same unwind "
46510b57cec5SDimitry Andric                 "dest",
46520b57cec5SDimitry Andric                 &FPI, U, FirstUser);
46530b57cec5SDimitry Andric         } else {
46540b57cec5SDimitry Andric           FirstUser = U;
46550b57cec5SDimitry Andric           FirstUnwindPad = UnwindPad;
46560b57cec5SDimitry Andric           // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
46570b57cec5SDimitry Andric           if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
46580b57cec5SDimitry Andric               getParentPad(UnwindPad) == getParentPad(&FPI))
46590b57cec5SDimitry Andric             SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
46600b57cec5SDimitry Andric         }
46610b57cec5SDimitry Andric       }
46620b57cec5SDimitry Andric       // Make sure we visit all uses of FPI, but for nested pads stop as
46630b57cec5SDimitry Andric       // soon as we know where they unwind to.
46640b57cec5SDimitry Andric       if (CurrentPad != &FPI)
46650b57cec5SDimitry Andric         break;
46660b57cec5SDimitry Andric     }
46670b57cec5SDimitry Andric     if (UnresolvedAncestorPad) {
46680b57cec5SDimitry Andric       if (CurrentPad == UnresolvedAncestorPad) {
46690b57cec5SDimitry Andric         // When CurrentPad is FPI itself, we don't mark it as resolved even if
46700b57cec5SDimitry Andric         // we've found an unwind edge that exits it, because we need to verify
46710b57cec5SDimitry Andric         // all direct uses of FPI.
46720b57cec5SDimitry Andric         assert(CurrentPad == &FPI);
46730b57cec5SDimitry Andric         continue;
46740b57cec5SDimitry Andric       }
46750b57cec5SDimitry Andric       // Pop off the worklist any nested pads that we've found an unwind
46760b57cec5SDimitry Andric       // destination for.  The pads on the worklist are the uncles,
46770b57cec5SDimitry Andric       // great-uncles, etc. of CurrentPad.  We've found an unwind destination
46780b57cec5SDimitry Andric       // for all ancestors of CurrentPad up to but not including
46790b57cec5SDimitry Andric       // UnresolvedAncestorPad.
46800b57cec5SDimitry Andric       Value *ResolvedPad = CurrentPad;
46810b57cec5SDimitry Andric       while (!Worklist.empty()) {
46820b57cec5SDimitry Andric         Value *UnclePad = Worklist.back();
46830b57cec5SDimitry Andric         Value *AncestorPad = getParentPad(UnclePad);
46840b57cec5SDimitry Andric         // Walk ResolvedPad up the ancestor list until we either find the
46850b57cec5SDimitry Andric         // uncle's parent or the last resolved ancestor.
46860b57cec5SDimitry Andric         while (ResolvedPad != AncestorPad) {
46870b57cec5SDimitry Andric           Value *ResolvedParent = getParentPad(ResolvedPad);
46880b57cec5SDimitry Andric           if (ResolvedParent == UnresolvedAncestorPad) {
46890b57cec5SDimitry Andric             break;
46900b57cec5SDimitry Andric           }
46910b57cec5SDimitry Andric           ResolvedPad = ResolvedParent;
46920b57cec5SDimitry Andric         }
46930b57cec5SDimitry Andric         // If the resolved ancestor search didn't find the uncle's parent,
46940b57cec5SDimitry Andric         // then the uncle is not yet resolved.
46950b57cec5SDimitry Andric         if (ResolvedPad != AncestorPad)
46960b57cec5SDimitry Andric           break;
46970b57cec5SDimitry Andric         // This uncle is resolved, so pop it from the worklist.
46980b57cec5SDimitry Andric         Worklist.pop_back();
46990b57cec5SDimitry Andric       }
47000b57cec5SDimitry Andric     }
47010b57cec5SDimitry Andric   }
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   if (FirstUnwindPad) {
47040b57cec5SDimitry Andric     if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
47050b57cec5SDimitry Andric       BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
47060b57cec5SDimitry Andric       Value *SwitchUnwindPad;
47070b57cec5SDimitry Andric       if (SwitchUnwindDest)
47080b57cec5SDimitry Andric         SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
47090b57cec5SDimitry Andric       else
47100b57cec5SDimitry Andric         SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
471181ad6265SDimitry Andric       Check(SwitchUnwindPad == FirstUnwindPad,
47120b57cec5SDimitry Andric             "Unwind edges out of a catch must have the same unwind dest as "
47130b57cec5SDimitry Andric             "the parent catchswitch",
47140b57cec5SDimitry Andric             &FPI, FirstUser, CatchSwitch);
47150b57cec5SDimitry Andric     }
47160b57cec5SDimitry Andric   }
47170b57cec5SDimitry Andric 
47180b57cec5SDimitry Andric   visitInstruction(FPI);
47190b57cec5SDimitry Andric }
47200b57cec5SDimitry Andric 
visitCatchSwitchInst(CatchSwitchInst & CatchSwitch)47210b57cec5SDimitry Andric void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
47220b57cec5SDimitry Andric   BasicBlock *BB = CatchSwitch.getParent();
47230b57cec5SDimitry Andric 
47240b57cec5SDimitry Andric   Function *F = BB->getParent();
472581ad6265SDimitry Andric   Check(F->hasPersonalityFn(),
47260b57cec5SDimitry Andric         "CatchSwitchInst needs to be in a function with a personality.",
47270b57cec5SDimitry Andric         &CatchSwitch);
47280b57cec5SDimitry Andric 
47290b57cec5SDimitry Andric   // The catchswitch instruction must be the first non-PHI instruction in the
47300b57cec5SDimitry Andric   // block.
473181ad6265SDimitry Andric   Check(BB->getFirstNonPHI() == &CatchSwitch,
47320b57cec5SDimitry Andric         "CatchSwitchInst not the first non-PHI instruction in the block.",
47330b57cec5SDimitry Andric         &CatchSwitch);
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric   auto *ParentPad = CatchSwitch.getParentPad();
473681ad6265SDimitry Andric   Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
47370b57cec5SDimitry Andric         "CatchSwitchInst has an invalid parent.", ParentPad);
47380b57cec5SDimitry Andric 
47390b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
47400b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
474181ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
47420b57cec5SDimitry Andric           "CatchSwitchInst must unwind to an EH block which is not a "
47430b57cec5SDimitry Andric           "landingpad.",
47440b57cec5SDimitry Andric           &CatchSwitch);
47450b57cec5SDimitry Andric 
47460b57cec5SDimitry Andric     // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
47470b57cec5SDimitry Andric     if (getParentPad(I) == ParentPad)
47480b57cec5SDimitry Andric       SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
47490b57cec5SDimitry Andric   }
47500b57cec5SDimitry Andric 
475181ad6265SDimitry Andric   Check(CatchSwitch.getNumHandlers() != 0,
47520b57cec5SDimitry Andric         "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
47530b57cec5SDimitry Andric 
47540b57cec5SDimitry Andric   for (BasicBlock *Handler : CatchSwitch.handlers()) {
475581ad6265SDimitry Andric     Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
47560b57cec5SDimitry Andric           "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
47570b57cec5SDimitry Andric   }
47580b57cec5SDimitry Andric 
47590b57cec5SDimitry Andric   visitEHPadPredecessors(CatchSwitch);
47600b57cec5SDimitry Andric   visitTerminator(CatchSwitch);
47610b57cec5SDimitry Andric }
47620b57cec5SDimitry Andric 
visitCleanupReturnInst(CleanupReturnInst & CRI)47630b57cec5SDimitry Andric void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
476481ad6265SDimitry Andric   Check(isa<CleanupPadInst>(CRI.getOperand(0)),
47650b57cec5SDimitry Andric         "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
47660b57cec5SDimitry Andric         CRI.getOperand(0));
47670b57cec5SDimitry Andric 
47680b57cec5SDimitry Andric   if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
47690b57cec5SDimitry Andric     Instruction *I = UnwindDest->getFirstNonPHI();
477081ad6265SDimitry Andric     Check(I->isEHPad() && !isa<LandingPadInst>(I),
47710b57cec5SDimitry Andric           "CleanupReturnInst must unwind to an EH block which is not a "
47720b57cec5SDimitry Andric           "landingpad.",
47730b57cec5SDimitry Andric           &CRI);
47740b57cec5SDimitry Andric   }
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric   visitTerminator(CRI);
47770b57cec5SDimitry Andric }
47780b57cec5SDimitry Andric 
verifyDominatesUse(Instruction & I,unsigned i)47790b57cec5SDimitry Andric void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
47800b57cec5SDimitry Andric   Instruction *Op = cast<Instruction>(I.getOperand(i));
47810b57cec5SDimitry Andric   // If the we have an invalid invoke, don't try to compute the dominance.
47820b57cec5SDimitry Andric   // We already reject it in the invoke specific checks and the dominance
47830b57cec5SDimitry Andric   // computation doesn't handle multiple edges.
47840b57cec5SDimitry Andric   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
47850b57cec5SDimitry Andric     if (II->getNormalDest() == II->getUnwindDest())
47860b57cec5SDimitry Andric       return;
47870b57cec5SDimitry Andric   }
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric   // Quick check whether the def has already been encountered in the same block.
47900b57cec5SDimitry Andric   // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
47910b57cec5SDimitry Andric   // uses are defined to happen on the incoming edge, not at the instruction.
47920b57cec5SDimitry Andric   //
47930b57cec5SDimitry Andric   // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
47940b57cec5SDimitry Andric   // wrapping an SSA value, assert that we've already encountered it.  See
47950b57cec5SDimitry Andric   // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
47960b57cec5SDimitry Andric   if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
47970b57cec5SDimitry Andric     return;
47980b57cec5SDimitry Andric 
47990b57cec5SDimitry Andric   const Use &U = I.getOperandUse(i);
480081ad6265SDimitry Andric   Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
48010b57cec5SDimitry Andric }
48020b57cec5SDimitry Andric 
visitDereferenceableMetadata(Instruction & I,MDNode * MD)48030b57cec5SDimitry Andric void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
480481ad6265SDimitry Andric   Check(I.getType()->isPointerTy(),
480581ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
480681ad6265SDimitry Andric         "apply only to pointer types",
480781ad6265SDimitry Andric         &I);
480881ad6265SDimitry Andric   Check((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
48090b57cec5SDimitry Andric         "dereferenceable, dereferenceable_or_null apply only to load"
481081ad6265SDimitry Andric         " and inttoptr instructions, use attributes for calls or invokes",
481181ad6265SDimitry Andric         &I);
481281ad6265SDimitry Andric   Check(MD->getNumOperands() == 1,
481381ad6265SDimitry Andric         "dereferenceable, dereferenceable_or_null "
481481ad6265SDimitry Andric         "take one operand!",
481581ad6265SDimitry Andric         &I);
48160b57cec5SDimitry Andric   ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
481781ad6265SDimitry Andric   Check(CI && CI->getType()->isIntegerTy(64),
481881ad6265SDimitry Andric         "dereferenceable, "
481981ad6265SDimitry Andric         "dereferenceable_or_null metadata value must be an i64!",
482081ad6265SDimitry Andric         &I);
48210b57cec5SDimitry Andric }
48220b57cec5SDimitry Andric 
visitProfMetadata(Instruction & I,MDNode * MD)48238bcb0991SDimitry Andric void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
482481ad6265SDimitry Andric   Check(MD->getNumOperands() >= 2,
48258bcb0991SDimitry Andric         "!prof annotations should have no less than 2 operands", MD);
48268bcb0991SDimitry Andric 
48278bcb0991SDimitry Andric   // Check first operand.
482881ad6265SDimitry Andric   Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
482981ad6265SDimitry Andric   Check(isa<MDString>(MD->getOperand(0)),
48308bcb0991SDimitry Andric         "expected string with name of the !prof annotation", MD);
48318bcb0991SDimitry Andric   MDString *MDS = cast<MDString>(MD->getOperand(0));
48328bcb0991SDimitry Andric   StringRef ProfName = MDS->getString();
48338bcb0991SDimitry Andric 
48348bcb0991SDimitry Andric   // Check consistency of !prof branch_weights metadata.
4835*0fca6ea1SDimitry Andric   if (ProfName == "branch_weights") {
4836*0fca6ea1SDimitry Andric     unsigned NumBranchWeights = getNumBranchWeights(*MD);
48375ffd83dbSDimitry Andric     if (isa<InvokeInst>(&I)) {
4838*0fca6ea1SDimitry Andric       Check(NumBranchWeights == 1 || NumBranchWeights == 2,
48395ffd83dbSDimitry Andric             "Wrong number of InvokeInst branch_weights operands", MD);
48405ffd83dbSDimitry Andric     } else {
48418bcb0991SDimitry Andric       unsigned ExpectedNumOperands = 0;
48428bcb0991SDimitry Andric       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
48438bcb0991SDimitry Andric         ExpectedNumOperands = BI->getNumSuccessors();
48448bcb0991SDimitry Andric       else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
48458bcb0991SDimitry Andric         ExpectedNumOperands = SI->getNumSuccessors();
48465ffd83dbSDimitry Andric       else if (isa<CallInst>(&I))
48478bcb0991SDimitry Andric         ExpectedNumOperands = 1;
48488bcb0991SDimitry Andric       else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
48498bcb0991SDimitry Andric         ExpectedNumOperands = IBI->getNumDestinations();
48508bcb0991SDimitry Andric       else if (isa<SelectInst>(&I))
48518bcb0991SDimitry Andric         ExpectedNumOperands = 2;
4852bdd1243dSDimitry Andric       else if (CallBrInst *CI = dyn_cast<CallBrInst>(&I))
4853bdd1243dSDimitry Andric         ExpectedNumOperands = CI->getNumSuccessors();
48548bcb0991SDimitry Andric       else
48558bcb0991SDimitry Andric         CheckFailed("!prof branch_weights are not allowed for this instruction",
48568bcb0991SDimitry Andric                     MD);
48578bcb0991SDimitry Andric 
4858*0fca6ea1SDimitry Andric       Check(NumBranchWeights == ExpectedNumOperands, "Wrong number of operands",
4859*0fca6ea1SDimitry Andric             MD);
48605ffd83dbSDimitry Andric     }
4861*0fca6ea1SDimitry Andric     for (unsigned i = getBranchWeightOffset(MD); i < MD->getNumOperands();
4862*0fca6ea1SDimitry Andric          ++i) {
48638bcb0991SDimitry Andric       auto &MDO = MD->getOperand(i);
486481ad6265SDimitry Andric       Check(MDO, "second operand should not be null", MD);
486581ad6265SDimitry Andric       Check(mdconst::dyn_extract<ConstantInt>(MDO),
48668bcb0991SDimitry Andric             "!prof brunch_weights operand is not a const int");
48678bcb0991SDimitry Andric     }
48688bcb0991SDimitry Andric   }
48698bcb0991SDimitry Andric }
48708bcb0991SDimitry Andric 
visitDIAssignIDMetadata(Instruction & I,MDNode * MD)4871bdd1243dSDimitry Andric void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
4872bdd1243dSDimitry Andric   assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
4873bdd1243dSDimitry Andric   bool ExpectedInstTy =
4874bdd1243dSDimitry Andric       isa<AllocaInst>(I) || isa<StoreInst>(I) || isa<MemIntrinsic>(I);
4875bdd1243dSDimitry Andric   CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
4876bdd1243dSDimitry Andric           I, MD);
4877bdd1243dSDimitry Andric   // Iterate over the MetadataAsValue uses of the DIAssignID - these should
4878bdd1243dSDimitry Andric   // only be found as DbgAssignIntrinsic operands.
4879bdd1243dSDimitry Andric   if (auto *AsValue = MetadataAsValue::getIfExists(Context, MD)) {
4880bdd1243dSDimitry Andric     for (auto *User : AsValue->users()) {
4881bdd1243dSDimitry Andric       CheckDI(isa<DbgAssignIntrinsic>(User),
4882bdd1243dSDimitry Andric               "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4883bdd1243dSDimitry Andric               MD, User);
4884bdd1243dSDimitry Andric       // All of the dbg.assign intrinsics should be in the same function as I.
4885bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(User))
4886bdd1243dSDimitry Andric         CheckDI(DAI->getFunction() == I.getFunction(),
4887bdd1243dSDimitry Andric                 "dbg.assign not in same function as inst", DAI, &I);
4888bdd1243dSDimitry Andric     }
4889bdd1243dSDimitry Andric   }
4890*0fca6ea1SDimitry Andric   for (DbgVariableRecord *DVR :
4891*0fca6ea1SDimitry Andric        cast<DIAssignID>(MD)->getAllDbgVariableRecordUsers()) {
4892*0fca6ea1SDimitry Andric     CheckDI(DVR->isDbgAssign(),
4893*0fca6ea1SDimitry Andric             "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
4894*0fca6ea1SDimitry Andric     CheckDI(DVR->getFunction() == I.getFunction(),
4895*0fca6ea1SDimitry Andric             "DVRAssign not in same function as inst", DVR, &I);
48967a6dacacSDimitry Andric   }
4897bdd1243dSDimitry Andric }
4898bdd1243dSDimitry Andric 
visitMMRAMetadata(Instruction & I,MDNode * MD)4899*0fca6ea1SDimitry Andric void Verifier::visitMMRAMetadata(Instruction &I, MDNode *MD) {
4900*0fca6ea1SDimitry Andric   Check(canInstructionHaveMMRAs(I),
4901*0fca6ea1SDimitry Andric         "!mmra metadata attached to unexpected instruction kind", I, MD);
4902*0fca6ea1SDimitry Andric 
4903*0fca6ea1SDimitry Andric   // MMRA Metadata should either be a tag, e.g. !{!"foo", !"bar"}, or a
4904*0fca6ea1SDimitry Andric   // list of tags such as !2 in the following example:
4905*0fca6ea1SDimitry Andric   //    !0 = !{!"a", !"b"}
4906*0fca6ea1SDimitry Andric   //    !1 = !{!"c", !"d"}
4907*0fca6ea1SDimitry Andric   //    !2 = !{!0, !1}
4908*0fca6ea1SDimitry Andric   if (MMRAMetadata::isTagMD(MD))
4909*0fca6ea1SDimitry Andric     return;
4910*0fca6ea1SDimitry Andric 
4911*0fca6ea1SDimitry Andric   Check(isa<MDTuple>(MD), "!mmra expected to be a metadata tuple", I, MD);
4912*0fca6ea1SDimitry Andric   for (const MDOperand &MDOp : MD->operands())
4913*0fca6ea1SDimitry Andric     Check(MMRAMetadata::isTagMD(MDOp.get()),
4914*0fca6ea1SDimitry Andric           "!mmra metadata tuple operand is not an MMRA tag", I, MDOp.get());
4915*0fca6ea1SDimitry Andric }
4916*0fca6ea1SDimitry Andric 
visitCallStackMetadata(MDNode * MD)4917fcaf7f86SDimitry Andric void Verifier::visitCallStackMetadata(MDNode *MD) {
4918fcaf7f86SDimitry Andric   // Call stack metadata should consist of a list of at least 1 constant int
4919fcaf7f86SDimitry Andric   // (representing a hash of the location).
4920fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4921fcaf7f86SDimitry Andric         "call stack metadata should have at least 1 operand", MD);
4922fcaf7f86SDimitry Andric 
4923fcaf7f86SDimitry Andric   for (const auto &Op : MD->operands())
4924fcaf7f86SDimitry Andric     Check(mdconst::dyn_extract_or_null<ConstantInt>(Op),
4925fcaf7f86SDimitry Andric           "call stack metadata operand should be constant integer", Op);
4926fcaf7f86SDimitry Andric }
4927fcaf7f86SDimitry Andric 
visitMemProfMetadata(Instruction & I,MDNode * MD)4928fcaf7f86SDimitry Andric void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
4929fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
4930fcaf7f86SDimitry Andric   Check(MD->getNumOperands() >= 1,
4931fcaf7f86SDimitry Andric         "!memprof annotations should have at least 1 metadata operand "
4932fcaf7f86SDimitry Andric         "(MemInfoBlock)",
4933fcaf7f86SDimitry Andric         MD);
4934fcaf7f86SDimitry Andric 
4935fcaf7f86SDimitry Andric   // Check each MIB
4936fcaf7f86SDimitry Andric   for (auto &MIBOp : MD->operands()) {
4937fcaf7f86SDimitry Andric     MDNode *MIB = dyn_cast<MDNode>(MIBOp);
4938fcaf7f86SDimitry Andric     // The first operand of an MIB should be the call stack metadata.
4939fcaf7f86SDimitry Andric     // There rest of the operands should be MDString tags, and there should be
4940fcaf7f86SDimitry Andric     // at least one.
4941fcaf7f86SDimitry Andric     Check(MIB->getNumOperands() >= 2,
4942fcaf7f86SDimitry Andric           "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
4943fcaf7f86SDimitry Andric 
4944fcaf7f86SDimitry Andric     // Check call stack metadata (first operand).
4945fcaf7f86SDimitry Andric     Check(MIB->getOperand(0) != nullptr,
4946fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should not be null", MIB);
4947fcaf7f86SDimitry Andric     Check(isa<MDNode>(MIB->getOperand(0)),
4948fcaf7f86SDimitry Andric           "!memprof MemInfoBlock first operand should be an MDNode", MIB);
4949fcaf7f86SDimitry Andric     MDNode *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
4950fcaf7f86SDimitry Andric     visitCallStackMetadata(StackMD);
4951fcaf7f86SDimitry Andric 
4952*0fca6ea1SDimitry Andric     // Check that remaining operands, except possibly the last, are MDString.
4953*0fca6ea1SDimitry Andric     Check(llvm::all_of(MIB->operands().drop_front().drop_back(),
4954fcaf7f86SDimitry Andric                        [](const MDOperand &Op) { return isa<MDString>(Op); }),
4955*0fca6ea1SDimitry Andric           "Not all !memprof MemInfoBlock operands 1 to N-1 are MDString", MIB);
4956*0fca6ea1SDimitry Andric     // The last operand might be the total profiled size so can be an integer.
4957*0fca6ea1SDimitry Andric     auto &LastOperand = MIB->operands().back();
4958*0fca6ea1SDimitry Andric     Check(isa<MDString>(LastOperand) || mdconst::hasa<ConstantInt>(LastOperand),
4959*0fca6ea1SDimitry Andric           "Last !memprof MemInfoBlock operand not MDString or int", MIB);
4960fcaf7f86SDimitry Andric   }
4961fcaf7f86SDimitry Andric }
4962fcaf7f86SDimitry Andric 
visitCallsiteMetadata(Instruction & I,MDNode * MD)4963fcaf7f86SDimitry Andric void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
4964fcaf7f86SDimitry Andric   Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
4965fcaf7f86SDimitry Andric   // Verify the partial callstack annotated from memprof profiles. This callsite
4966fcaf7f86SDimitry Andric   // is a part of a profiled allocation callstack.
4967fcaf7f86SDimitry Andric   visitCallStackMetadata(MD);
4968fcaf7f86SDimitry Andric }
4969fcaf7f86SDimitry Andric 
visitAnnotationMetadata(MDNode * Annotation)4970e8d8bef9SDimitry Andric void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
497181ad6265SDimitry Andric   Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
497281ad6265SDimitry Andric   Check(Annotation->getNumOperands() >= 1,
4973e8d8bef9SDimitry Andric         "annotation must have at least one operand");
497406c3fb27SDimitry Andric   for (const MDOperand &Op : Annotation->operands()) {
497506c3fb27SDimitry Andric     bool TupleOfStrings =
497606c3fb27SDimitry Andric         isa<MDTuple>(Op.get()) &&
497706c3fb27SDimitry Andric         all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
497806c3fb27SDimitry Andric           return isa<MDString>(Annotation.get());
497906c3fb27SDimitry Andric         });
498006c3fb27SDimitry Andric     Check(isa<MDString>(Op.get()) || TupleOfStrings,
498106c3fb27SDimitry Andric           "operands must be a string or a tuple of strings");
498206c3fb27SDimitry Andric   }
4983e8d8bef9SDimitry Andric }
4984e8d8bef9SDimitry Andric 
visitAliasScopeMetadata(const MDNode * MD)4985349cc55cSDimitry Andric void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
4986349cc55cSDimitry Andric   unsigned NumOps = MD->getNumOperands();
498781ad6265SDimitry Andric   Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
4988349cc55cSDimitry Andric         MD);
498981ad6265SDimitry Andric   Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
4990349cc55cSDimitry Andric         "first scope operand must be self-referential or string", MD);
4991349cc55cSDimitry Andric   if (NumOps == 3)
499281ad6265SDimitry Andric     Check(isa<MDString>(MD->getOperand(2)),
4993349cc55cSDimitry Andric           "third scope operand must be string (if used)", MD);
4994349cc55cSDimitry Andric 
4995349cc55cSDimitry Andric   MDNode *Domain = dyn_cast<MDNode>(MD->getOperand(1));
499681ad6265SDimitry Andric   Check(Domain != nullptr, "second scope operand must be MDNode", MD);
4997349cc55cSDimitry Andric 
4998349cc55cSDimitry Andric   unsigned NumDomainOps = Domain->getNumOperands();
499981ad6265SDimitry Andric   Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5000349cc55cSDimitry Andric         "domain must have one or two operands", Domain);
500181ad6265SDimitry Andric   Check(Domain->getOperand(0).get() == Domain ||
5002349cc55cSDimitry Andric             isa<MDString>(Domain->getOperand(0)),
5003349cc55cSDimitry Andric         "first domain operand must be self-referential or string", Domain);
5004349cc55cSDimitry Andric   if (NumDomainOps == 2)
500581ad6265SDimitry Andric     Check(isa<MDString>(Domain->getOperand(1)),
5006349cc55cSDimitry Andric           "second domain operand must be string (if used)", Domain);
5007349cc55cSDimitry Andric }
5008349cc55cSDimitry Andric 
visitAliasScopeListMetadata(const MDNode * MD)5009349cc55cSDimitry Andric void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
5010349cc55cSDimitry Andric   for (const MDOperand &Op : MD->operands()) {
5011349cc55cSDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
501281ad6265SDimitry Andric     Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
5013349cc55cSDimitry Andric     visitAliasScopeMetadata(OpMD);
5014349cc55cSDimitry Andric   }
5015349cc55cSDimitry Andric }
5016349cc55cSDimitry Andric 
visitAccessGroupMetadata(const MDNode * MD)501781ad6265SDimitry Andric void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
501881ad6265SDimitry Andric   auto IsValidAccessScope = [](const MDNode *MD) {
501981ad6265SDimitry Andric     return MD->getNumOperands() == 0 && MD->isDistinct();
502081ad6265SDimitry Andric   };
502181ad6265SDimitry Andric 
502281ad6265SDimitry Andric   // It must be either an access scope itself...
502381ad6265SDimitry Andric   if (IsValidAccessScope(MD))
502481ad6265SDimitry Andric     return;
502581ad6265SDimitry Andric 
502681ad6265SDimitry Andric   // ...or a list of access scopes.
502781ad6265SDimitry Andric   for (const MDOperand &Op : MD->operands()) {
502881ad6265SDimitry Andric     const MDNode *OpMD = dyn_cast<MDNode>(Op);
502981ad6265SDimitry Andric     Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
503081ad6265SDimitry Andric     Check(IsValidAccessScope(OpMD),
503181ad6265SDimitry Andric           "Access scope list contains invalid access scope", MD);
503281ad6265SDimitry Andric   }
503381ad6265SDimitry Andric }
503481ad6265SDimitry Andric 
50350b57cec5SDimitry Andric /// verifyInstruction - Verify that an instruction is well formed.
50360b57cec5SDimitry Andric ///
visitInstruction(Instruction & I)50370b57cec5SDimitry Andric void Verifier::visitInstruction(Instruction &I) {
50380b57cec5SDimitry Andric   BasicBlock *BB = I.getParent();
503981ad6265SDimitry Andric   Check(BB, "Instruction not embedded in basic block!", &I);
50400b57cec5SDimitry Andric 
50410b57cec5SDimitry Andric   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
50420b57cec5SDimitry Andric     for (User *U : I.users()) {
504381ad6265SDimitry Andric       Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
50440b57cec5SDimitry Andric             "Only PHI nodes may reference their own value!", &I);
50450b57cec5SDimitry Andric     }
50460b57cec5SDimitry Andric   }
50470b57cec5SDimitry Andric 
50480b57cec5SDimitry Andric   // Check that void typed values don't have names
504981ad6265SDimitry Andric   Check(!I.getType()->isVoidTy() || !I.hasName(),
50500b57cec5SDimitry Andric         "Instruction has a name, but provides a void value!", &I);
50510b57cec5SDimitry Andric 
50520b57cec5SDimitry Andric   // Check that the return value of the instruction is either void or a legal
50530b57cec5SDimitry Andric   // value type.
505481ad6265SDimitry Andric   Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
50550b57cec5SDimitry Andric         "Instruction returns a non-scalar type!", &I);
50560b57cec5SDimitry Andric 
50570b57cec5SDimitry Andric   // Check that the instruction doesn't produce metadata. Calls are already
50580b57cec5SDimitry Andric   // checked against the callee type.
505981ad6265SDimitry Andric   Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
50600b57cec5SDimitry Andric         "Invalid use of metadata!", &I);
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric   // Check that all uses of the instruction, if they are instructions
50630b57cec5SDimitry Andric   // themselves, actually have parent basic blocks.  If the use is not an
50640b57cec5SDimitry Andric   // instruction, it is an error!
50650b57cec5SDimitry Andric   for (Use &U : I.uses()) {
50660b57cec5SDimitry Andric     if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
506781ad6265SDimitry Andric       Check(Used->getParent() != nullptr,
50680b57cec5SDimitry Andric             "Instruction referencing"
50690b57cec5SDimitry Andric             " instruction not embedded in a basic block!",
50700b57cec5SDimitry Andric             &I, Used);
50710b57cec5SDimitry Andric     else {
50720b57cec5SDimitry Andric       CheckFailed("Use of instruction is not an instruction!", U);
50730b57cec5SDimitry Andric       return;
50740b57cec5SDimitry Andric     }
50750b57cec5SDimitry Andric   }
50760b57cec5SDimitry Andric 
50770b57cec5SDimitry Andric   // Get a pointer to the call base of the instruction if it is some form of
50780b57cec5SDimitry Andric   // call.
50790b57cec5SDimitry Andric   const CallBase *CBI = dyn_cast<CallBase>(&I);
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
508281ad6265SDimitry Andric     Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
50830b57cec5SDimitry Andric 
50840b57cec5SDimitry Andric     // Check to make sure that only first-class-values are operands to
50850b57cec5SDimitry Andric     // instructions.
50860b57cec5SDimitry Andric     if (!I.getOperand(i)->getType()->isFirstClassType()) {
508781ad6265SDimitry Andric       Check(false, "Instruction operands must be first-class values!", &I);
50880b57cec5SDimitry Andric     }
50890b57cec5SDimitry Andric 
50900b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
5091349cc55cSDimitry Andric       // This code checks whether the function is used as the operand of a
5092349cc55cSDimitry Andric       // clang_arc_attachedcall operand bundle.
5093349cc55cSDimitry Andric       auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
5094349cc55cSDimitry Andric                                       int Idx) {
5095349cc55cSDimitry Andric         return CBI && CBI->isOperandBundleOfType(
5096349cc55cSDimitry Andric                           LLVMContext::OB_clang_arc_attachedcall, Idx);
5097349cc55cSDimitry Andric       };
5098349cc55cSDimitry Andric 
50990b57cec5SDimitry Andric       // Check to make sure that the "address of" an intrinsic function is never
5100349cc55cSDimitry Andric       // taken. Ignore cases where the address of the intrinsic function is used
5101349cc55cSDimitry Andric       // as the argument of operand bundle "clang.arc.attachedcall" as those
5102349cc55cSDimitry Andric       // cases are handled in verifyAttachedCallBundle.
510381ad6265SDimitry Andric       Check((!F->isIntrinsic() ||
5104349cc55cSDimitry Andric              (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
5105349cc55cSDimitry Andric              IsAttachedCallOperand(F, CBI, i)),
51060b57cec5SDimitry Andric             "Cannot take the address of an intrinsic!", &I);
510781ad6265SDimitry Andric       Check(!F->isIntrinsic() || isa<CallInst>(I) ||
51080b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::donothing ||
5109fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5110fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5111fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5112fe6060f1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
51130b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_resume ||
51140b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5115*0fca6ea1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5116*0fca6ea1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5117*0fca6ea1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
511881ad6265SDimitry Andric                 F->getIntrinsicID() ==
511981ad6265SDimitry Andric                     Intrinsic::experimental_patchpoint_void ||
5120*0fca6ea1SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
51210b57cec5SDimitry Andric                 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5122349cc55cSDimitry Andric                 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5123349cc55cSDimitry Andric                 IsAttachedCallOperand(F, CBI, i),
51240b57cec5SDimitry Andric             "Cannot invoke an intrinsic other than donothing, patchpoint, "
5125349cc55cSDimitry Andric             "statepoint, coro_resume, coro_destroy or clang.arc.attachedcall",
51260b57cec5SDimitry Andric             &I);
512781ad6265SDimitry Andric       Check(F->getParent() == &M, "Referencing function in another module!", &I,
512881ad6265SDimitry Andric             &M, F, F->getParent());
51290b57cec5SDimitry Andric     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
513081ad6265SDimitry Andric       Check(OpBB->getParent() == BB->getParent(),
51310b57cec5SDimitry Andric             "Referring to a basic block in another function!", &I);
51320b57cec5SDimitry Andric     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
513381ad6265SDimitry Andric       Check(OpArg->getParent() == BB->getParent(),
51340b57cec5SDimitry Andric             "Referring to an argument in another function!", &I);
51350b57cec5SDimitry Andric     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
513681ad6265SDimitry Andric       Check(GV->getParent() == &M, "Referencing global in another module!", &I,
51370b57cec5SDimitry Andric             &M, GV, GV->getParent());
5138*0fca6ea1SDimitry Andric     } else if (Instruction *OpInst = dyn_cast<Instruction>(I.getOperand(i))) {
5139*0fca6ea1SDimitry Andric       Check(OpInst->getFunction() == BB->getParent(),
5140*0fca6ea1SDimitry Andric             "Referring to an instruction in another function!", &I);
51410b57cec5SDimitry Andric       verifyDominatesUse(I, i);
51420b57cec5SDimitry Andric     } else if (isa<InlineAsm>(I.getOperand(i))) {
514381ad6265SDimitry Andric       Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
51440b57cec5SDimitry Andric             "Cannot take the address of an inline asm!", &I);
5145*0fca6ea1SDimitry Andric     } else if (auto *CPA = dyn_cast<ConstantPtrAuth>(I.getOperand(i))) {
5146*0fca6ea1SDimitry Andric       visitConstantExprsRecursively(CPA);
51470b57cec5SDimitry Andric     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
5148fe6060f1SDimitry Andric       if (CE->getType()->isPtrOrPtrVectorTy()) {
51490b57cec5SDimitry Andric         // If we have a ConstantExpr pointer, we need to see if it came from an
5150fe6060f1SDimitry Andric         // illegal bitcast.
51510b57cec5SDimitry Andric         visitConstantExprsRecursively(CE);
51520b57cec5SDimitry Andric       }
51530b57cec5SDimitry Andric     }
51540b57cec5SDimitry Andric   }
51550b57cec5SDimitry Andric 
51560b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
515781ad6265SDimitry Andric     Check(I.getType()->isFPOrFPVectorTy(),
51580b57cec5SDimitry Andric           "fpmath requires a floating point result!", &I);
515981ad6265SDimitry Andric     Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
51600b57cec5SDimitry Andric     if (ConstantFP *CFP0 =
51610b57cec5SDimitry Andric             mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
51620b57cec5SDimitry Andric       const APFloat &Accuracy = CFP0->getValueAPF();
516381ad6265SDimitry Andric       Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
51640b57cec5SDimitry Andric             "fpmath accuracy must have float type", &I);
516581ad6265SDimitry Andric       Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
51660b57cec5SDimitry Andric             "fpmath accuracy not a positive number!", &I);
51670b57cec5SDimitry Andric     } else {
516881ad6265SDimitry Andric       Check(false, "invalid fpmath accuracy!", &I);
51690b57cec5SDimitry Andric     }
51700b57cec5SDimitry Andric   }
51710b57cec5SDimitry Andric 
51720b57cec5SDimitry Andric   if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
517381ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
51740b57cec5SDimitry Andric           "Ranges are only for loads, calls and invokes!", &I);
51750b57cec5SDimitry Andric     visitRangeMetadata(I, Range, I.getType());
51760b57cec5SDimitry Andric   }
51770b57cec5SDimitry Andric 
5178349cc55cSDimitry Andric   if (I.hasMetadata(LLVMContext::MD_invariant_group)) {
517981ad6265SDimitry Andric     Check(isa<LoadInst>(I) || isa<StoreInst>(I),
5180349cc55cSDimitry Andric           "invariant.group metadata is only for loads and stores", &I);
5181349cc55cSDimitry Andric   }
5182349cc55cSDimitry Andric 
5183bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_nonnull)) {
518481ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
51850b57cec5SDimitry Andric           &I);
518681ad6265SDimitry Andric     Check(isa<LoadInst>(I),
51870b57cec5SDimitry Andric           "nonnull applies only to load instructions, use attributes"
51880b57cec5SDimitry Andric           " for calls or invokes",
51890b57cec5SDimitry Andric           &I);
5190bdd1243dSDimitry Andric     Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
51910b57cec5SDimitry Andric   }
51920b57cec5SDimitry Andric 
51930b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
51940b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
51950b57cec5SDimitry Andric 
51960b57cec5SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
51970b57cec5SDimitry Andric     visitDereferenceableMetadata(I, MD);
51980b57cec5SDimitry Andric 
51990b57cec5SDimitry Andric   if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
52000b57cec5SDimitry Andric     TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
52010b57cec5SDimitry Andric 
5202349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_noalias))
5203349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
5204349cc55cSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_alias_scope))
5205349cc55cSDimitry Andric     visitAliasScopeListMetadata(MD);
5206349cc55cSDimitry Andric 
520781ad6265SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_access_group))
520881ad6265SDimitry Andric     visitAccessGroupMetadata(MD);
520981ad6265SDimitry Andric 
52100b57cec5SDimitry Andric   if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
521181ad6265SDimitry Andric     Check(I.getType()->isPointerTy(), "align applies only to pointer types",
52120b57cec5SDimitry Andric           &I);
521381ad6265SDimitry Andric     Check(isa<LoadInst>(I),
521481ad6265SDimitry Andric           "align applies only to load instructions, "
521581ad6265SDimitry Andric           "use attributes for calls or invokes",
521681ad6265SDimitry Andric           &I);
521781ad6265SDimitry Andric     Check(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
52180b57cec5SDimitry Andric     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
521981ad6265SDimitry Andric     Check(CI && CI->getType()->isIntegerTy(64),
52200b57cec5SDimitry Andric           "align metadata value must be an i64!", &I);
52210b57cec5SDimitry Andric     uint64_t Align = CI->getZExtValue();
522281ad6265SDimitry Andric     Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
522381ad6265SDimitry Andric           &I);
522481ad6265SDimitry Andric     Check(Align <= Value::MaximumAlignment,
52250b57cec5SDimitry Andric           "alignment is larger that implementation defined limit", &I);
52260b57cec5SDimitry Andric   }
52270b57cec5SDimitry Andric 
52288bcb0991SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof))
52298bcb0991SDimitry Andric     visitProfMetadata(I, MD);
52308bcb0991SDimitry Andric 
5231fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_memprof))
5232fcaf7f86SDimitry Andric     visitMemProfMetadata(I, MD);
5233fcaf7f86SDimitry Andric 
5234fcaf7f86SDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_callsite))
5235fcaf7f86SDimitry Andric     visitCallsiteMetadata(I, MD);
5236fcaf7f86SDimitry Andric 
5237bdd1243dSDimitry Andric   if (MDNode *MD = I.getMetadata(LLVMContext::MD_DIAssignID))
5238bdd1243dSDimitry Andric     visitDIAssignIDMetadata(I, MD);
5239bdd1243dSDimitry Andric 
5240*0fca6ea1SDimitry Andric   if (MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra))
5241*0fca6ea1SDimitry Andric     visitMMRAMetadata(I, MMRA);
5242*0fca6ea1SDimitry Andric 
5243e8d8bef9SDimitry Andric   if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation))
5244e8d8bef9SDimitry Andric     visitAnnotationMetadata(Annotation);
5245e8d8bef9SDimitry Andric 
52460b57cec5SDimitry Andric   if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
524781ad6265SDimitry Andric     CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
52485ffd83dbSDimitry Andric     visitMDNode(*N, AreDebugLocsAllowed::Yes);
52490b57cec5SDimitry Andric   }
52500b57cec5SDimitry Andric 
52518bcb0991SDimitry Andric   if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
52520b57cec5SDimitry Andric     verifyFragmentExpression(*DII);
52538bcb0991SDimitry Andric     verifyNotEntryValue(*DII);
52548bcb0991SDimitry Andric   }
52550b57cec5SDimitry Andric 
52565ffd83dbSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
52575ffd83dbSDimitry Andric   I.getAllMetadata(MDs);
52585ffd83dbSDimitry Andric   for (auto Attachment : MDs) {
52595ffd83dbSDimitry Andric     unsigned Kind = Attachment.first;
52605ffd83dbSDimitry Andric     auto AllowLocs =
52615ffd83dbSDimitry Andric         (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop)
52625ffd83dbSDimitry Andric             ? AreDebugLocsAllowed::Yes
52635ffd83dbSDimitry Andric             : AreDebugLocsAllowed::No;
52645ffd83dbSDimitry Andric     visitMDNode(*Attachment.second, AllowLocs);
52655ffd83dbSDimitry Andric   }
52665ffd83dbSDimitry Andric 
52670b57cec5SDimitry Andric   InstsInThisBlock.insert(&I);
52680b57cec5SDimitry Andric }
52690b57cec5SDimitry Andric 
52700b57cec5SDimitry Andric /// Allow intrinsics to be verified in different ways.
visitIntrinsicCall(Intrinsic::ID ID,CallBase & Call)52710b57cec5SDimitry Andric void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
52720b57cec5SDimitry Andric   Function *IF = Call.getCalledFunction();
527381ad6265SDimitry Andric   Check(IF->isDeclaration(), "Intrinsic functions should never be defined!",
52740b57cec5SDimitry Andric         IF);
52750b57cec5SDimitry Andric 
52760b57cec5SDimitry Andric   // Verify that the intrinsic prototype lines up with what the .td files
52770b57cec5SDimitry Andric   // describe.
52780b57cec5SDimitry Andric   FunctionType *IFTy = IF->getFunctionType();
52790b57cec5SDimitry Andric   bool IsVarArg = IFTy->isVarArg();
52800b57cec5SDimitry Andric 
52810b57cec5SDimitry Andric   SmallVector<Intrinsic::IITDescriptor, 8> Table;
52820b57cec5SDimitry Andric   getIntrinsicInfoTableEntries(ID, Table);
52830b57cec5SDimitry Andric   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric   // Walk the descriptors to extract overloaded types.
52860b57cec5SDimitry Andric   SmallVector<Type *, 4> ArgTys;
52870b57cec5SDimitry Andric   Intrinsic::MatchIntrinsicTypesResult Res =
52880b57cec5SDimitry Andric       Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys);
528981ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet,
52900b57cec5SDimitry Andric         "Intrinsic has incorrect return type!", IF);
529181ad6265SDimitry Andric   Check(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg,
52920b57cec5SDimitry Andric         "Intrinsic has incorrect argument type!", IF);
52930b57cec5SDimitry Andric 
52940b57cec5SDimitry Andric   // Verify if the intrinsic call matches the vararg property.
52950b57cec5SDimitry Andric   if (IsVarArg)
529681ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
52970b57cec5SDimitry Andric           "Intrinsic was not defined with variable arguments!", IF);
52980b57cec5SDimitry Andric   else
529981ad6265SDimitry Andric     Check(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
53000b57cec5SDimitry Andric           "Callsite was not defined with variable arguments!", IF);
53010b57cec5SDimitry Andric 
53020b57cec5SDimitry Andric   // All descriptors should be absorbed by now.
530381ad6265SDimitry Andric   Check(TableRef.empty(), "Intrinsic has too few arguments!", IF);
53040b57cec5SDimitry Andric 
53050b57cec5SDimitry Andric   // Now that we have the intrinsic ID and the actual argument types (and we
53060b57cec5SDimitry Andric   // know they are legal for the intrinsic!) get the intrinsic name through the
53070b57cec5SDimitry Andric   // usual means.  This allows us to verify the mangling of argument types into
53080b57cec5SDimitry Andric   // the name.
5309fe6060f1SDimitry Andric   const std::string ExpectedName =
5310fe6060f1SDimitry Andric       Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy);
531181ad6265SDimitry Andric   Check(ExpectedName == IF->getName(),
53120b57cec5SDimitry Andric         "Intrinsic name not mangled correctly for type arguments! "
53130b57cec5SDimitry Andric         "Should be: " +
53140b57cec5SDimitry Andric             ExpectedName,
53150b57cec5SDimitry Andric         IF);
53160b57cec5SDimitry Andric 
53170b57cec5SDimitry Andric   // If the intrinsic takes MDNode arguments, verify that they are either global
53180b57cec5SDimitry Andric   // or are local to *this* function.
5319fe6060f1SDimitry Andric   for (Value *V : Call.args()) {
53200b57cec5SDimitry Andric     if (auto *MD = dyn_cast<MetadataAsValue>(V))
53210b57cec5SDimitry Andric       visitMetadataAsValue(*MD, Call.getCaller());
5322fe6060f1SDimitry Andric     if (auto *Const = dyn_cast<Constant>(V))
532381ad6265SDimitry Andric       Check(!Const->getType()->isX86_AMXTy(),
5324fe6060f1SDimitry Andric             "const x86_amx is not allowed in argument!");
5325fe6060f1SDimitry Andric   }
53260b57cec5SDimitry Andric 
53270b57cec5SDimitry Andric   switch (ID) {
53280b57cec5SDimitry Andric   default:
53290b57cec5SDimitry Andric     break;
53305ffd83dbSDimitry Andric   case Intrinsic::assume: {
53315ffd83dbSDimitry Andric     for (auto &Elem : Call.bundle_op_infos()) {
5332bdd1243dSDimitry Andric       unsigned ArgCount = Elem.End - Elem.Begin;
5333bdd1243dSDimitry Andric       // Separate storage assumptions are special insofar as they're the only
5334bdd1243dSDimitry Andric       // operand bundles allowed on assumes that aren't parameter attributes.
5335bdd1243dSDimitry Andric       if (Elem.Tag->getKey() == "separate_storage") {
5336bdd1243dSDimitry Andric         Check(ArgCount == 2,
5337bdd1243dSDimitry Andric               "separate_storage assumptions should have 2 arguments", Call);
5338bdd1243dSDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy() &&
5339bdd1243dSDimitry Andric                   Call.getOperand(Elem.Begin + 1)->getType()->isPointerTy(),
5340bdd1243dSDimitry Andric               "arguments to separate_storage assumptions should be pointers",
5341bdd1243dSDimitry Andric               Call);
5342bdd1243dSDimitry Andric         return;
5343bdd1243dSDimitry Andric       }
534481ad6265SDimitry Andric       Check(Elem.Tag->getKey() == "ignore" ||
53455ffd83dbSDimitry Andric                 Attribute::isExistingAttribute(Elem.Tag->getKey()),
5346349cc55cSDimitry Andric             "tags must be valid attribute names", Call);
53475ffd83dbSDimitry Andric       Attribute::AttrKind Kind =
53485ffd83dbSDimitry Andric           Attribute::getAttrKindFromName(Elem.Tag->getKey());
5349e8d8bef9SDimitry Andric       if (Kind == Attribute::Alignment) {
535081ad6265SDimitry Andric         Check(ArgCount <= 3 && ArgCount >= 2,
5351349cc55cSDimitry Andric               "alignment assumptions should have 2 or 3 arguments", Call);
535281ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin)->getType()->isPointerTy(),
5353349cc55cSDimitry Andric               "first argument should be a pointer", Call);
535481ad6265SDimitry Andric         Check(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(),
5355349cc55cSDimitry Andric               "second argument should be an integer", Call);
5356e8d8bef9SDimitry Andric         if (ArgCount == 3)
535781ad6265SDimitry Andric           Check(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(),
5358349cc55cSDimitry Andric                 "third argument should be an integer if present", Call);
5359e8d8bef9SDimitry Andric         return;
5360e8d8bef9SDimitry Andric       }
536181ad6265SDimitry Andric       Check(ArgCount <= 2, "too many arguments", Call);
53625ffd83dbSDimitry Andric       if (Kind == Attribute::None)
53635ffd83dbSDimitry Andric         break;
5364fe6060f1SDimitry Andric       if (Attribute::isIntAttrKind(Kind)) {
536581ad6265SDimitry Andric         Check(ArgCount == 2, "this attribute should have 2 arguments", Call);
536681ad6265SDimitry Andric         Check(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)),
5367349cc55cSDimitry Andric               "the second argument should be a constant integral value", Call);
5368fe6060f1SDimitry Andric       } else if (Attribute::canUseAsParamAttr(Kind)) {
536981ad6265SDimitry Andric         Check((ArgCount) == 1, "this attribute should have one argument", Call);
5370fe6060f1SDimitry Andric       } else if (Attribute::canUseAsFnAttr(Kind)) {
537181ad6265SDimitry Andric         Check((ArgCount) == 0, "this attribute has no argument", Call);
53725ffd83dbSDimitry Andric       }
53735ffd83dbSDimitry Andric     }
53745ffd83dbSDimitry Andric     break;
53755ffd83dbSDimitry Andric   }
5376*0fca6ea1SDimitry Andric   case Intrinsic::ucmp:
5377*0fca6ea1SDimitry Andric   case Intrinsic::scmp: {
5378*0fca6ea1SDimitry Andric     Type *SrcTy = Call.getOperand(0)->getType();
5379*0fca6ea1SDimitry Andric     Type *DestTy = Call.getType();
5380*0fca6ea1SDimitry Andric 
5381*0fca6ea1SDimitry Andric     Check(DestTy->getScalarSizeInBits() >= 2,
5382*0fca6ea1SDimitry Andric           "result type must be at least 2 bits wide", Call);
5383*0fca6ea1SDimitry Andric 
5384*0fca6ea1SDimitry Andric     bool IsDestTypeVector = DestTy->isVectorTy();
5385*0fca6ea1SDimitry Andric     Check(SrcTy->isVectorTy() == IsDestTypeVector,
5386*0fca6ea1SDimitry Andric           "ucmp/scmp argument and result types must both be either vector or "
5387*0fca6ea1SDimitry Andric           "scalar types",
5388*0fca6ea1SDimitry Andric           Call);
5389*0fca6ea1SDimitry Andric     if (IsDestTypeVector) {
5390*0fca6ea1SDimitry Andric       auto SrcVecLen = cast<VectorType>(SrcTy)->getElementCount();
5391*0fca6ea1SDimitry Andric       auto DestVecLen = cast<VectorType>(DestTy)->getElementCount();
5392*0fca6ea1SDimitry Andric       Check(SrcVecLen == DestVecLen,
5393*0fca6ea1SDimitry Andric             "return type and arguments must have the same number of "
5394*0fca6ea1SDimitry Andric             "elements",
5395*0fca6ea1SDimitry Andric             Call);
5396*0fca6ea1SDimitry Andric     }
5397*0fca6ea1SDimitry Andric     break;
5398*0fca6ea1SDimitry Andric   }
53990b57cec5SDimitry Andric   case Intrinsic::coro_id: {
54000b57cec5SDimitry Andric     auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts();
54010b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(InfoArg))
54020b57cec5SDimitry Andric       break;
54030b57cec5SDimitry Andric     auto *GV = dyn_cast<GlobalVariable>(InfoArg);
540481ad6265SDimitry Andric     Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
5405fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to an initialized "
54060b57cec5SDimitry Andric           "constant");
54070b57cec5SDimitry Andric     Constant *Init = GV->getInitializer();
540881ad6265SDimitry Andric     Check(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
5409fe6060f1SDimitry Andric           "info argument of llvm.coro.id must refer to either a struct or "
54100b57cec5SDimitry Andric           "an array");
54110b57cec5SDimitry Andric     break;
54120b57cec5SDimitry Andric   }
5413bdd1243dSDimitry Andric   case Intrinsic::is_fpclass: {
5414bdd1243dSDimitry Andric     const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
541506c3fb27SDimitry Andric     Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
5416bdd1243dSDimitry Andric           "unsupported bits for llvm.is.fpclass test mask");
5417bdd1243dSDimitry Andric     break;
5418bdd1243dSDimitry Andric   }
541981ad6265SDimitry Andric   case Intrinsic::fptrunc_round: {
542081ad6265SDimitry Andric     // Check the rounding mode
542181ad6265SDimitry Andric     Metadata *MD = nullptr;
542281ad6265SDimitry Andric     auto *MAV = dyn_cast<MetadataAsValue>(Call.getOperand(1));
542381ad6265SDimitry Andric     if (MAV)
542481ad6265SDimitry Andric       MD = MAV->getMetadata();
542581ad6265SDimitry Andric 
542681ad6265SDimitry Andric     Check(MD != nullptr, "missing rounding mode argument", Call);
542781ad6265SDimitry Andric 
542881ad6265SDimitry Andric     Check(isa<MDString>(MD),
542981ad6265SDimitry Andric           ("invalid value for llvm.fptrunc.round metadata operand"
543081ad6265SDimitry Andric            " (the operand should be a string)"),
543181ad6265SDimitry Andric           MD);
543281ad6265SDimitry Andric 
5433bdd1243dSDimitry Andric     std::optional<RoundingMode> RoundMode =
543481ad6265SDimitry Andric         convertStrToRoundingMode(cast<MDString>(MD)->getString());
543581ad6265SDimitry Andric     Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
543681ad6265SDimitry Andric           "unsupported rounding mode argument", Call);
543781ad6265SDimitry Andric     break;
543881ad6265SDimitry Andric   }
543981ad6265SDimitry Andric #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
544081ad6265SDimitry Andric #include "llvm/IR/VPIntrinsics.def"
5441*0fca6ea1SDimitry Andric #undef BEGIN_REGISTER_VP_INTRINSIC
544281ad6265SDimitry Andric     visitVPIntrinsic(cast<VPIntrinsic>(Call));
544381ad6265SDimitry Andric     break;
54445ffd83dbSDimitry Andric #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC)                        \
5445480093f4SDimitry Andric   case Intrinsic::INTRINSIC:
5446480093f4SDimitry Andric #include "llvm/IR/ConstrainedOps.def"
5447*0fca6ea1SDimitry Andric #undef INSTRUCTION
54480b57cec5SDimitry Andric     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
54490b57cec5SDimitry Andric     break;
54500b57cec5SDimitry Andric   case Intrinsic::dbg_declare: // llvm.dbg.declare
545181ad6265SDimitry Andric     Check(isa<MetadataAsValue>(Call.getArgOperand(0)),
54520b57cec5SDimitry Andric           "invalid llvm.dbg.declare intrinsic call 1", Call);
54530b57cec5SDimitry Andric     visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call));
54540b57cec5SDimitry Andric     break;
54550b57cec5SDimitry Andric   case Intrinsic::dbg_value: // llvm.dbg.value
54560b57cec5SDimitry Andric     visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call));
54570b57cec5SDimitry Andric     break;
5458bdd1243dSDimitry Andric   case Intrinsic::dbg_assign: // llvm.dbg.assign
5459bdd1243dSDimitry Andric     visitDbgIntrinsic("assign", cast<DbgVariableIntrinsic>(Call));
5460bdd1243dSDimitry Andric     break;
54610b57cec5SDimitry Andric   case Intrinsic::dbg_label: // llvm.dbg.label
54620b57cec5SDimitry Andric     visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call));
54630b57cec5SDimitry Andric     break;
54640b57cec5SDimitry Andric   case Intrinsic::memcpy:
54655ffd83dbSDimitry Andric   case Intrinsic::memcpy_inline:
54660b57cec5SDimitry Andric   case Intrinsic::memmove:
546781ad6265SDimitry Andric   case Intrinsic::memset:
546881ad6265SDimitry Andric   case Intrinsic::memset_inline: {
54690b57cec5SDimitry Andric     break;
54700b57cec5SDimitry Andric   }
54710b57cec5SDimitry Andric   case Intrinsic::memcpy_element_unordered_atomic:
54720b57cec5SDimitry Andric   case Intrinsic::memmove_element_unordered_atomic:
54730b57cec5SDimitry Andric   case Intrinsic::memset_element_unordered_atomic: {
54740b57cec5SDimitry Andric     const auto *AMI = cast<AtomicMemIntrinsic>(&Call);
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric     ConstantInt *ElementSizeCI =
54770b57cec5SDimitry Andric         cast<ConstantInt>(AMI->getRawElementSizeInBytes());
54780b57cec5SDimitry Andric     const APInt &ElementSizeVal = ElementSizeCI->getValue();
547981ad6265SDimitry Andric     Check(ElementSizeVal.isPowerOf2(),
54800b57cec5SDimitry Andric           "element size of the element-wise atomic memory intrinsic "
54810b57cec5SDimitry Andric           "must be a power of 2",
54820b57cec5SDimitry Andric           Call);
54830b57cec5SDimitry Andric 
5484bdd1243dSDimitry Andric     auto IsValidAlignment = [&](MaybeAlign Alignment) {
5485bdd1243dSDimitry Andric       return Alignment && ElementSizeVal.ule(Alignment->value());
54860b57cec5SDimitry Andric     };
5487bdd1243dSDimitry Andric     Check(IsValidAlignment(AMI->getDestAlign()),
54880b57cec5SDimitry Andric           "incorrect alignment of the destination argument", Call);
54890b57cec5SDimitry Andric     if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
5490bdd1243dSDimitry Andric       Check(IsValidAlignment(AMT->getSourceAlign()),
54910b57cec5SDimitry Andric             "incorrect alignment of the source argument", Call);
54920b57cec5SDimitry Andric     }
54930b57cec5SDimitry Andric     break;
54940b57cec5SDimitry Andric   }
54955ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_setup: {
54965ffd83dbSDimitry Andric     auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0));
549781ad6265SDimitry Andric     Check(NumArgs != nullptr,
54985ffd83dbSDimitry Andric           "llvm.call.preallocated.setup argument must be a constant");
54995ffd83dbSDimitry Andric     bool FoundCall = false;
55005ffd83dbSDimitry Andric     for (User *U : Call.users()) {
55015ffd83dbSDimitry Andric       auto *UseCall = dyn_cast<CallBase>(U);
550281ad6265SDimitry Andric       Check(UseCall != nullptr,
55035ffd83dbSDimitry Andric             "Uses of llvm.call.preallocated.setup must be calls");
55045ffd83dbSDimitry Andric       const Function *Fn = UseCall->getCalledFunction();
55055ffd83dbSDimitry Andric       if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) {
55065ffd83dbSDimitry Andric         auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
550781ad6265SDimitry Andric         Check(AllocArgIndex != nullptr,
55085ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be a constant");
55095ffd83dbSDimitry Andric         auto AllocArgIndexInt = AllocArgIndex->getValue();
551081ad6265SDimitry Andric         Check(AllocArgIndexInt.sge(0) &&
55115ffd83dbSDimitry Andric                   AllocArgIndexInt.slt(NumArgs->getValue()),
55125ffd83dbSDimitry Andric               "llvm.call.preallocated.alloc arg index must be between 0 and "
55135ffd83dbSDimitry Andric               "corresponding "
55145ffd83dbSDimitry Andric               "llvm.call.preallocated.setup's argument count");
55155ffd83dbSDimitry Andric       } else if (Fn && Fn->getIntrinsicID() ==
55165ffd83dbSDimitry Andric                            Intrinsic::call_preallocated_teardown) {
55175ffd83dbSDimitry Andric         // nothing to do
55185ffd83dbSDimitry Andric       } else {
551981ad6265SDimitry Andric         Check(!FoundCall, "Can have at most one call corresponding to a "
55205ffd83dbSDimitry Andric                           "llvm.call.preallocated.setup");
55215ffd83dbSDimitry Andric         FoundCall = true;
55225ffd83dbSDimitry Andric         size_t NumPreallocatedArgs = 0;
5523349cc55cSDimitry Andric         for (unsigned i = 0; i < UseCall->arg_size(); i++) {
55245ffd83dbSDimitry Andric           if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
55255ffd83dbSDimitry Andric             ++NumPreallocatedArgs;
55265ffd83dbSDimitry Andric           }
55275ffd83dbSDimitry Andric         }
552881ad6265SDimitry Andric         Check(NumPreallocatedArgs != 0,
55295ffd83dbSDimitry Andric               "cannot use preallocated intrinsics on a call without "
55305ffd83dbSDimitry Andric               "preallocated arguments");
553181ad6265SDimitry Andric         Check(NumArgs->equalsInt(NumPreallocatedArgs),
55325ffd83dbSDimitry Andric               "llvm.call.preallocated.setup arg size must be equal to number "
55335ffd83dbSDimitry Andric               "of preallocated arguments "
55345ffd83dbSDimitry Andric               "at call site",
55355ffd83dbSDimitry Andric               Call, *UseCall);
55365ffd83dbSDimitry Andric         // getOperandBundle() cannot be called if more than one of the operand
55375ffd83dbSDimitry Andric         // bundle exists. There is already a check elsewhere for this, so skip
55385ffd83dbSDimitry Andric         // here if we see more than one.
55395ffd83dbSDimitry Andric         if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
55405ffd83dbSDimitry Andric             1) {
55415ffd83dbSDimitry Andric           return;
55425ffd83dbSDimitry Andric         }
55435ffd83dbSDimitry Andric         auto PreallocatedBundle =
55445ffd83dbSDimitry Andric             UseCall->getOperandBundle(LLVMContext::OB_preallocated);
554581ad6265SDimitry Andric         Check(PreallocatedBundle,
55465ffd83dbSDimitry Andric               "Use of llvm.call.preallocated.setup outside intrinsics "
55475ffd83dbSDimitry Andric               "must be in \"preallocated\" operand bundle");
554881ad6265SDimitry Andric         Check(PreallocatedBundle->Inputs.front().get() == &Call,
55495ffd83dbSDimitry Andric               "preallocated bundle must have token from corresponding "
55505ffd83dbSDimitry Andric               "llvm.call.preallocated.setup");
55515ffd83dbSDimitry Andric       }
55525ffd83dbSDimitry Andric     }
55535ffd83dbSDimitry Andric     break;
55545ffd83dbSDimitry Andric   }
55555ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_arg: {
55565ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
555781ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
55585ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
55595ffd83dbSDimitry Andric           "llvm.call.preallocated.arg token argument must be a "
55605ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
556181ad6265SDimitry Andric     Check(Call.hasFnAttr(Attribute::Preallocated),
55625ffd83dbSDimitry Andric           "llvm.call.preallocated.arg must be called with a \"preallocated\" "
55635ffd83dbSDimitry Andric           "call site attribute");
55645ffd83dbSDimitry Andric     break;
55655ffd83dbSDimitry Andric   }
55665ffd83dbSDimitry Andric   case Intrinsic::call_preallocated_teardown: {
55675ffd83dbSDimitry Andric     auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
556881ad6265SDimitry Andric     Check(Token && Token->getCalledFunction()->getIntrinsicID() ==
55695ffd83dbSDimitry Andric                        Intrinsic::call_preallocated_setup,
55705ffd83dbSDimitry Andric           "llvm.call.preallocated.teardown token argument must be a "
55715ffd83dbSDimitry Andric           "llvm.call.preallocated.setup");
55725ffd83dbSDimitry Andric     break;
55735ffd83dbSDimitry Andric   }
55740b57cec5SDimitry Andric   case Intrinsic::gcroot:
55750b57cec5SDimitry Andric   case Intrinsic::gcwrite:
55760b57cec5SDimitry Andric   case Intrinsic::gcread:
55770b57cec5SDimitry Andric     if (ID == Intrinsic::gcroot) {
55780b57cec5SDimitry Andric       AllocaInst *AI =
55790b57cec5SDimitry Andric           dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts());
558081ad6265SDimitry Andric       Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
558181ad6265SDimitry Andric       Check(isa<Constant>(Call.getArgOperand(1)),
55820b57cec5SDimitry Andric             "llvm.gcroot parameter #2 must be a constant.", Call);
55830b57cec5SDimitry Andric       if (!AI->getAllocatedType()->isPointerTy()) {
558481ad6265SDimitry Andric         Check(!isa<ConstantPointerNull>(Call.getArgOperand(1)),
55850b57cec5SDimitry Andric               "llvm.gcroot parameter #1 must either be a pointer alloca, "
55860b57cec5SDimitry Andric               "or argument #2 must be a non-null constant.",
55870b57cec5SDimitry Andric               Call);
55880b57cec5SDimitry Andric       }
55890b57cec5SDimitry Andric     }
55900b57cec5SDimitry Andric 
559181ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
55920b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
55930b57cec5SDimitry Andric     break;
55940b57cec5SDimitry Andric   case Intrinsic::init_trampoline:
559581ad6265SDimitry Andric     Check(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()),
55960b57cec5SDimitry Andric           "llvm.init_trampoline parameter #2 must resolve to a function.",
55970b57cec5SDimitry Andric           Call);
55980b57cec5SDimitry Andric     break;
55990b57cec5SDimitry Andric   case Intrinsic::prefetch:
5600bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
5601bdd1243dSDimitry Andric           "rw argument to llvm.prefetch must be 0-1", Call);
5602bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
56035f757f3fSDimitry Andric           "locality argument to llvm.prefetch must be 0-3", Call);
5604bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
5605bdd1243dSDimitry Andric           "cache type argument to llvm.prefetch must be 0-1", Call);
56060b57cec5SDimitry Andric     break;
56070b57cec5SDimitry Andric   case Intrinsic::stackprotector:
560881ad6265SDimitry Andric     Check(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()),
56090b57cec5SDimitry Andric           "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
56100b57cec5SDimitry Andric     break;
56110b57cec5SDimitry Andric   case Intrinsic::localescape: {
56120b57cec5SDimitry Andric     BasicBlock *BB = Call.getParent();
5613bdd1243dSDimitry Andric     Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
5614bdd1243dSDimitry Andric           Call);
561581ad6265SDimitry Andric     Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
561681ad6265SDimitry Andric           Call);
56170b57cec5SDimitry Andric     for (Value *Arg : Call.args()) {
56180b57cec5SDimitry Andric       if (isa<ConstantPointerNull>(Arg))
56190b57cec5SDimitry Andric         continue; // Null values are allowed as placeholders.
56200b57cec5SDimitry Andric       auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
562181ad6265SDimitry Andric       Check(AI && AI->isStaticAlloca(),
56220b57cec5SDimitry Andric             "llvm.localescape only accepts static allocas", Call);
56230b57cec5SDimitry Andric     }
5624349cc55cSDimitry Andric     FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
56250b57cec5SDimitry Andric     SawFrameEscape = true;
56260b57cec5SDimitry Andric     break;
56270b57cec5SDimitry Andric   }
56280b57cec5SDimitry Andric   case Intrinsic::localrecover: {
56290b57cec5SDimitry Andric     Value *FnArg = Call.getArgOperand(0)->stripPointerCasts();
56300b57cec5SDimitry Andric     Function *Fn = dyn_cast<Function>(FnArg);
563181ad6265SDimitry Andric     Check(Fn && !Fn->isDeclaration(),
56320b57cec5SDimitry Andric           "llvm.localrecover first "
56330b57cec5SDimitry Andric           "argument must be function defined in this module",
56340b57cec5SDimitry Andric           Call);
56350b57cec5SDimitry Andric     auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
56360b57cec5SDimitry Andric     auto &Entry = FrameEscapeInfo[Fn];
56370b57cec5SDimitry Andric     Entry.second = unsigned(
56380b57cec5SDimitry Andric         std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
56390b57cec5SDimitry Andric     break;
56400b57cec5SDimitry Andric   }
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric   case Intrinsic::experimental_gc_statepoint:
56430b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CallInst>(&Call))
564481ad6265SDimitry Andric       Check(!CI->isInlineAsm(),
56450b57cec5SDimitry Andric             "gc.statepoint support for inline assembly unimplemented", CI);
564681ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
56470b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
56480b57cec5SDimitry Andric 
56490b57cec5SDimitry Andric     verifyStatepoint(Call);
56500b57cec5SDimitry Andric     break;
56510b57cec5SDimitry Andric   case Intrinsic::experimental_gc_result: {
565281ad6265SDimitry Andric     Check(Call.getParent()->getParent()->hasGC(),
56530b57cec5SDimitry Andric           "Enclosing function does not use GC.", Call);
5654bdd1243dSDimitry Andric 
5655bdd1243dSDimitry Andric     auto *Statepoint = Call.getArgOperand(0);
5656bdd1243dSDimitry Andric     if (isa<UndefValue>(Statepoint))
5657bdd1243dSDimitry Andric       break;
5658bdd1243dSDimitry Andric 
56590b57cec5SDimitry Andric     // Are we tied to a statepoint properly?
5660bdd1243dSDimitry Andric     const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
56610b57cec5SDimitry Andric     const Function *StatepointFn =
56620b57cec5SDimitry Andric         StatepointCall ? StatepointCall->getCalledFunction() : nullptr;
566381ad6265SDimitry Andric     Check(StatepointFn && StatepointFn->isDeclaration() &&
56640b57cec5SDimitry Andric               StatepointFn->getIntrinsicID() ==
56650b57cec5SDimitry Andric                   Intrinsic::experimental_gc_statepoint,
56660b57cec5SDimitry Andric           "gc.result operand #1 must be from a statepoint", Call,
56670b57cec5SDimitry Andric           Call.getArgOperand(0));
56680b57cec5SDimitry Andric 
566981ad6265SDimitry Andric     // Check that result type matches wrapped callee.
567081ad6265SDimitry Andric     auto *TargetFuncType =
567181ad6265SDimitry Andric         cast<FunctionType>(StatepointCall->getParamElementType(2));
567281ad6265SDimitry Andric     Check(Call.getType() == TargetFuncType->getReturnType(),
56730b57cec5SDimitry Andric           "gc.result result type does not match wrapped callee", Call);
56740b57cec5SDimitry Andric     break;
56750b57cec5SDimitry Andric   }
56760b57cec5SDimitry Andric   case Intrinsic::experimental_gc_relocate: {
567781ad6265SDimitry Andric     Check(Call.arg_size() == 3, "wrong number of arguments", Call);
56780b57cec5SDimitry Andric 
567981ad6265SDimitry Andric     Check(isa<PointerType>(Call.getType()->getScalarType()),
56800b57cec5SDimitry Andric           "gc.relocate must return a pointer or a vector of pointers", Call);
56810b57cec5SDimitry Andric 
56820b57cec5SDimitry Andric     // Check that this relocate is correctly tied to the statepoint
56830b57cec5SDimitry Andric 
56840b57cec5SDimitry Andric     // This is case for relocate on the unwinding path of an invoke statepoint
56850b57cec5SDimitry Andric     if (LandingPadInst *LandingPad =
56860b57cec5SDimitry Andric             dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
56870b57cec5SDimitry Andric 
56880b57cec5SDimitry Andric       const BasicBlock *InvokeBB =
56890b57cec5SDimitry Andric           LandingPad->getParent()->getUniquePredecessor();
56900b57cec5SDimitry Andric 
56910b57cec5SDimitry Andric       // Landingpad relocates should have only one predecessor with invoke
56920b57cec5SDimitry Andric       // statepoint terminator
569381ad6265SDimitry Andric       Check(InvokeBB, "safepoints should have unique landingpads",
56940b57cec5SDimitry Andric             LandingPad->getParent());
569581ad6265SDimitry Andric       Check(InvokeBB->getTerminator(), "safepoint block should be well formed",
56960b57cec5SDimitry Andric             InvokeBB);
569781ad6265SDimitry Andric       Check(isa<GCStatepointInst>(InvokeBB->getTerminator()),
56980b57cec5SDimitry Andric             "gc relocate should be linked to a statepoint", InvokeBB);
56990b57cec5SDimitry Andric     } else {
57000b57cec5SDimitry Andric       // In all other cases relocate should be tied to the statepoint directly.
57010b57cec5SDimitry Andric       // This covers relocates on a normal return path of invoke statepoint and
57020b57cec5SDimitry Andric       // relocates of a call statepoint.
5703fcaf7f86SDimitry Andric       auto *Token = Call.getArgOperand(0);
5704fcaf7f86SDimitry Andric       Check(isa<GCStatepointInst>(Token) || isa<UndefValue>(Token),
57050b57cec5SDimitry Andric             "gc relocate is incorrectly tied to the statepoint", Call, Token);
57060b57cec5SDimitry Andric     }
57070b57cec5SDimitry Andric 
57080b57cec5SDimitry Andric     // Verify rest of the relocate arguments.
5709fcaf7f86SDimitry Andric     const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
57100b57cec5SDimitry Andric 
57110b57cec5SDimitry Andric     // Both the base and derived must be piped through the safepoint.
57120b57cec5SDimitry Andric     Value *Base = Call.getArgOperand(1);
571381ad6265SDimitry Andric     Check(isa<ConstantInt>(Base),
57140b57cec5SDimitry Andric           "gc.relocate operand #2 must be integer offset", Call);
57150b57cec5SDimitry Andric 
57160b57cec5SDimitry Andric     Value *Derived = Call.getArgOperand(2);
571781ad6265SDimitry Andric     Check(isa<ConstantInt>(Derived),
57180b57cec5SDimitry Andric           "gc.relocate operand #3 must be integer offset", Call);
57190b57cec5SDimitry Andric 
57205ffd83dbSDimitry Andric     const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
57215ffd83dbSDimitry Andric     const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
57225ffd83dbSDimitry Andric 
57230b57cec5SDimitry Andric     // Check the bounds
5724fcaf7f86SDimitry Andric     if (isa<UndefValue>(StatepointCall))
5725fcaf7f86SDimitry Andric       break;
5726fcaf7f86SDimitry Andric     if (auto Opt = cast<GCStatepointInst>(StatepointCall)
5727fcaf7f86SDimitry Andric                        .getOperandBundle(LLVMContext::OB_gc_live)) {
572881ad6265SDimitry Andric       Check(BaseIndex < Opt->Inputs.size(),
57290b57cec5SDimitry Andric             "gc.relocate: statepoint base index out of bounds", Call);
573081ad6265SDimitry Andric       Check(DerivedIndex < Opt->Inputs.size(),
57315ffd83dbSDimitry Andric             "gc.relocate: statepoint derived index out of bounds", Call);
57325ffd83dbSDimitry Andric     }
57330b57cec5SDimitry Andric 
57340b57cec5SDimitry Andric     // Relocated value must be either a pointer type or vector-of-pointer type,
57350b57cec5SDimitry Andric     // but gc_relocate does not need to return the same pointer type as the
57360b57cec5SDimitry Andric     // relocated pointer. It can be casted to the correct type later if it's
57370b57cec5SDimitry Andric     // desired. However, they must have the same address space and 'vectorness'
57380b57cec5SDimitry Andric     GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
5739bdd1243dSDimitry Andric     auto *ResultType = Call.getType();
5740bdd1243dSDimitry Andric     auto *DerivedType = Relocate.getDerivedPtr()->getType();
5741bdd1243dSDimitry Andric     auto *BaseType = Relocate.getBasePtr()->getType();
57420b57cec5SDimitry Andric 
5743bdd1243dSDimitry Andric     Check(BaseType->isPtrOrPtrVectorTy(),
5744bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5745bdd1243dSDimitry Andric     Check(DerivedType->isPtrOrPtrVectorTy(),
5746bdd1243dSDimitry Andric           "gc.relocate: relocated value must be a pointer", Call);
5747bdd1243dSDimitry Andric 
574881ad6265SDimitry Andric     Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
57490b57cec5SDimitry Andric           "gc.relocate: vector relocates to vector and pointer to pointer",
57500b57cec5SDimitry Andric           Call);
575181ad6265SDimitry Andric     Check(
57520b57cec5SDimitry Andric         ResultType->getPointerAddressSpace() ==
57530b57cec5SDimitry Andric             DerivedType->getPointerAddressSpace(),
57540b57cec5SDimitry Andric         "gc.relocate: relocating a pointer shouldn't change its address space",
57550b57cec5SDimitry Andric         Call);
5756bdd1243dSDimitry Andric 
5757bdd1243dSDimitry Andric     auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
5758bdd1243dSDimitry Andric     Check(GC, "gc.relocate: calling function must have GCStrategy",
5759bdd1243dSDimitry Andric           Call.getFunction());
5760bdd1243dSDimitry Andric     if (GC) {
5761bdd1243dSDimitry Andric       auto isGCPtr = [&GC](Type *PTy) {
5762bdd1243dSDimitry Andric         return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
5763bdd1243dSDimitry Andric       };
5764bdd1243dSDimitry Andric       Check(isGCPtr(ResultType), "gc.relocate: must return gc pointer", Call);
5765bdd1243dSDimitry Andric       Check(isGCPtr(BaseType),
5766bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5767bdd1243dSDimitry Andric       Check(isGCPtr(DerivedType),
5768bdd1243dSDimitry Andric             "gc.relocate: relocated value must be a gc pointer", Call);
5769bdd1243dSDimitry Andric     }
57700b57cec5SDimitry Andric     break;
57710b57cec5SDimitry Andric   }
5772*0fca6ea1SDimitry Andric   case Intrinsic::experimental_patchpoint: {
5773*0fca6ea1SDimitry Andric     if (Call.getCallingConv() == CallingConv::AnyReg) {
5774*0fca6ea1SDimitry Andric       Check(Call.getType()->isSingleValueType(),
5775*0fca6ea1SDimitry Andric             "patchpoint: invalid return type used with anyregcc", Call);
5776*0fca6ea1SDimitry Andric     }
5777*0fca6ea1SDimitry Andric     break;
5778*0fca6ea1SDimitry Andric   }
57790b57cec5SDimitry Andric   case Intrinsic::eh_exceptioncode:
57800b57cec5SDimitry Andric   case Intrinsic::eh_exceptionpointer: {
578181ad6265SDimitry Andric     Check(isa<CatchPadInst>(Call.getArgOperand(0)),
57820b57cec5SDimitry Andric           "eh.exceptionpointer argument must be a catchpad", Call);
57830b57cec5SDimitry Andric     break;
57840b57cec5SDimitry Andric   }
57855ffd83dbSDimitry Andric   case Intrinsic::get_active_lane_mask: {
578681ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(),
578781ad6265SDimitry Andric           "get_active_lane_mask: must return a "
578881ad6265SDimitry Andric           "vector",
578981ad6265SDimitry Andric           Call);
57905ffd83dbSDimitry Andric     auto *ElemTy = Call.getType()->getScalarType();
579181ad6265SDimitry Andric     Check(ElemTy->isIntegerTy(1),
579281ad6265SDimitry Andric           "get_active_lane_mask: element type is not "
579381ad6265SDimitry Andric           "i1",
579481ad6265SDimitry Andric           Call);
57955ffd83dbSDimitry Andric     break;
57965ffd83dbSDimitry Andric   }
579706c3fb27SDimitry Andric   case Intrinsic::experimental_get_vector_length: {
579806c3fb27SDimitry Andric     ConstantInt *VF = cast<ConstantInt>(Call.getArgOperand(1));
579906c3fb27SDimitry Andric     Check(!VF->isNegative() && !VF->isZero(),
580006c3fb27SDimitry Andric           "get_vector_length: VF must be positive", Call);
580106c3fb27SDimitry Andric     break;
580206c3fb27SDimitry Andric   }
58030b57cec5SDimitry Andric   case Intrinsic::masked_load: {
580481ad6265SDimitry Andric     Check(Call.getType()->isVectorTy(), "masked_load: must return a vector",
58050b57cec5SDimitry Andric           Call);
58060b57cec5SDimitry Andric 
58070b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1));
58080b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(2);
58090b57cec5SDimitry Andric     Value *PassThru = Call.getArgOperand(3);
581081ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_load: mask must be vector",
58110b57cec5SDimitry Andric           Call);
581281ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
58130b57cec5SDimitry Andric           "masked_load: alignment must be a power of 2", Call);
581481ad6265SDimitry Andric     Check(PassThru->getType() == Call.getType(),
5815fe6060f1SDimitry Andric           "masked_load: pass through and return type must match", Call);
581681ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5817fe6060f1SDimitry Andric               cast<VectorType>(Call.getType())->getElementCount(),
5818fe6060f1SDimitry Andric           "masked_load: vector mask must be same length as return", Call);
58190b57cec5SDimitry Andric     break;
58200b57cec5SDimitry Andric   }
58210b57cec5SDimitry Andric   case Intrinsic::masked_store: {
58220b57cec5SDimitry Andric     Value *Val = Call.getArgOperand(0);
58230b57cec5SDimitry Andric     ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2));
58240b57cec5SDimitry Andric     Value *Mask = Call.getArgOperand(3);
582581ad6265SDimitry Andric     Check(Mask->getType()->isVectorTy(), "masked_store: mask must be vector",
58260b57cec5SDimitry Andric           Call);
582781ad6265SDimitry Andric     Check(Alignment->getValue().isPowerOf2(),
58280b57cec5SDimitry Andric           "masked_store: alignment must be a power of 2", Call);
582981ad6265SDimitry Andric     Check(cast<VectorType>(Mask->getType())->getElementCount() ==
5830fe6060f1SDimitry Andric               cast<VectorType>(Val->getType())->getElementCount(),
5831fe6060f1SDimitry Andric           "masked_store: vector mask must be same length as value", Call);
58320b57cec5SDimitry Andric     break;
58330b57cec5SDimitry Andric   }
58340b57cec5SDimitry Andric 
58355ffd83dbSDimitry Andric   case Intrinsic::masked_gather: {
58365ffd83dbSDimitry Andric     const APInt &Alignment =
58375ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(1))->getValue();
583881ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
58395ffd83dbSDimitry Andric           "masked_gather: alignment must be 0 or a power of 2", Call);
58405ffd83dbSDimitry Andric     break;
58415ffd83dbSDimitry Andric   }
58425ffd83dbSDimitry Andric   case Intrinsic::masked_scatter: {
58435ffd83dbSDimitry Andric     const APInt &Alignment =
58445ffd83dbSDimitry Andric         cast<ConstantInt>(Call.getArgOperand(2))->getValue();
584581ad6265SDimitry Andric     Check(Alignment.isZero() || Alignment.isPowerOf2(),
58465ffd83dbSDimitry Andric           "masked_scatter: alignment must be 0 or a power of 2", Call);
58475ffd83dbSDimitry Andric     break;
58485ffd83dbSDimitry Andric   }
58495ffd83dbSDimitry Andric 
58500b57cec5SDimitry Andric   case Intrinsic::experimental_guard: {
585181ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
585281ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
58530b57cec5SDimitry Andric           "experimental_guard must have exactly one "
58540b57cec5SDimitry Andric           "\"deopt\" operand bundle");
58550b57cec5SDimitry Andric     break;
58560b57cec5SDimitry Andric   }
58570b57cec5SDimitry Andric 
58580b57cec5SDimitry Andric   case Intrinsic::experimental_deoptimize: {
585981ad6265SDimitry Andric     Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
58600b57cec5SDimitry Andric           Call);
586181ad6265SDimitry Andric     Check(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
58620b57cec5SDimitry Andric           "experimental_deoptimize must have exactly one "
58630b57cec5SDimitry Andric           "\"deopt\" operand bundle");
586481ad6265SDimitry Andric     Check(Call.getType() == Call.getFunction()->getReturnType(),
58650b57cec5SDimitry Andric           "experimental_deoptimize return type must match caller return type");
58660b57cec5SDimitry Andric 
58670b57cec5SDimitry Andric     if (isa<CallInst>(Call)) {
58680b57cec5SDimitry Andric       auto *RI = dyn_cast<ReturnInst>(Call.getNextNode());
586981ad6265SDimitry Andric       Check(RI,
58700b57cec5SDimitry Andric             "calls to experimental_deoptimize must be followed by a return");
58710b57cec5SDimitry Andric 
58720b57cec5SDimitry Andric       if (!Call.getType()->isVoidTy() && RI)
587381ad6265SDimitry Andric         Check(RI->getReturnValue() == &Call,
58740b57cec5SDimitry Andric               "calls to experimental_deoptimize must be followed by a return "
58750b57cec5SDimitry Andric               "of the value computed by experimental_deoptimize");
58760b57cec5SDimitry Andric     }
58770b57cec5SDimitry Andric 
58780b57cec5SDimitry Andric     break;
58790b57cec5SDimitry Andric   }
5880*0fca6ea1SDimitry Andric   case Intrinsic::vastart: {
5881*0fca6ea1SDimitry Andric     Check(Call.getFunction()->isVarArg(),
5882*0fca6ea1SDimitry Andric           "va_start called in a non-varargs function");
5883*0fca6ea1SDimitry Andric     break;
5884*0fca6ea1SDimitry Andric   }
5885fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_and:
5886fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_or:
5887fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_xor:
5888fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_add:
5889fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_mul:
5890fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smax:
5891fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_smin:
5892fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umax:
5893fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_umin: {
5894fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
589581ad6265SDimitry Andric     Check(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(),
5896fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5897fe6060f1SDimitry Andric     break;
5898fe6060f1SDimitry Andric   }
5899fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmax:
5900fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmin: {
5901fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(0)->getType();
590281ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5903fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
5904fe6060f1SDimitry Andric     break;
5905fe6060f1SDimitry Andric   }
5906fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fadd:
5907fe6060f1SDimitry Andric   case Intrinsic::vector_reduce_fmul: {
5908fe6060f1SDimitry Andric     // Unlike the other reductions, the first argument is a start value. The
5909fe6060f1SDimitry Andric     // second argument is the vector to be reduced.
5910fe6060f1SDimitry Andric     Type *ArgTy = Call.getArgOperand(1)->getType();
591181ad6265SDimitry Andric     Check(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(),
5912fe6060f1SDimitry Andric           "Intrinsic has incorrect argument type!");
59130b57cec5SDimitry Andric     break;
59140b57cec5SDimitry Andric   }
59150b57cec5SDimitry Andric   case Intrinsic::smul_fix:
59160b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
59178bcb0991SDimitry Andric   case Intrinsic::umul_fix:
5918480093f4SDimitry Andric   case Intrinsic::umul_fix_sat:
5919480093f4SDimitry Andric   case Intrinsic::sdiv_fix:
59205ffd83dbSDimitry Andric   case Intrinsic::sdiv_fix_sat:
59215ffd83dbSDimitry Andric   case Intrinsic::udiv_fix:
59225ffd83dbSDimitry Andric   case Intrinsic::udiv_fix_sat: {
59230b57cec5SDimitry Andric     Value *Op1 = Call.getArgOperand(0);
59240b57cec5SDimitry Andric     Value *Op2 = Call.getArgOperand(1);
592581ad6265SDimitry Andric     Check(Op1->getType()->isIntOrIntVectorTy(),
5926480093f4SDimitry Andric           "first operand of [us][mul|div]_fix[_sat] must be an int type or "
5927480093f4SDimitry Andric           "vector of ints");
592881ad6265SDimitry Andric     Check(Op2->getType()->isIntOrIntVectorTy(),
5929480093f4SDimitry Andric           "second operand of [us][mul|div]_fix[_sat] must be an int type or "
5930480093f4SDimitry Andric           "vector of ints");
59310b57cec5SDimitry Andric 
59320b57cec5SDimitry Andric     auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
5933cb14a3feSDimitry Andric     Check(Op3->getType()->isIntegerTy(),
5934cb14a3feSDimitry Andric           "third operand of [us][mul|div]_fix[_sat] must be an int type");
5935cb14a3feSDimitry Andric     Check(Op3->getBitWidth() <= 32,
5936cb14a3feSDimitry Andric           "third operand of [us][mul|div]_fix[_sat] must fit within 32 bits");
59370b57cec5SDimitry Andric 
5938480093f4SDimitry Andric     if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
59395ffd83dbSDimitry Andric         ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
594081ad6265SDimitry Andric       Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
5941480093f4SDimitry Andric             "the scale of s[mul|div]_fix[_sat] must be less than the width of "
5942480093f4SDimitry Andric             "the operands");
59430b57cec5SDimitry Andric     } else {
594481ad6265SDimitry Andric       Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
5945480093f4SDimitry Andric             "the scale of u[mul|div]_fix[_sat] must be less than or equal "
5946480093f4SDimitry Andric             "to the width of the operands");
59470b57cec5SDimitry Andric     }
59480b57cec5SDimitry Andric     break;
59490b57cec5SDimitry Andric   }
59500b57cec5SDimitry Andric   case Intrinsic::lrint:
59510b57cec5SDimitry Andric   case Intrinsic::llrint: {
59520b57cec5SDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
59530b57cec5SDimitry Andric     Type *ResultTy = Call.getType();
59545f757f3fSDimitry Andric     Check(
59555f757f3fSDimitry Andric         ValTy->isFPOrFPVectorTy() && ResultTy->isIntOrIntVectorTy(),
59565f757f3fSDimitry Andric         "llvm.lrint, llvm.llrint: argument must be floating-point or vector "
59575f757f3fSDimitry Andric         "of floating-points, and result must be integer or vector of integers",
59585f757f3fSDimitry Andric         &Call);
59595f757f3fSDimitry Andric     Check(ValTy->isVectorTy() == ResultTy->isVectorTy(),
59605f757f3fSDimitry Andric           "llvm.lrint, llvm.llrint: argument and result disagree on vector use",
59615f757f3fSDimitry Andric           &Call);
59625f757f3fSDimitry Andric     if (ValTy->isVectorTy()) {
59635f757f3fSDimitry Andric       Check(cast<VectorType>(ValTy)->getElementCount() ==
59645f757f3fSDimitry Andric                 cast<VectorType>(ResultTy)->getElementCount(),
59655f757f3fSDimitry Andric             "llvm.lrint, llvm.llrint: argument must be same length as result",
59665f757f3fSDimitry Andric             &Call);
59675f757f3fSDimitry Andric     }
59685f757f3fSDimitry Andric     break;
59695f757f3fSDimitry Andric   }
59705f757f3fSDimitry Andric   case Intrinsic::lround:
59715f757f3fSDimitry Andric   case Intrinsic::llround: {
59725f757f3fSDimitry Andric     Type *ValTy = Call.getArgOperand(0)->getType();
59735f757f3fSDimitry Andric     Type *ResultTy = Call.getType();
597481ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
59750b57cec5SDimitry Andric           "Intrinsic does not support vectors", &Call);
59760b57cec5SDimitry Andric     break;
59770b57cec5SDimitry Andric   }
59785ffd83dbSDimitry Andric   case Intrinsic::bswap: {
59795ffd83dbSDimitry Andric     Type *Ty = Call.getType();
59805ffd83dbSDimitry Andric     unsigned Size = Ty->getScalarSizeInBits();
598181ad6265SDimitry Andric     Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
59825ffd83dbSDimitry Andric     break;
59835ffd83dbSDimitry Andric   }
5984e8d8bef9SDimitry Andric   case Intrinsic::invariant_start: {
5985e8d8bef9SDimitry Andric     ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
598681ad6265SDimitry Andric     Check(InvariantSize &&
5987e8d8bef9SDimitry Andric               (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
5988e8d8bef9SDimitry Andric           "invariant_start parameter must be -1, 0 or a positive number",
5989e8d8bef9SDimitry Andric           &Call);
5990e8d8bef9SDimitry Andric     break;
5991e8d8bef9SDimitry Andric   }
59925ffd83dbSDimitry Andric   case Intrinsic::matrix_multiply:
59935ffd83dbSDimitry Andric   case Intrinsic::matrix_transpose:
59945ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_load:
59955ffd83dbSDimitry Andric   case Intrinsic::matrix_column_major_store: {
59965ffd83dbSDimitry Andric     Function *IF = Call.getCalledFunction();
59975ffd83dbSDimitry Andric     ConstantInt *Stride = nullptr;
59985ffd83dbSDimitry Andric     ConstantInt *NumRows;
59995ffd83dbSDimitry Andric     ConstantInt *NumColumns;
60005ffd83dbSDimitry Andric     VectorType *ResultTy;
60015ffd83dbSDimitry Andric     Type *Op0ElemTy = nullptr;
60025ffd83dbSDimitry Andric     Type *Op1ElemTy = nullptr;
60035ffd83dbSDimitry Andric     switch (ID) {
600406c3fb27SDimitry Andric     case Intrinsic::matrix_multiply: {
60055ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(2));
600606c3fb27SDimitry Andric       ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
60075ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
600806c3fb27SDimitry Andric       Check(cast<FixedVectorType>(Call.getArgOperand(0)->getType())
600906c3fb27SDimitry Andric                     ->getNumElements() ==
601006c3fb27SDimitry Andric                 NumRows->getZExtValue() * N->getZExtValue(),
601106c3fb27SDimitry Andric             "First argument of a matrix operation does not match specified "
601206c3fb27SDimitry Andric             "shape!");
601306c3fb27SDimitry Andric       Check(cast<FixedVectorType>(Call.getArgOperand(1)->getType())
601406c3fb27SDimitry Andric                     ->getNumElements() ==
601506c3fb27SDimitry Andric                 N->getZExtValue() * NumColumns->getZExtValue(),
601606c3fb27SDimitry Andric             "Second argument of a matrix operation does not match specified "
601706c3fb27SDimitry Andric             "shape!");
601806c3fb27SDimitry Andric 
60195ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
60205ffd83dbSDimitry Andric       Op0ElemTy =
60215ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
60225ffd83dbSDimitry Andric       Op1ElemTy =
60235ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType();
60245ffd83dbSDimitry Andric       break;
602506c3fb27SDimitry Andric     }
60265ffd83dbSDimitry Andric     case Intrinsic::matrix_transpose:
60275ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(1));
60285ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
60295ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
60305ffd83dbSDimitry Andric       Op0ElemTy =
60315ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
60325ffd83dbSDimitry Andric       break;
60334824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_load: {
60345ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1));
60355ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(3));
60365ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
60375ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getType());
60385ffd83dbSDimitry Andric       break;
60394824e7fdSDimitry Andric     }
60404824e7fdSDimitry Andric     case Intrinsic::matrix_column_major_store: {
60415ffd83dbSDimitry Andric       Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2));
60425ffd83dbSDimitry Andric       NumRows = cast<ConstantInt>(Call.getArgOperand(4));
60435ffd83dbSDimitry Andric       NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
60445ffd83dbSDimitry Andric       ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType());
60455ffd83dbSDimitry Andric       Op0ElemTy =
60465ffd83dbSDimitry Andric           cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType();
60475ffd83dbSDimitry Andric       break;
60484824e7fdSDimitry Andric     }
60495ffd83dbSDimitry Andric     default:
60505ffd83dbSDimitry Andric       llvm_unreachable("unexpected intrinsic");
60515ffd83dbSDimitry Andric     }
60525ffd83dbSDimitry Andric 
605381ad6265SDimitry Andric     Check(ResultTy->getElementType()->isIntegerTy() ||
60545ffd83dbSDimitry Andric               ResultTy->getElementType()->isFloatingPointTy(),
60555ffd83dbSDimitry Andric           "Result type must be an integer or floating-point type!", IF);
60565ffd83dbSDimitry Andric 
60574824e7fdSDimitry Andric     if (Op0ElemTy)
605881ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op0ElemTy,
60595ffd83dbSDimitry Andric             "Vector element type mismatch of the result and first operand "
606081ad6265SDimitry Andric             "vector!",
606181ad6265SDimitry Andric             IF);
60625ffd83dbSDimitry Andric 
60635ffd83dbSDimitry Andric     if (Op1ElemTy)
606481ad6265SDimitry Andric       Check(ResultTy->getElementType() == Op1ElemTy,
60655ffd83dbSDimitry Andric             "Vector element type mismatch of the result and second operand "
606681ad6265SDimitry Andric             "vector!",
606781ad6265SDimitry Andric             IF);
60685ffd83dbSDimitry Andric 
606981ad6265SDimitry Andric     Check(cast<FixedVectorType>(ResultTy)->getNumElements() ==
60705ffd83dbSDimitry Andric               NumRows->getZExtValue() * NumColumns->getZExtValue(),
60715ffd83dbSDimitry Andric           "Result of a matrix operation does not fit in the returned vector!");
60725ffd83dbSDimitry Andric 
60735ffd83dbSDimitry Andric     if (Stride)
607481ad6265SDimitry Andric       Check(Stride->getZExtValue() >= NumRows->getZExtValue(),
60755ffd83dbSDimitry Andric             "Stride must be greater or equal than the number of rows!", IF);
60765ffd83dbSDimitry Andric 
60775ffd83dbSDimitry Andric     break;
60785ffd83dbSDimitry Andric   }
6079*0fca6ea1SDimitry Andric   case Intrinsic::vector_splice: {
608004eeddc0SDimitry Andric     VectorType *VecTy = cast<VectorType>(Call.getType());
608104eeddc0SDimitry Andric     int64_t Idx = cast<ConstantInt>(Call.getArgOperand(2))->getSExtValue();
608204eeddc0SDimitry Andric     int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
608304eeddc0SDimitry Andric     if (Call.getParent() && Call.getParent()->getParent()) {
608404eeddc0SDimitry Andric       AttributeList Attrs = Call.getParent()->getParent()->getAttributes();
608504eeddc0SDimitry Andric       if (Attrs.hasFnAttr(Attribute::VScaleRange))
608604eeddc0SDimitry Andric         KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
608704eeddc0SDimitry Andric     }
608881ad6265SDimitry Andric     Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
608904eeddc0SDimitry Andric               (Idx >= 0 && Idx < KnownMinNumElements),
609004eeddc0SDimitry Andric           "The splice index exceeds the range [-VL, VL-1] where VL is the "
609104eeddc0SDimitry Andric           "known minimum number of elements in the vector. For scalable "
609204eeddc0SDimitry Andric           "vectors the minimum number of elements is determined from "
609304eeddc0SDimitry Andric           "vscale_range.",
609404eeddc0SDimitry Andric           &Call);
609504eeddc0SDimitry Andric     break;
609604eeddc0SDimitry Andric   }
6097fe6060f1SDimitry Andric   case Intrinsic::experimental_stepvector: {
6098fe6060f1SDimitry Andric     VectorType *VecTy = dyn_cast<VectorType>(Call.getType());
609981ad6265SDimitry Andric     Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6100fe6060f1SDimitry Andric               VecTy->getScalarSizeInBits() >= 8,
6101fe6060f1SDimitry Andric           "experimental_stepvector only supported for vectors of integers "
6102fe6060f1SDimitry Andric           "with a bitwidth of at least 8.",
6103fe6060f1SDimitry Andric           &Call);
6104fe6060f1SDimitry Andric     break;
6105fe6060f1SDimitry Andric   }
610681ad6265SDimitry Andric   case Intrinsic::vector_insert: {
6107fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
6108fe6060f1SDimitry Andric     Value *SubVec = Call.getArgOperand(1);
6109fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(2);
6110fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6111e8d8bef9SDimitry Andric 
6112fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
6113fe6060f1SDimitry Andric     VectorType *SubVecTy = cast<VectorType>(SubVec->getType());
6114fe6060f1SDimitry Andric 
6115fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
6116fe6060f1SDimitry Andric     ElementCount SubVecEC = SubVecTy->getElementCount();
611781ad6265SDimitry Andric     Check(VecTy->getElementType() == SubVecTy->getElementType(),
611881ad6265SDimitry Andric           "vector_insert parameters must have the same element "
6119e8d8bef9SDimitry Andric           "type.",
6120e8d8bef9SDimitry Andric           &Call);
612181ad6265SDimitry Andric     Check(IdxN % SubVecEC.getKnownMinValue() == 0,
612281ad6265SDimitry Andric           "vector_insert index must be a constant multiple of "
6123fe6060f1SDimitry Andric           "the subvector's known minimum vector length.");
6124fe6060f1SDimitry Andric 
6125fe6060f1SDimitry Andric     // If this insertion is not the 'mixed' case where a fixed vector is
6126fe6060f1SDimitry Andric     // inserted into a scalable vector, ensure that the insertion of the
6127fe6060f1SDimitry Andric     // subvector does not overrun the parent vector.
6128fe6060f1SDimitry Andric     if (VecEC.isScalable() == SubVecEC.isScalable()) {
612981ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
6130fe6060f1SDimitry Andric                 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
613181ad6265SDimitry Andric             "subvector operand of vector_insert would overrun the "
6132fe6060f1SDimitry Andric             "vector being inserted into.");
6133fe6060f1SDimitry Andric     }
6134e8d8bef9SDimitry Andric     break;
6135e8d8bef9SDimitry Andric   }
613681ad6265SDimitry Andric   case Intrinsic::vector_extract: {
6137fe6060f1SDimitry Andric     Value *Vec = Call.getArgOperand(0);
6138fe6060f1SDimitry Andric     Value *Idx = Call.getArgOperand(1);
6139fe6060f1SDimitry Andric     unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6140fe6060f1SDimitry Andric 
6141e8d8bef9SDimitry Andric     VectorType *ResultTy = cast<VectorType>(Call.getType());
6142fe6060f1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Vec->getType());
6143fe6060f1SDimitry Andric 
6144fe6060f1SDimitry Andric     ElementCount VecEC = VecTy->getElementCount();
6145fe6060f1SDimitry Andric     ElementCount ResultEC = ResultTy->getElementCount();
6146e8d8bef9SDimitry Andric 
614781ad6265SDimitry Andric     Check(ResultTy->getElementType() == VecTy->getElementType(),
614881ad6265SDimitry Andric           "vector_extract result must have the same element "
6149e8d8bef9SDimitry Andric           "type as the input vector.",
6150e8d8bef9SDimitry Andric           &Call);
615181ad6265SDimitry Andric     Check(IdxN % ResultEC.getKnownMinValue() == 0,
615281ad6265SDimitry Andric           "vector_extract index must be a constant multiple of "
6153fe6060f1SDimitry Andric           "the result type's known minimum vector length.");
6154fe6060f1SDimitry Andric 
61555f757f3fSDimitry Andric     // If this extraction is not the 'mixed' case where a fixed vector is
6156fe6060f1SDimitry Andric     // extracted from a scalable vector, ensure that the extraction does not
6157fe6060f1SDimitry Andric     // overrun the parent vector.
6158fe6060f1SDimitry Andric     if (VecEC.isScalable() == ResultEC.isScalable()) {
615981ad6265SDimitry Andric       Check(IdxN < VecEC.getKnownMinValue() &&
6160fe6060f1SDimitry Andric                 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
616181ad6265SDimitry Andric             "vector_extract would overrun.");
6162fe6060f1SDimitry Andric     }
6163e8d8bef9SDimitry Andric     break;
6164e8d8bef9SDimitry Andric   }
6165*0fca6ea1SDimitry Andric   case Intrinsic::experimental_vector_partial_reduce_add: {
6166*0fca6ea1SDimitry Andric     VectorType *AccTy = cast<VectorType>(Call.getArgOperand(0)->getType());
6167*0fca6ea1SDimitry Andric     VectorType *VecTy = cast<VectorType>(Call.getArgOperand(1)->getType());
6168*0fca6ea1SDimitry Andric 
6169*0fca6ea1SDimitry Andric     unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6170*0fca6ea1SDimitry Andric     unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6171*0fca6ea1SDimitry Andric 
6172*0fca6ea1SDimitry Andric     Check((VecWidth % AccWidth) == 0,
6173*0fca6ea1SDimitry Andric           "Invalid vector widths for partial "
6174*0fca6ea1SDimitry Andric           "reduction. The width of the input vector "
6175*0fca6ea1SDimitry Andric           "must be a positive integer multiple of "
6176*0fca6ea1SDimitry Andric           "the width of the accumulator vector.");
6177*0fca6ea1SDimitry Andric     break;
6178*0fca6ea1SDimitry Andric   }
6179e8d8bef9SDimitry Andric   case Intrinsic::experimental_noalias_scope_decl: {
6180e8d8bef9SDimitry Andric     NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
6181e8d8bef9SDimitry Andric     break;
6182e8d8bef9SDimitry Andric   }
6183fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
618481ad6265SDimitry Andric   case Intrinsic::preserve_struct_access_index:
618581ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
618681ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
618781ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
618881ad6265SDimitry Andric   case Intrinsic::arm_ldrex: {
618981ad6265SDimitry Andric     Type *ElemTy = Call.getParamElementType(0);
619081ad6265SDimitry Andric     Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
619181ad6265SDimitry Andric           &Call);
619281ad6265SDimitry Andric     break;
619381ad6265SDimitry Andric   }
619481ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
619581ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
619681ad6265SDimitry Andric   case Intrinsic::arm_stlex:
619781ad6265SDimitry Andric   case Intrinsic::arm_strex: {
619881ad6265SDimitry Andric     Type *ElemTy = Call.getAttributes().getParamElementType(1);
619981ad6265SDimitry Andric     Check(ElemTy,
620081ad6265SDimitry Andric           "Intrinsic requires elementtype attribute on second argument.",
6201fe6060f1SDimitry Andric           &Call);
6202fe6060f1SDimitry Andric     break;
6203fe6060f1SDimitry Andric   }
6204bdd1243dSDimitry Andric   case Intrinsic::aarch64_prefetch: {
6205bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
6206bdd1243dSDimitry Andric           "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
6207bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
6208bdd1243dSDimitry Andric           "target argument to llvm.aarch64.prefetch must be 0-3", Call);
6209bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
6210bdd1243dSDimitry Andric           "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
6211bdd1243dSDimitry Andric     Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
6212bdd1243dSDimitry Andric           "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
6213bdd1243dSDimitry Andric     break;
6214bdd1243dSDimitry Andric   }
621506c3fb27SDimitry Andric   case Intrinsic::callbr_landingpad: {
621606c3fb27SDimitry Andric     const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
621706c3fb27SDimitry Andric     Check(CBR, "intrinstic requires callbr operand", &Call);
621806c3fb27SDimitry Andric     if (!CBR)
621906c3fb27SDimitry Andric       break;
622006c3fb27SDimitry Andric 
622106c3fb27SDimitry Andric     const BasicBlock *LandingPadBB = Call.getParent();
622206c3fb27SDimitry Andric     const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
622306c3fb27SDimitry Andric     if (!PredBB) {
622406c3fb27SDimitry Andric       CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
622506c3fb27SDimitry Andric       break;
622606c3fb27SDimitry Andric     }
622706c3fb27SDimitry Andric     if (!isa<CallBrInst>(PredBB->getTerminator())) {
622806c3fb27SDimitry Andric       CheckFailed("Intrinsic must have corresponding callbr in predecessor",
622906c3fb27SDimitry Andric                   &Call);
623006c3fb27SDimitry Andric       break;
623106c3fb27SDimitry Andric     }
623206c3fb27SDimitry Andric     Check(llvm::any_of(CBR->getIndirectDests(),
623306c3fb27SDimitry Andric                        [LandingPadBB](const BasicBlock *IndDest) {
623406c3fb27SDimitry Andric                          return IndDest == LandingPadBB;
623506c3fb27SDimitry Andric                        }),
623606c3fb27SDimitry Andric           "Intrinsic's corresponding callbr must have intrinsic's parent basic "
623706c3fb27SDimitry Andric           "block in indirect destination list",
623806c3fb27SDimitry Andric           &Call);
623906c3fb27SDimitry Andric     const Instruction &First = *LandingPadBB->begin();
624006c3fb27SDimitry Andric     Check(&First == &Call, "No other instructions may proceed intrinsic",
624106c3fb27SDimitry Andric           &Call);
624206c3fb27SDimitry Andric     break;
624306c3fb27SDimitry Andric   }
624406c3fb27SDimitry Andric   case Intrinsic::amdgcn_cs_chain: {
624506c3fb27SDimitry Andric     auto CallerCC = Call.getCaller()->getCallingConv();
624606c3fb27SDimitry Andric     switch (CallerCC) {
624706c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS:
624806c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS_Chain:
624906c3fb27SDimitry Andric     case CallingConv::AMDGPU_CS_ChainPreserve:
625006c3fb27SDimitry Andric       break;
625106c3fb27SDimitry Andric     default:
625206c3fb27SDimitry Andric       CheckFailed("Intrinsic can only be used from functions with the "
625306c3fb27SDimitry Andric                   "amdgpu_cs, amdgpu_cs_chain or amdgpu_cs_chain_preserve "
625406c3fb27SDimitry Andric                   "calling conventions",
625506c3fb27SDimitry Andric                   &Call);
625606c3fb27SDimitry Andric       break;
625706c3fb27SDimitry Andric     }
62585f757f3fSDimitry Andric 
62595f757f3fSDimitry Andric     Check(Call.paramHasAttr(2, Attribute::InReg),
62605f757f3fSDimitry Andric           "SGPR arguments must have the `inreg` attribute", &Call);
62615f757f3fSDimitry Andric     Check(!Call.paramHasAttr(3, Attribute::InReg),
62625f757f3fSDimitry Andric           "VGPR arguments must not have the `inreg` attribute", &Call);
62635f757f3fSDimitry Andric     break;
62645f757f3fSDimitry Andric   }
62655f757f3fSDimitry Andric   case Intrinsic::amdgcn_set_inactive_chain_arg: {
62665f757f3fSDimitry Andric     auto CallerCC = Call.getCaller()->getCallingConv();
62675f757f3fSDimitry Andric     switch (CallerCC) {
62685f757f3fSDimitry Andric     case CallingConv::AMDGPU_CS_Chain:
62695f757f3fSDimitry Andric     case CallingConv::AMDGPU_CS_ChainPreserve:
62705f757f3fSDimitry Andric       break;
62715f757f3fSDimitry Andric     default:
62725f757f3fSDimitry Andric       CheckFailed("Intrinsic can only be used from functions with the "
62735f757f3fSDimitry Andric                   "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
62745f757f3fSDimitry Andric                   "calling conventions",
62755f757f3fSDimitry Andric                   &Call);
62765f757f3fSDimitry Andric       break;
62775f757f3fSDimitry Andric     }
62785f757f3fSDimitry Andric 
62795f757f3fSDimitry Andric     unsigned InactiveIdx = 1;
62805f757f3fSDimitry Andric     Check(!Call.paramHasAttr(InactiveIdx, Attribute::InReg),
62815f757f3fSDimitry Andric           "Value for inactive lanes must not have the `inreg` attribute",
62825f757f3fSDimitry Andric           &Call);
62835f757f3fSDimitry Andric     Check(isa<Argument>(Call.getArgOperand(InactiveIdx)),
62845f757f3fSDimitry Andric           "Value for inactive lanes must be a function argument", &Call);
62855f757f3fSDimitry Andric     Check(!cast<Argument>(Call.getArgOperand(InactiveIdx))->hasInRegAttr(),
62865f757f3fSDimitry Andric           "Value for inactive lanes must be a VGPR function argument", &Call);
628706c3fb27SDimitry Andric     break;
628806c3fb27SDimitry Andric   }
6289297eecfbSDimitry Andric   case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
6290297eecfbSDimitry Andric   case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
6291297eecfbSDimitry Andric     Value *V = Call.getArgOperand(0);
6292297eecfbSDimitry Andric     unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
6293297eecfbSDimitry Andric     Check(RegCount % 8 == 0,
6294297eecfbSDimitry Andric           "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
6295297eecfbSDimitry Andric     Check((RegCount >= 24 && RegCount <= 256),
6296297eecfbSDimitry Andric           "reg_count argument to nvvm.setmaxnreg must be within [24, 256]");
6297297eecfbSDimitry Andric     break;
6298297eecfbSDimitry Andric   }
629906c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_entry:
630006c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_anchor:
630106c3fb27SDimitry Andric     break;
630206c3fb27SDimitry Andric   case Intrinsic::experimental_convergence_loop:
630306c3fb27SDimitry Andric     break;
63045f757f3fSDimitry Andric   case Intrinsic::ptrmask: {
63055f757f3fSDimitry Andric     Type *Ty0 = Call.getArgOperand(0)->getType();
63065f757f3fSDimitry Andric     Type *Ty1 = Call.getArgOperand(1)->getType();
63075f757f3fSDimitry Andric     Check(Ty0->isPtrOrPtrVectorTy(),
63085f757f3fSDimitry Andric           "llvm.ptrmask intrinsic first argument must be pointer or vector "
63095f757f3fSDimitry Andric           "of pointers",
63105f757f3fSDimitry Andric           &Call);
63115f757f3fSDimitry Andric     Check(
63125f757f3fSDimitry Andric         Ty0->isVectorTy() == Ty1->isVectorTy(),
63135f757f3fSDimitry Andric         "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
63145f757f3fSDimitry Andric         &Call);
63155f757f3fSDimitry Andric     if (Ty0->isVectorTy())
63165f757f3fSDimitry Andric       Check(cast<VectorType>(Ty0)->getElementCount() ==
63175f757f3fSDimitry Andric                 cast<VectorType>(Ty1)->getElementCount(),
63185f757f3fSDimitry Andric             "llvm.ptrmask intrinsic arguments must have the same number of "
63195f757f3fSDimitry Andric             "elements",
63205f757f3fSDimitry Andric             &Call);
63215f757f3fSDimitry Andric     Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
63225f757f3fSDimitry Andric           "llvm.ptrmask intrinsic second argument bitwidth must match "
63235f757f3fSDimitry Andric           "pointer index type size of first argument",
63245f757f3fSDimitry Andric           &Call);
63255f757f3fSDimitry Andric     break;
63265f757f3fSDimitry Andric   }
6327*0fca6ea1SDimitry Andric   case Intrinsic::threadlocal_address: {
6328*0fca6ea1SDimitry Andric     const Value &Arg0 = *Call.getArgOperand(0);
6329*0fca6ea1SDimitry Andric     Check(isa<GlobalValue>(Arg0),
6330*0fca6ea1SDimitry Andric           "llvm.threadlocal.address first argument must be a GlobalValue");
6331*0fca6ea1SDimitry Andric     Check(cast<GlobalValue>(Arg0).isThreadLocal(),
6332*0fca6ea1SDimitry Andric           "llvm.threadlocal.address operand isThreadLocal() must be true");
6333*0fca6ea1SDimitry Andric     break;
6334*0fca6ea1SDimitry Andric   }
63350b57cec5SDimitry Andric   };
633606c3fb27SDimitry Andric 
633706c3fb27SDimitry Andric   // Verify that there aren't any unmediated control transfers between funclets.
633806c3fb27SDimitry Andric   if (IntrinsicInst::mayLowerToFunctionCall(ID)) {
633906c3fb27SDimitry Andric     Function *F = Call.getParent()->getParent();
634006c3fb27SDimitry Andric     if (F->hasPersonalityFn() &&
634106c3fb27SDimitry Andric         isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
634206c3fb27SDimitry Andric       // Run EH funclet coloring on-demand and cache results for other intrinsic
634306c3fb27SDimitry Andric       // calls in this function
634406c3fb27SDimitry Andric       if (BlockEHFuncletColors.empty())
634506c3fb27SDimitry Andric         BlockEHFuncletColors = colorEHFunclets(*F);
634606c3fb27SDimitry Andric 
634706c3fb27SDimitry Andric       // Check for catch-/cleanup-pad in first funclet block
634806c3fb27SDimitry Andric       bool InEHFunclet = false;
634906c3fb27SDimitry Andric       BasicBlock *CallBB = Call.getParent();
635006c3fb27SDimitry Andric       const ColorVector &CV = BlockEHFuncletColors.find(CallBB)->second;
635106c3fb27SDimitry Andric       assert(CV.size() > 0 && "Uncolored block");
635206c3fb27SDimitry Andric       for (BasicBlock *ColorFirstBB : CV)
635306c3fb27SDimitry Andric         if (dyn_cast_or_null<FuncletPadInst>(ColorFirstBB->getFirstNonPHI()))
635406c3fb27SDimitry Andric           InEHFunclet = true;
635506c3fb27SDimitry Andric 
635606c3fb27SDimitry Andric       // Check for funclet operand bundle
635706c3fb27SDimitry Andric       bool HasToken = false;
635806c3fb27SDimitry Andric       for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
635906c3fb27SDimitry Andric         if (Call.getOperandBundleAt(I).getTagID() == LLVMContext::OB_funclet)
636006c3fb27SDimitry Andric           HasToken = true;
636106c3fb27SDimitry Andric 
636206c3fb27SDimitry Andric       // This would cause silent code truncation in WinEHPrepare
636306c3fb27SDimitry Andric       if (InEHFunclet)
636406c3fb27SDimitry Andric         Check(HasToken, "Missing funclet token on intrinsic call", &Call);
636506c3fb27SDimitry Andric     }
636606c3fb27SDimitry Andric   }
63670b57cec5SDimitry Andric }
63680b57cec5SDimitry Andric 
63690b57cec5SDimitry Andric /// Carefully grab the subprogram from a local scope.
63700b57cec5SDimitry Andric ///
63710b57cec5SDimitry Andric /// This carefully grabs the subprogram from a local scope, avoiding the
63720b57cec5SDimitry Andric /// built-in assertions that would typically fire.
getSubprogram(Metadata * LocalScope)63730b57cec5SDimitry Andric static DISubprogram *getSubprogram(Metadata *LocalScope) {
63740b57cec5SDimitry Andric   if (!LocalScope)
63750b57cec5SDimitry Andric     return nullptr;
63760b57cec5SDimitry Andric 
63770b57cec5SDimitry Andric   if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
63780b57cec5SDimitry Andric     return SP;
63790b57cec5SDimitry Andric 
63800b57cec5SDimitry Andric   if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
63810b57cec5SDimitry Andric     return getSubprogram(LB->getRawScope());
63820b57cec5SDimitry Andric 
63830b57cec5SDimitry Andric   // Just return null; broken scope chains are checked elsewhere.
63840b57cec5SDimitry Andric   assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
63850b57cec5SDimitry Andric   return nullptr;
63860b57cec5SDimitry Andric }
63870b57cec5SDimitry Andric 
visit(DbgLabelRecord & DLR)6388*0fca6ea1SDimitry Andric void Verifier::visit(DbgLabelRecord &DLR) {
6389*0fca6ea1SDimitry Andric   CheckDI(isa<DILabel>(DLR.getRawLabel()),
6390*0fca6ea1SDimitry Andric           "invalid #dbg_label intrinsic variable", &DLR, DLR.getRawLabel());
6391*0fca6ea1SDimitry Andric 
6392*0fca6ea1SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
6393*0fca6ea1SDimitry Andric   if (MDNode *N = DLR.getDebugLoc().getAsMDNode())
6394*0fca6ea1SDimitry Andric     if (!isa<DILocation>(N))
6395*0fca6ea1SDimitry Andric       return;
6396*0fca6ea1SDimitry Andric 
6397*0fca6ea1SDimitry Andric   BasicBlock *BB = DLR.getParent();
6398*0fca6ea1SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
6399*0fca6ea1SDimitry Andric 
6400*0fca6ea1SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
6401*0fca6ea1SDimitry Andric   DILabel *Label = DLR.getLabel();
6402*0fca6ea1SDimitry Andric   DILocation *Loc = DLR.getDebugLoc();
6403*0fca6ea1SDimitry Andric   CheckDI(Loc, "#dbg_label record requires a !dbg attachment", &DLR, BB, F);
6404*0fca6ea1SDimitry Andric 
6405*0fca6ea1SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
6406*0fca6ea1SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
6407*0fca6ea1SDimitry Andric   if (!LabelSP || !LocSP)
6408*0fca6ea1SDimitry Andric     return;
6409*0fca6ea1SDimitry Andric 
6410*0fca6ea1SDimitry Andric   CheckDI(LabelSP == LocSP,
6411*0fca6ea1SDimitry Andric           "mismatched subprogram between #dbg_label label and !dbg attachment",
6412*0fca6ea1SDimitry Andric           &DLR, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
6413*0fca6ea1SDimitry Andric           Loc->getScope()->getSubprogram());
6414*0fca6ea1SDimitry Andric }
6415*0fca6ea1SDimitry Andric 
visit(DbgVariableRecord & DVR)6416*0fca6ea1SDimitry Andric void Verifier::visit(DbgVariableRecord &DVR) {
6417*0fca6ea1SDimitry Andric   BasicBlock *BB = DVR.getParent();
6418*0fca6ea1SDimitry Andric   Function *F = BB->getParent();
6419*0fca6ea1SDimitry Andric 
6420*0fca6ea1SDimitry Andric   CheckDI(DVR.getType() == DbgVariableRecord::LocationType::Value ||
6421*0fca6ea1SDimitry Andric               DVR.getType() == DbgVariableRecord::LocationType::Declare ||
6422*0fca6ea1SDimitry Andric               DVR.getType() == DbgVariableRecord::LocationType::Assign,
6423*0fca6ea1SDimitry Andric           "invalid #dbg record type", &DVR, DVR.getType());
6424*0fca6ea1SDimitry Andric 
6425*0fca6ea1SDimitry Andric   // The location for a DbgVariableRecord must be either a ValueAsMetadata,
6426*0fca6ea1SDimitry Andric   // DIArgList, or an empty MDNode (which is a legacy representation for an
6427*0fca6ea1SDimitry Andric   // "undef" location).
6428*0fca6ea1SDimitry Andric   auto *MD = DVR.getRawLocation();
6429*0fca6ea1SDimitry Andric   CheckDI(MD && (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
6430*0fca6ea1SDimitry Andric                  (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands())),
6431*0fca6ea1SDimitry Andric           "invalid #dbg record address/value", &DVR, MD);
6432*0fca6ea1SDimitry Andric   if (auto *VAM = dyn_cast<ValueAsMetadata>(MD))
6433*0fca6ea1SDimitry Andric     visitValueAsMetadata(*VAM, F);
6434*0fca6ea1SDimitry Andric   else if (auto *AL = dyn_cast<DIArgList>(MD))
6435*0fca6ea1SDimitry Andric     visitDIArgList(*AL, F);
6436*0fca6ea1SDimitry Andric 
6437*0fca6ea1SDimitry Andric   CheckDI(isa_and_nonnull<DILocalVariable>(DVR.getRawVariable()),
6438*0fca6ea1SDimitry Andric           "invalid #dbg record variable", &DVR, DVR.getRawVariable());
6439*0fca6ea1SDimitry Andric   visitMDNode(*DVR.getRawVariable(), AreDebugLocsAllowed::No);
6440*0fca6ea1SDimitry Andric 
6441*0fca6ea1SDimitry Andric   CheckDI(isa_and_nonnull<DIExpression>(DVR.getRawExpression()),
6442*0fca6ea1SDimitry Andric           "invalid #dbg record expression", &DVR, DVR.getRawExpression());
6443*0fca6ea1SDimitry Andric   visitMDNode(*DVR.getExpression(), AreDebugLocsAllowed::No);
6444*0fca6ea1SDimitry Andric 
6445*0fca6ea1SDimitry Andric   if (DVR.isDbgAssign()) {
6446*0fca6ea1SDimitry Andric     CheckDI(isa_and_nonnull<DIAssignID>(DVR.getRawAssignID()),
6447*0fca6ea1SDimitry Andric             "invalid #dbg_assign DIAssignID", &DVR, DVR.getRawAssignID());
6448*0fca6ea1SDimitry Andric     visitMDNode(*cast<DIAssignID>(DVR.getRawAssignID()),
6449*0fca6ea1SDimitry Andric                 AreDebugLocsAllowed::No);
6450*0fca6ea1SDimitry Andric 
6451*0fca6ea1SDimitry Andric     const auto *RawAddr = DVR.getRawAddress();
6452*0fca6ea1SDimitry Andric     // Similarly to the location above, the address for an assign
6453*0fca6ea1SDimitry Andric     // DbgVariableRecord must be a ValueAsMetadata or an empty MDNode, which
6454*0fca6ea1SDimitry Andric     // represents an undef address.
6455*0fca6ea1SDimitry Andric     CheckDI(
6456*0fca6ea1SDimitry Andric         isa<ValueAsMetadata>(RawAddr) ||
6457*0fca6ea1SDimitry Andric             (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
6458*0fca6ea1SDimitry Andric         "invalid #dbg_assign address", &DVR, DVR.getRawAddress());
6459*0fca6ea1SDimitry Andric     if (auto *VAM = dyn_cast<ValueAsMetadata>(RawAddr))
6460*0fca6ea1SDimitry Andric       visitValueAsMetadata(*VAM, F);
6461*0fca6ea1SDimitry Andric 
6462*0fca6ea1SDimitry Andric     CheckDI(isa_and_nonnull<DIExpression>(DVR.getRawAddressExpression()),
6463*0fca6ea1SDimitry Andric             "invalid #dbg_assign address expression", &DVR,
6464*0fca6ea1SDimitry Andric             DVR.getRawAddressExpression());
6465*0fca6ea1SDimitry Andric     visitMDNode(*DVR.getAddressExpression(), AreDebugLocsAllowed::No);
6466*0fca6ea1SDimitry Andric 
6467*0fca6ea1SDimitry Andric     // All of the linked instructions should be in the same function as DVR.
6468*0fca6ea1SDimitry Andric     for (Instruction *I : at::getAssignmentInsts(&DVR))
6469*0fca6ea1SDimitry Andric       CheckDI(DVR.getFunction() == I->getFunction(),
6470*0fca6ea1SDimitry Andric               "inst not in same function as #dbg_assign", I, &DVR);
6471*0fca6ea1SDimitry Andric   }
6472*0fca6ea1SDimitry Andric 
6473*0fca6ea1SDimitry Andric   // This check is redundant with one in visitLocalVariable().
6474*0fca6ea1SDimitry Andric   DILocalVariable *Var = DVR.getVariable();
6475*0fca6ea1SDimitry Andric   CheckDI(isType(Var->getRawType()), "invalid type ref", Var,
6476*0fca6ea1SDimitry Andric           Var->getRawType());
6477*0fca6ea1SDimitry Andric 
6478*0fca6ea1SDimitry Andric   auto *DLNode = DVR.getDebugLoc().getAsMDNode();
6479*0fca6ea1SDimitry Andric   CheckDI(isa_and_nonnull<DILocation>(DLNode), "invalid #dbg record DILocation",
6480*0fca6ea1SDimitry Andric           &DVR, DLNode);
6481*0fca6ea1SDimitry Andric   DILocation *Loc = DVR.getDebugLoc();
6482*0fca6ea1SDimitry Andric 
6483*0fca6ea1SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
6484*0fca6ea1SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
6485*0fca6ea1SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
6486*0fca6ea1SDimitry Andric   if (!VarSP || !LocSP)
6487*0fca6ea1SDimitry Andric     return; // Broken scope chains are checked elsewhere.
6488*0fca6ea1SDimitry Andric 
6489*0fca6ea1SDimitry Andric   CheckDI(VarSP == LocSP,
6490*0fca6ea1SDimitry Andric           "mismatched subprogram between #dbg record variable and DILocation",
6491*0fca6ea1SDimitry Andric           &DVR, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
6492*0fca6ea1SDimitry Andric           Loc->getScope()->getSubprogram());
6493*0fca6ea1SDimitry Andric 
6494*0fca6ea1SDimitry Andric   verifyFnArgs(DVR);
6495*0fca6ea1SDimitry Andric }
6496*0fca6ea1SDimitry Andric 
visitVPIntrinsic(VPIntrinsic & VPI)649781ad6265SDimitry Andric void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
649881ad6265SDimitry Andric   if (auto *VPCast = dyn_cast<VPCastIntrinsic>(&VPI)) {
649981ad6265SDimitry Andric     auto *RetTy = cast<VectorType>(VPCast->getType());
650081ad6265SDimitry Andric     auto *ValTy = cast<VectorType>(VPCast->getOperand(0)->getType());
650181ad6265SDimitry Andric     Check(RetTy->getElementCount() == ValTy->getElementCount(),
650281ad6265SDimitry Andric           "VP cast intrinsic first argument and result vector lengths must be "
650381ad6265SDimitry Andric           "equal",
650481ad6265SDimitry Andric           *VPCast);
650581ad6265SDimitry Andric 
650681ad6265SDimitry Andric     switch (VPCast->getIntrinsicID()) {
650781ad6265SDimitry Andric     default:
650881ad6265SDimitry Andric       llvm_unreachable("Unknown VP cast intrinsic");
650981ad6265SDimitry Andric     case Intrinsic::vp_trunc:
651081ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
651181ad6265SDimitry Andric             "llvm.vp.trunc intrinsic first argument and result element type "
651281ad6265SDimitry Andric             "must be integer",
651381ad6265SDimitry Andric             *VPCast);
651481ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
651581ad6265SDimitry Andric             "llvm.vp.trunc intrinsic the bit size of first argument must be "
651681ad6265SDimitry Andric             "larger than the bit size of the return type",
651781ad6265SDimitry Andric             *VPCast);
651881ad6265SDimitry Andric       break;
651981ad6265SDimitry Andric     case Intrinsic::vp_zext:
652081ad6265SDimitry Andric     case Intrinsic::vp_sext:
652181ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isIntOrIntVectorTy(),
652281ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
652381ad6265SDimitry Andric             "element type must be integer",
652481ad6265SDimitry Andric             *VPCast);
652581ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
652681ad6265SDimitry Andric             "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
652781ad6265SDimitry Andric             "argument must be smaller than the bit size of the return type",
652881ad6265SDimitry Andric             *VPCast);
652981ad6265SDimitry Andric       break;
653081ad6265SDimitry Andric     case Intrinsic::vp_fptoui:
653181ad6265SDimitry Andric     case Intrinsic::vp_fptosi:
6532*0fca6ea1SDimitry Andric     case Intrinsic::vp_lrint:
6533*0fca6ea1SDimitry Andric     case Intrinsic::vp_llrint:
653481ad6265SDimitry Andric       Check(
653581ad6265SDimitry Andric           RetTy->isIntOrIntVectorTy() && ValTy->isFPOrFPVectorTy(),
6536*0fca6ea1SDimitry Andric           "llvm.vp.fptoui, llvm.vp.fptosi, llvm.vp.lrint or llvm.vp.llrint" "intrinsic first argument element "
653781ad6265SDimitry Andric           "type must be floating-point and result element type must be integer",
653881ad6265SDimitry Andric           *VPCast);
653981ad6265SDimitry Andric       break;
654081ad6265SDimitry Andric     case Intrinsic::vp_uitofp:
654181ad6265SDimitry Andric     case Intrinsic::vp_sitofp:
654281ad6265SDimitry Andric       Check(
654381ad6265SDimitry Andric           RetTy->isFPOrFPVectorTy() && ValTy->isIntOrIntVectorTy(),
654481ad6265SDimitry Andric           "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
654581ad6265SDimitry Andric           "type must be integer and result element type must be floating-point",
654681ad6265SDimitry Andric           *VPCast);
654781ad6265SDimitry Andric       break;
654881ad6265SDimitry Andric     case Intrinsic::vp_fptrunc:
654981ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
655081ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic first argument and result element type "
655181ad6265SDimitry Andric             "must be floating-point",
655281ad6265SDimitry Andric             *VPCast);
655381ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() < ValTy->getScalarSizeInBits(),
655481ad6265SDimitry Andric             "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
655581ad6265SDimitry Andric             "larger than the bit size of the return type",
655681ad6265SDimitry Andric             *VPCast);
655781ad6265SDimitry Andric       break;
655881ad6265SDimitry Andric     case Intrinsic::vp_fpext:
655981ad6265SDimitry Andric       Check(RetTy->isFPOrFPVectorTy() && ValTy->isFPOrFPVectorTy(),
656081ad6265SDimitry Andric             "llvm.vp.fpext intrinsic first argument and result element type "
656181ad6265SDimitry Andric             "must be floating-point",
656281ad6265SDimitry Andric             *VPCast);
656381ad6265SDimitry Andric       Check(RetTy->getScalarSizeInBits() > ValTy->getScalarSizeInBits(),
656481ad6265SDimitry Andric             "llvm.vp.fpext intrinsic the bit size of first argument must be "
656581ad6265SDimitry Andric             "smaller than the bit size of the return type",
656681ad6265SDimitry Andric             *VPCast);
656781ad6265SDimitry Andric       break;
656881ad6265SDimitry Andric     case Intrinsic::vp_ptrtoint:
656981ad6265SDimitry Andric       Check(RetTy->isIntOrIntVectorTy() && ValTy->isPtrOrPtrVectorTy(),
657081ad6265SDimitry Andric             "llvm.vp.ptrtoint intrinsic first argument element type must be "
657181ad6265SDimitry Andric             "pointer and result element type must be integer",
657281ad6265SDimitry Andric             *VPCast);
657381ad6265SDimitry Andric       break;
657481ad6265SDimitry Andric     case Intrinsic::vp_inttoptr:
657581ad6265SDimitry Andric       Check(RetTy->isPtrOrPtrVectorTy() && ValTy->isIntOrIntVectorTy(),
657681ad6265SDimitry Andric             "llvm.vp.inttoptr intrinsic first argument element type must be "
657781ad6265SDimitry Andric             "integer and result element type must be pointer",
657881ad6265SDimitry Andric             *VPCast);
657981ad6265SDimitry Andric       break;
658081ad6265SDimitry Andric     }
658181ad6265SDimitry Andric   }
658281ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_fcmp) {
658381ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
658481ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
658581ad6265SDimitry Andric           "invalid predicate for VP FP comparison intrinsic", &VPI);
658681ad6265SDimitry Andric   }
658781ad6265SDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_icmp) {
658881ad6265SDimitry Andric     auto Pred = cast<VPCmpIntrinsic>(&VPI)->getPredicate();
658981ad6265SDimitry Andric     Check(CmpInst::isIntPredicate(Pred),
659081ad6265SDimitry Andric           "invalid predicate for VP integer comparison intrinsic", &VPI);
659181ad6265SDimitry Andric   }
65925f757f3fSDimitry Andric   if (VPI.getIntrinsicID() == Intrinsic::vp_is_fpclass) {
65935f757f3fSDimitry Andric     auto TestMask = cast<ConstantInt>(VPI.getOperand(1));
65945f757f3fSDimitry Andric     Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
65955f757f3fSDimitry Andric           "unsupported bits for llvm.vp.is.fpclass test mask");
65965f757f3fSDimitry Andric   }
659781ad6265SDimitry Andric }
659881ad6265SDimitry Andric 
visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic & FPI)65990b57cec5SDimitry Andric void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
6600*0fca6ea1SDimitry Andric   unsigned NumOperands = FPI.getNonMetadataArgCount();
6601*0fca6ea1SDimitry Andric   bool HasRoundingMD =
6602*0fca6ea1SDimitry Andric       Intrinsic::hasConstrainedFPRoundingModeOperand(FPI.getIntrinsicID());
6603*0fca6ea1SDimitry Andric 
6604*0fca6ea1SDimitry Andric   // Add the expected number of metadata operands.
6605480093f4SDimitry Andric   NumOperands += (1 + HasRoundingMD);
6606*0fca6ea1SDimitry Andric 
6607480093f4SDimitry Andric   // Compare intrinsics carry an extra predicate metadata operand.
6608480093f4SDimitry Andric   if (isa<ConstrainedFPCmpIntrinsic>(FPI))
6609480093f4SDimitry Andric     NumOperands += 1;
661081ad6265SDimitry Andric   Check((FPI.arg_size() == NumOperands),
6611480093f4SDimitry Andric         "invalid arguments for constrained FP intrinsic", &FPI);
66120b57cec5SDimitry Andric 
6613480093f4SDimitry Andric   switch (FPI.getIntrinsicID()) {
66148bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lrint:
66158bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llrint: {
66168bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
66178bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
661881ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
66198bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
66208bcb0991SDimitry Andric     break;
6621*0fca6ea1SDimitry Andric   }
66228bcb0991SDimitry Andric 
66238bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_lround:
66248bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_llround: {
66258bcb0991SDimitry Andric     Type *ValTy = FPI.getArgOperand(0)->getType();
66268bcb0991SDimitry Andric     Type *ResultTy = FPI.getType();
662781ad6265SDimitry Andric     Check(!ValTy->isVectorTy() && !ResultTy->isVectorTy(),
66288bcb0991SDimitry Andric           "Intrinsic does not support vectors", &FPI);
66298bcb0991SDimitry Andric     break;
66308bcb0991SDimitry Andric   }
66318bcb0991SDimitry Andric 
6632480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmp:
6633480093f4SDimitry Andric   case Intrinsic::experimental_constrained_fcmps: {
6634480093f4SDimitry Andric     auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
663581ad6265SDimitry Andric     Check(CmpInst::isFPPredicate(Pred),
6636480093f4SDimitry Andric           "invalid predicate for constrained FP comparison intrinsic", &FPI);
66370b57cec5SDimitry Andric     break;
6638480093f4SDimitry Andric   }
66390b57cec5SDimitry Andric 
66408bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptosi:
66418bcb0991SDimitry Andric   case Intrinsic::experimental_constrained_fptoui: {
66428bcb0991SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
664306c3fb27SDimitry Andric     ElementCount SrcEC;
664481ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
66458bcb0991SDimitry Andric           "Intrinsic first argument must be floating point", &FPI);
66468bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
664706c3fb27SDimitry Andric       SrcEC = cast<VectorType>(OperandT)->getElementCount();
66488bcb0991SDimitry Andric     }
66498bcb0991SDimitry Andric 
66508bcb0991SDimitry Andric     Operand = &FPI;
665106c3fb27SDimitry Andric     Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
66528bcb0991SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
665381ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
66548bcb0991SDimitry Andric           "Intrinsic result must be an integer", &FPI);
66558bcb0991SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
665606c3fb27SDimitry Andric       Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
66578bcb0991SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
66588bcb0991SDimitry Andric             &FPI);
66598bcb0991SDimitry Andric     }
66608bcb0991SDimitry Andric     break;
6661*0fca6ea1SDimitry Andric   }
66628bcb0991SDimitry Andric 
6663480093f4SDimitry Andric   case Intrinsic::experimental_constrained_sitofp:
6664480093f4SDimitry Andric   case Intrinsic::experimental_constrained_uitofp: {
6665480093f4SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
666606c3fb27SDimitry Andric     ElementCount SrcEC;
666781ad6265SDimitry Andric     Check(Operand->getType()->isIntOrIntVectorTy(),
6668480093f4SDimitry Andric           "Intrinsic first argument must be integer", &FPI);
6669480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
667006c3fb27SDimitry Andric       SrcEC = cast<VectorType>(OperandT)->getElementCount();
6671480093f4SDimitry Andric     }
6672480093f4SDimitry Andric 
6673480093f4SDimitry Andric     Operand = &FPI;
667406c3fb27SDimitry Andric     Check(SrcEC.isNonZero() == Operand->getType()->isVectorTy(),
6675480093f4SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
667681ad6265SDimitry Andric     Check(Operand->getType()->isFPOrFPVectorTy(),
6677480093f4SDimitry Andric           "Intrinsic result must be a floating point", &FPI);
6678480093f4SDimitry Andric     if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) {
667906c3fb27SDimitry Andric       Check(SrcEC == cast<VectorType>(OperandT)->getElementCount(),
6680480093f4SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
6681480093f4SDimitry Andric             &FPI);
6682480093f4SDimitry Andric     }
6683*0fca6ea1SDimitry Andric     break;
6684*0fca6ea1SDimitry Andric   }
6685480093f4SDimitry Andric 
66860b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fptrunc:
66870b57cec5SDimitry Andric   case Intrinsic::experimental_constrained_fpext: {
66880b57cec5SDimitry Andric     Value *Operand = FPI.getArgOperand(0);
66890b57cec5SDimitry Andric     Type *OperandTy = Operand->getType();
66900b57cec5SDimitry Andric     Value *Result = &FPI;
66910b57cec5SDimitry Andric     Type *ResultTy = Result->getType();
669281ad6265SDimitry Andric     Check(OperandTy->isFPOrFPVectorTy(),
66930b57cec5SDimitry Andric           "Intrinsic first argument must be FP or FP vector", &FPI);
669481ad6265SDimitry Andric     Check(ResultTy->isFPOrFPVectorTy(),
66950b57cec5SDimitry Andric           "Intrinsic result must be FP or FP vector", &FPI);
669681ad6265SDimitry Andric     Check(OperandTy->isVectorTy() == ResultTy->isVectorTy(),
66970b57cec5SDimitry Andric           "Intrinsic first argument and result disagree on vector use", &FPI);
66980b57cec5SDimitry Andric     if (OperandTy->isVectorTy()) {
669906c3fb27SDimitry Andric       Check(cast<VectorType>(OperandTy)->getElementCount() ==
670006c3fb27SDimitry Andric                 cast<VectorType>(ResultTy)->getElementCount(),
67010b57cec5SDimitry Andric             "Intrinsic first argument and result vector lengths must be equal",
67020b57cec5SDimitry Andric             &FPI);
67030b57cec5SDimitry Andric     }
67040b57cec5SDimitry Andric     if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
670581ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
67060b57cec5SDimitry Andric             "Intrinsic first argument's type must be larger than result type",
67070b57cec5SDimitry Andric             &FPI);
67080b57cec5SDimitry Andric     } else {
670981ad6265SDimitry Andric       Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
67100b57cec5SDimitry Andric             "Intrinsic first argument's type must be smaller than result type",
67110b57cec5SDimitry Andric             &FPI);
67120b57cec5SDimitry Andric     }
67130b57cec5SDimitry Andric     break;
6714*0fca6ea1SDimitry Andric   }
67150b57cec5SDimitry Andric 
67160b57cec5SDimitry Andric   default:
6717480093f4SDimitry Andric     break;
67180b57cec5SDimitry Andric   }
67190b57cec5SDimitry Andric 
67200b57cec5SDimitry Andric   // If a non-metadata argument is passed in a metadata slot then the
67210b57cec5SDimitry Andric   // error will be caught earlier when the incorrect argument doesn't
67220b57cec5SDimitry Andric   // match the specification in the intrinsic call table. Thus, no
67230b57cec5SDimitry Andric   // argument type check is needed here.
67240b57cec5SDimitry Andric 
672581ad6265SDimitry Andric   Check(FPI.getExceptionBehavior().has_value(),
67260b57cec5SDimitry Andric         "invalid exception behavior argument", &FPI);
67270b57cec5SDimitry Andric   if (HasRoundingMD) {
672881ad6265SDimitry Andric     Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
672981ad6265SDimitry Andric           &FPI);
67300b57cec5SDimitry Andric   }
67310b57cec5SDimitry Andric }
67320b57cec5SDimitry Andric 
visitDbgIntrinsic(StringRef Kind,DbgVariableIntrinsic & DII)67330b57cec5SDimitry Andric void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) {
6734fe6060f1SDimitry Andric   auto *MD = DII.getRawLocation();
673581ad6265SDimitry Andric   CheckDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
67360b57cec5SDimitry Andric               (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
67370b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
673881ad6265SDimitry Andric   CheckDI(isa<DILocalVariable>(DII.getRawVariable()),
67390b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
67400b57cec5SDimitry Andric           DII.getRawVariable());
674181ad6265SDimitry Andric   CheckDI(isa<DIExpression>(DII.getRawExpression()),
67420b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
67430b57cec5SDimitry Andric           DII.getRawExpression());
67440b57cec5SDimitry Andric 
6745bdd1243dSDimitry Andric   if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&DII)) {
6746bdd1243dSDimitry Andric     CheckDI(isa<DIAssignID>(DAI->getRawAssignID()),
6747bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic DIAssignID", &DII,
6748bdd1243dSDimitry Andric             DAI->getRawAssignID());
6749bdd1243dSDimitry Andric     const auto *RawAddr = DAI->getRawAddress();
6750bdd1243dSDimitry Andric     CheckDI(
6751bdd1243dSDimitry Andric         isa<ValueAsMetadata>(RawAddr) ||
6752bdd1243dSDimitry Andric             (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
6753bdd1243dSDimitry Andric         "invalid llvm.dbg.assign intrinsic address", &DII,
6754bdd1243dSDimitry Andric         DAI->getRawAddress());
6755bdd1243dSDimitry Andric     CheckDI(isa<DIExpression>(DAI->getRawAddressExpression()),
6756bdd1243dSDimitry Andric             "invalid llvm.dbg.assign intrinsic address expression", &DII,
6757bdd1243dSDimitry Andric             DAI->getRawAddressExpression());
6758bdd1243dSDimitry Andric     // All of the linked instructions should be in the same function as DII.
6759bdd1243dSDimitry Andric     for (Instruction *I : at::getAssignmentInsts(DAI))
6760bdd1243dSDimitry Andric       CheckDI(DAI->getFunction() == I->getFunction(),
6761bdd1243dSDimitry Andric               "inst not in same function as dbg.assign", I, DAI);
6762bdd1243dSDimitry Andric   }
6763bdd1243dSDimitry Andric 
67640b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
67650b57cec5SDimitry Andric   if (MDNode *N = DII.getDebugLoc().getAsMDNode())
67660b57cec5SDimitry Andric     if (!isa<DILocation>(N))
67670b57cec5SDimitry Andric       return;
67680b57cec5SDimitry Andric 
67690b57cec5SDimitry Andric   BasicBlock *BB = DII.getParent();
67700b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
67710b57cec5SDimitry Andric 
67720b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
67730b57cec5SDimitry Andric   DILocalVariable *Var = DII.getVariable();
67740b57cec5SDimitry Andric   DILocation *Loc = DII.getDebugLoc();
677581ad6265SDimitry Andric   CheckDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
67760b57cec5SDimitry Andric           &DII, BB, F);
67770b57cec5SDimitry Andric 
67780b57cec5SDimitry Andric   DISubprogram *VarSP = getSubprogram(Var->getRawScope());
67790b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
67800b57cec5SDimitry Andric   if (!VarSP || !LocSP)
67810b57cec5SDimitry Andric     return; // Broken scope chains are checked elsewhere.
67820b57cec5SDimitry Andric 
678381ad6265SDimitry Andric   CheckDI(VarSP == LocSP,
678481ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
67850b57cec5SDimitry Andric               " variable and !dbg attachment",
67860b57cec5SDimitry Andric           &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
67870b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
67880b57cec5SDimitry Andric 
67890b57cec5SDimitry Andric   // This check is redundant with one in visitLocalVariable().
679081ad6265SDimitry Andric   CheckDI(isType(Var->getRawType()), "invalid type ref", Var,
67910b57cec5SDimitry Andric           Var->getRawType());
67920b57cec5SDimitry Andric   verifyFnArgs(DII);
67930b57cec5SDimitry Andric }
67940b57cec5SDimitry Andric 
visitDbgLabelIntrinsic(StringRef Kind,DbgLabelInst & DLI)67950b57cec5SDimitry Andric void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) {
679681ad6265SDimitry Andric   CheckDI(isa<DILabel>(DLI.getRawLabel()),
67970b57cec5SDimitry Andric           "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI,
67980b57cec5SDimitry Andric           DLI.getRawLabel());
67990b57cec5SDimitry Andric 
68000b57cec5SDimitry Andric   // Ignore broken !dbg attachments; they're checked elsewhere.
68010b57cec5SDimitry Andric   if (MDNode *N = DLI.getDebugLoc().getAsMDNode())
68020b57cec5SDimitry Andric     if (!isa<DILocation>(N))
68030b57cec5SDimitry Andric       return;
68040b57cec5SDimitry Andric 
68050b57cec5SDimitry Andric   BasicBlock *BB = DLI.getParent();
68060b57cec5SDimitry Andric   Function *F = BB ? BB->getParent() : nullptr;
68070b57cec5SDimitry Andric 
68080b57cec5SDimitry Andric   // The scopes for variables and !dbg attachments must agree.
68090b57cec5SDimitry Andric   DILabel *Label = DLI.getLabel();
68100b57cec5SDimitry Andric   DILocation *Loc = DLI.getDebugLoc();
681181ad6265SDimitry Andric   Check(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", &DLI,
681281ad6265SDimitry Andric         BB, F);
68130b57cec5SDimitry Andric 
68140b57cec5SDimitry Andric   DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
68150b57cec5SDimitry Andric   DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
68160b57cec5SDimitry Andric   if (!LabelSP || !LocSP)
68170b57cec5SDimitry Andric     return;
68180b57cec5SDimitry Andric 
681981ad6265SDimitry Andric   CheckDI(LabelSP == LocSP,
682081ad6265SDimitry Andric           "mismatched subprogram between llvm.dbg." + Kind +
68210b57cec5SDimitry Andric               " label and !dbg attachment",
68220b57cec5SDimitry Andric           &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
68230b57cec5SDimitry Andric           Loc->getScope()->getSubprogram());
68240b57cec5SDimitry Andric }
68250b57cec5SDimitry Andric 
verifyFragmentExpression(const DbgVariableIntrinsic & I)68260b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) {
68270b57cec5SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable());
68280b57cec5SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
68290b57cec5SDimitry Andric 
68300b57cec5SDimitry Andric   // We don't know whether this intrinsic verified correctly.
68310b57cec5SDimitry Andric   if (!V || !E || !E->isValid())
68320b57cec5SDimitry Andric     return;
68330b57cec5SDimitry Andric 
68340b57cec5SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
68350b57cec5SDimitry Andric   auto Fragment = E->getFragmentInfo();
68360b57cec5SDimitry Andric   if (!Fragment)
68370b57cec5SDimitry Andric     return;
68380b57cec5SDimitry Andric 
68390b57cec5SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
68400b57cec5SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
68410b57cec5SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
68420b57cec5SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
68430b57cec5SDimitry Andric   // variable and this check fails.
68440b57cec5SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
68450b57cec5SDimitry Andric   if (V->isArtificial())
68460b57cec5SDimitry Andric     return;
68470b57cec5SDimitry Andric 
68480b57cec5SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &I);
68490b57cec5SDimitry Andric }
verifyFragmentExpression(const DbgVariableRecord & DVR)6850*0fca6ea1SDimitry Andric void Verifier::verifyFragmentExpression(const DbgVariableRecord &DVR) {
6851*0fca6ea1SDimitry Andric   DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(DVR.getRawVariable());
6852*0fca6ea1SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
6853*0fca6ea1SDimitry Andric 
6854*0fca6ea1SDimitry Andric   // We don't know whether this intrinsic verified correctly.
6855*0fca6ea1SDimitry Andric   if (!V || !E || !E->isValid())
6856*0fca6ea1SDimitry Andric     return;
6857*0fca6ea1SDimitry Andric 
6858*0fca6ea1SDimitry Andric   // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
6859*0fca6ea1SDimitry Andric   auto Fragment = E->getFragmentInfo();
6860*0fca6ea1SDimitry Andric   if (!Fragment)
6861*0fca6ea1SDimitry Andric     return;
6862*0fca6ea1SDimitry Andric 
6863*0fca6ea1SDimitry Andric   // The frontend helps out GDB by emitting the members of local anonymous
6864*0fca6ea1SDimitry Andric   // unions as artificial local variables with shared storage. When SROA splits
6865*0fca6ea1SDimitry Andric   // the storage for artificial local variables that are smaller than the entire
6866*0fca6ea1SDimitry Andric   // union, the overhang piece will be outside of the allotted space for the
6867*0fca6ea1SDimitry Andric   // variable and this check fails.
6868*0fca6ea1SDimitry Andric   // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
6869*0fca6ea1SDimitry Andric   if (V->isArtificial())
6870*0fca6ea1SDimitry Andric     return;
6871*0fca6ea1SDimitry Andric 
6872*0fca6ea1SDimitry Andric   verifyFragmentExpression(*V, *Fragment, &DVR);
6873*0fca6ea1SDimitry Andric }
68740b57cec5SDimitry Andric 
68750b57cec5SDimitry Andric template <typename ValueOrMetadata>
verifyFragmentExpression(const DIVariable & V,DIExpression::FragmentInfo Fragment,ValueOrMetadata * Desc)68760b57cec5SDimitry Andric void Verifier::verifyFragmentExpression(const DIVariable &V,
68770b57cec5SDimitry Andric                                         DIExpression::FragmentInfo Fragment,
68780b57cec5SDimitry Andric                                         ValueOrMetadata *Desc) {
68790b57cec5SDimitry Andric   // If there's no size, the type is broken, but that should be checked
68800b57cec5SDimitry Andric   // elsewhere.
68810b57cec5SDimitry Andric   auto VarSize = V.getSizeInBits();
68820b57cec5SDimitry Andric   if (!VarSize)
68830b57cec5SDimitry Andric     return;
68840b57cec5SDimitry Andric 
68850b57cec5SDimitry Andric   unsigned FragSize = Fragment.SizeInBits;
68860b57cec5SDimitry Andric   unsigned FragOffset = Fragment.OffsetInBits;
688781ad6265SDimitry Andric   CheckDI(FragSize + FragOffset <= *VarSize,
68880b57cec5SDimitry Andric           "fragment is larger than or outside of variable", Desc, &V);
688981ad6265SDimitry Andric   CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
68900b57cec5SDimitry Andric }
68910b57cec5SDimitry Andric 
verifyFnArgs(const DbgVariableIntrinsic & I)68920b57cec5SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) {
68930b57cec5SDimitry Andric   // This function does not take the scope of noninlined function arguments into
68940b57cec5SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
68950b57cec5SDimitry Andric   // contain inlined debug intrinsics.
68960b57cec5SDimitry Andric   if (!HasDebugInfo)
68970b57cec5SDimitry Andric     return;
68980b57cec5SDimitry Andric 
68990b57cec5SDimitry Andric   // For performance reasons only check non-inlined ones.
69000b57cec5SDimitry Andric   if (I.getDebugLoc()->getInlinedAt())
69010b57cec5SDimitry Andric     return;
69020b57cec5SDimitry Andric 
69030b57cec5SDimitry Andric   DILocalVariable *Var = I.getVariable();
690481ad6265SDimitry Andric   CheckDI(Var, "dbg intrinsic without variable");
69050b57cec5SDimitry Andric 
69060b57cec5SDimitry Andric   unsigned ArgNo = Var->getArg();
69070b57cec5SDimitry Andric   if (!ArgNo)
69080b57cec5SDimitry Andric     return;
69090b57cec5SDimitry Andric 
69100b57cec5SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
69110b57cec5SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
69120b57cec5SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
69130b57cec5SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
69140b57cec5SDimitry Andric 
69150b57cec5SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
69160b57cec5SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
691781ad6265SDimitry Andric   CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
69180b57cec5SDimitry Andric           Prev, Var);
69190b57cec5SDimitry Andric }
verifyFnArgs(const DbgVariableRecord & DVR)6920*0fca6ea1SDimitry Andric void Verifier::verifyFnArgs(const DbgVariableRecord &DVR) {
6921*0fca6ea1SDimitry Andric   // This function does not take the scope of noninlined function arguments into
6922*0fca6ea1SDimitry Andric   // account. Don't run it if current function is nodebug, because it may
6923*0fca6ea1SDimitry Andric   // contain inlined debug intrinsics.
6924*0fca6ea1SDimitry Andric   if (!HasDebugInfo)
6925*0fca6ea1SDimitry Andric     return;
6926*0fca6ea1SDimitry Andric 
6927*0fca6ea1SDimitry Andric   // For performance reasons only check non-inlined ones.
6928*0fca6ea1SDimitry Andric   if (DVR.getDebugLoc()->getInlinedAt())
6929*0fca6ea1SDimitry Andric     return;
6930*0fca6ea1SDimitry Andric 
6931*0fca6ea1SDimitry Andric   DILocalVariable *Var = DVR.getVariable();
6932*0fca6ea1SDimitry Andric   CheckDI(Var, "#dbg record without variable");
6933*0fca6ea1SDimitry Andric 
6934*0fca6ea1SDimitry Andric   unsigned ArgNo = Var->getArg();
6935*0fca6ea1SDimitry Andric   if (!ArgNo)
6936*0fca6ea1SDimitry Andric     return;
6937*0fca6ea1SDimitry Andric 
6938*0fca6ea1SDimitry Andric   // Verify there are no duplicate function argument debug info entries.
6939*0fca6ea1SDimitry Andric   // These will cause hard-to-debug assertions in the DWARF backend.
6940*0fca6ea1SDimitry Andric   if (DebugFnArgs.size() < ArgNo)
6941*0fca6ea1SDimitry Andric     DebugFnArgs.resize(ArgNo, nullptr);
6942*0fca6ea1SDimitry Andric 
6943*0fca6ea1SDimitry Andric   auto *Prev = DebugFnArgs[ArgNo - 1];
6944*0fca6ea1SDimitry Andric   DebugFnArgs[ArgNo - 1] = Var;
6945*0fca6ea1SDimitry Andric   CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &DVR,
6946*0fca6ea1SDimitry Andric           Prev, Var);
6947*0fca6ea1SDimitry Andric }
69480b57cec5SDimitry Andric 
verifyNotEntryValue(const DbgVariableIntrinsic & I)69498bcb0991SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) {
69508bcb0991SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression());
69518bcb0991SDimitry Andric 
69528bcb0991SDimitry Andric   // We don't know whether this intrinsic verified correctly.
69538bcb0991SDimitry Andric   if (!E || !E->isValid())
69548bcb0991SDimitry Andric     return;
69558bcb0991SDimitry Andric 
69565f757f3fSDimitry Andric   if (isa<ValueAsMetadata>(I.getRawLocation())) {
69575f757f3fSDimitry Andric     Value *VarValue = I.getVariableLocationOp(0);
69585f757f3fSDimitry Andric     if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
69595f757f3fSDimitry Andric       return;
696006c3fb27SDimitry Andric     // We allow EntryValues for swift async arguments, as they have an
696106c3fb27SDimitry Andric     // ABI-guarantee to be turned into a specific register.
69625f757f3fSDimitry Andric     if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
696306c3fb27SDimitry Andric         ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
696406c3fb27SDimitry Andric       return;
69655f757f3fSDimitry Andric   }
696606c3fb27SDimitry Andric 
696706c3fb27SDimitry Andric   CheckDI(!E->isEntryValue(),
696806c3fb27SDimitry Andric           "Entry values are only allowed in MIR unless they target a "
696906c3fb27SDimitry Andric           "swiftasync Argument",
697006c3fb27SDimitry Andric           &I);
69718bcb0991SDimitry Andric }
verifyNotEntryValue(const DbgVariableRecord & DVR)6972*0fca6ea1SDimitry Andric void Verifier::verifyNotEntryValue(const DbgVariableRecord &DVR) {
6973*0fca6ea1SDimitry Andric   DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
6974*0fca6ea1SDimitry Andric 
6975*0fca6ea1SDimitry Andric   // We don't know whether this intrinsic verified correctly.
6976*0fca6ea1SDimitry Andric   if (!E || !E->isValid())
6977*0fca6ea1SDimitry Andric     return;
6978*0fca6ea1SDimitry Andric 
6979*0fca6ea1SDimitry Andric   if (isa<ValueAsMetadata>(DVR.getRawLocation())) {
6980*0fca6ea1SDimitry Andric     Value *VarValue = DVR.getVariableLocationOp(0);
6981*0fca6ea1SDimitry Andric     if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
6982*0fca6ea1SDimitry Andric       return;
6983*0fca6ea1SDimitry Andric     // We allow EntryValues for swift async arguments, as they have an
6984*0fca6ea1SDimitry Andric     // ABI-guarantee to be turned into a specific register.
6985*0fca6ea1SDimitry Andric     if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
6986*0fca6ea1SDimitry Andric         ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
6987*0fca6ea1SDimitry Andric       return;
6988*0fca6ea1SDimitry Andric   }
6989*0fca6ea1SDimitry Andric 
6990*0fca6ea1SDimitry Andric   CheckDI(!E->isEntryValue(),
6991*0fca6ea1SDimitry Andric           "Entry values are only allowed in MIR unless they target a "
6992*0fca6ea1SDimitry Andric           "swiftasync Argument",
6993*0fca6ea1SDimitry Andric           &DVR);
6994*0fca6ea1SDimitry Andric }
69958bcb0991SDimitry Andric 
verifyCompileUnits()69960b57cec5SDimitry Andric void Verifier::verifyCompileUnits() {
69970b57cec5SDimitry Andric   // When more than one Module is imported into the same context, such as during
69980b57cec5SDimitry Andric   // an LTO build before linking the modules, ODR type uniquing may cause types
69990b57cec5SDimitry Andric   // to point to a different CU. This check does not make sense in this case.
70000b57cec5SDimitry Andric   if (M.getContext().isODRUniquingDebugTypes())
70010b57cec5SDimitry Andric     return;
70020b57cec5SDimitry Andric   auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
70030b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 2> Listed;
70040b57cec5SDimitry Andric   if (CUs)
70050b57cec5SDimitry Andric     Listed.insert(CUs->op_begin(), CUs->op_end());
7006bdd1243dSDimitry Andric   for (const auto *CU : CUVisited)
700781ad6265SDimitry Andric     CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
70080b57cec5SDimitry Andric   CUVisited.clear();
70090b57cec5SDimitry Andric }
70100b57cec5SDimitry Andric 
verifyDeoptimizeCallingConvs()70110b57cec5SDimitry Andric void Verifier::verifyDeoptimizeCallingConvs() {
70120b57cec5SDimitry Andric   if (DeoptimizeDeclarations.empty())
70130b57cec5SDimitry Andric     return;
70140b57cec5SDimitry Andric 
70150b57cec5SDimitry Andric   const Function *First = DeoptimizeDeclarations[0];
7016bdd1243dSDimitry Andric   for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
701781ad6265SDimitry Andric     Check(First->getCallingConv() == F->getCallingConv(),
70180b57cec5SDimitry Andric           "All llvm.experimental.deoptimize declarations must have the same "
70190b57cec5SDimitry Andric           "calling convention",
70200b57cec5SDimitry Andric           First, F);
70210b57cec5SDimitry Andric   }
70220b57cec5SDimitry Andric }
70230b57cec5SDimitry Andric 
verifyAttachedCallBundle(const CallBase & Call,const OperandBundleUse & BU)7024349cc55cSDimitry Andric void Verifier::verifyAttachedCallBundle(const CallBase &Call,
7025349cc55cSDimitry Andric                                         const OperandBundleUse &BU) {
7026349cc55cSDimitry Andric   FunctionType *FTy = Call.getFunctionType();
7027349cc55cSDimitry Andric 
702881ad6265SDimitry Andric   Check((FTy->getReturnType()->isPointerTy() ||
7029349cc55cSDimitry Andric          (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
7030349cc55cSDimitry Andric         "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7031349cc55cSDimitry Andric         "function returning a pointer or a non-returning function that has a "
7032349cc55cSDimitry Andric         "void return type",
7033349cc55cSDimitry Andric         Call);
7034349cc55cSDimitry Andric 
703581ad6265SDimitry Andric   Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
70361fd87a68SDimitry Andric         "operand bundle \"clang.arc.attachedcall\" requires one function as "
70371fd87a68SDimitry Andric         "an argument",
7038349cc55cSDimitry Andric         Call);
7039349cc55cSDimitry Andric 
7040349cc55cSDimitry Andric   auto *Fn = cast<Function>(BU.Inputs.front());
7041349cc55cSDimitry Andric   Intrinsic::ID IID = Fn->getIntrinsicID();
7042349cc55cSDimitry Andric 
7043349cc55cSDimitry Andric   if (IID) {
704481ad6265SDimitry Andric     Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7045349cc55cSDimitry Andric            IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7046349cc55cSDimitry Andric           "invalid function argument", Call);
7047349cc55cSDimitry Andric   } else {
7048349cc55cSDimitry Andric     StringRef FnName = Fn->getName();
704981ad6265SDimitry Andric     Check((FnName == "objc_retainAutoreleasedReturnValue" ||
7050349cc55cSDimitry Andric            FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
7051349cc55cSDimitry Andric           "invalid function argument", Call);
7052349cc55cSDimitry Andric   }
7053349cc55cSDimitry Andric }
7054349cc55cSDimitry Andric 
verifyNoAliasScopeDecl()7055e8d8bef9SDimitry Andric void Verifier::verifyNoAliasScopeDecl() {
7056e8d8bef9SDimitry Andric   if (NoAliasScopeDecls.empty())
7057e8d8bef9SDimitry Andric     return;
7058e8d8bef9SDimitry Andric 
7059e8d8bef9SDimitry Andric   // only a single scope must be declared at a time.
7060e8d8bef9SDimitry Andric   for (auto *II : NoAliasScopeDecls) {
7061e8d8bef9SDimitry Andric     assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7062e8d8bef9SDimitry Andric            "Not a llvm.experimental.noalias.scope.decl ?");
7063e8d8bef9SDimitry Andric     const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
7064e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
706581ad6265SDimitry Andric     Check(ScopeListMV != nullptr,
7066e8d8bef9SDimitry Andric           "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7067e8d8bef9SDimitry Andric           "argument",
7068e8d8bef9SDimitry Andric           II);
7069e8d8bef9SDimitry Andric 
7070e8d8bef9SDimitry Andric     const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
707181ad6265SDimitry Andric     Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
707281ad6265SDimitry Andric     Check(ScopeListMD->getNumOperands() == 1,
7073e8d8bef9SDimitry Andric           "!id.scope.list must point to a list with a single scope", II);
7074349cc55cSDimitry Andric     visitAliasScopeListMetadata(ScopeListMD);
7075e8d8bef9SDimitry Andric   }
7076e8d8bef9SDimitry Andric 
7077e8d8bef9SDimitry Andric   // Only check the domination rule when requested. Once all passes have been
7078e8d8bef9SDimitry Andric   // adapted this option can go away.
7079e8d8bef9SDimitry Andric   if (!VerifyNoAliasScopeDomination)
7080e8d8bef9SDimitry Andric     return;
7081e8d8bef9SDimitry Andric 
7082e8d8bef9SDimitry Andric   // Now sort the intrinsics based on the scope MDNode so that declarations of
7083e8d8bef9SDimitry Andric   // the same scopes are next to each other.
7084e8d8bef9SDimitry Andric   auto GetScope = [](IntrinsicInst *II) {
7085e8d8bef9SDimitry Andric     const auto *ScopeListMV = cast<MetadataAsValue>(
7086e8d8bef9SDimitry Andric         II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
7087e8d8bef9SDimitry Andric     return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7088e8d8bef9SDimitry Andric   };
7089e8d8bef9SDimitry Andric 
7090e8d8bef9SDimitry Andric   // We are sorting on MDNode pointers here. For valid input IR this is ok.
7091e8d8bef9SDimitry Andric   // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
7092e8d8bef9SDimitry Andric   auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7093e8d8bef9SDimitry Andric     return GetScope(Lhs) < GetScope(Rhs);
7094e8d8bef9SDimitry Andric   };
7095e8d8bef9SDimitry Andric 
7096e8d8bef9SDimitry Andric   llvm::sort(NoAliasScopeDecls, Compare);
7097e8d8bef9SDimitry Andric 
7098e8d8bef9SDimitry Andric   // Go over the intrinsics and check that for the same scope, they are not
7099e8d8bef9SDimitry Andric   // dominating each other.
7100e8d8bef9SDimitry Andric   auto ItCurrent = NoAliasScopeDecls.begin();
7101e8d8bef9SDimitry Andric   while (ItCurrent != NoAliasScopeDecls.end()) {
7102e8d8bef9SDimitry Andric     auto CurScope = GetScope(*ItCurrent);
7103e8d8bef9SDimitry Andric     auto ItNext = ItCurrent;
7104e8d8bef9SDimitry Andric     do {
7105e8d8bef9SDimitry Andric       ++ItNext;
7106e8d8bef9SDimitry Andric     } while (ItNext != NoAliasScopeDecls.end() &&
7107e8d8bef9SDimitry Andric              GetScope(*ItNext) == CurScope);
7108e8d8bef9SDimitry Andric 
7109e8d8bef9SDimitry Andric     // [ItCurrent, ItNext) represents the declarations for the same scope.
7110e8d8bef9SDimitry Andric     // Ensure they are not dominating each other.. but only if it is not too
7111e8d8bef9SDimitry Andric     // expensive.
7112e8d8bef9SDimitry Andric     if (ItNext - ItCurrent < 32)
7113e8d8bef9SDimitry Andric       for (auto *I : llvm::make_range(ItCurrent, ItNext))
7114e8d8bef9SDimitry Andric         for (auto *J : llvm::make_range(ItCurrent, ItNext))
7115e8d8bef9SDimitry Andric           if (I != J)
711681ad6265SDimitry Andric             Check(!DT.dominates(I, J),
7117e8d8bef9SDimitry Andric                   "llvm.experimental.noalias.scope.decl dominates another one "
7118e8d8bef9SDimitry Andric                   "with the same scope",
7119e8d8bef9SDimitry Andric                   I);
7120e8d8bef9SDimitry Andric     ItCurrent = ItNext;
7121e8d8bef9SDimitry Andric   }
7122e8d8bef9SDimitry Andric }
7123e8d8bef9SDimitry Andric 
71240b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
71250b57cec5SDimitry Andric //  Implement the public interfaces to this file...
71260b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
71270b57cec5SDimitry Andric 
verifyFunction(const Function & f,raw_ostream * OS)71280b57cec5SDimitry Andric bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
71290b57cec5SDimitry Andric   Function &F = const_cast<Function &>(f);
71300b57cec5SDimitry Andric 
71310b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
71320b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
71330b57cec5SDimitry Andric 
71340b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
71350b57cec5SDimitry Andric   // expect of a function called "verify".
71360b57cec5SDimitry Andric   return !V.verify(F);
71370b57cec5SDimitry Andric }
71380b57cec5SDimitry Andric 
verifyModule(const Module & M,raw_ostream * OS,bool * BrokenDebugInfo)71390b57cec5SDimitry Andric bool llvm::verifyModule(const Module &M, raw_ostream *OS,
71400b57cec5SDimitry Andric                         bool *BrokenDebugInfo) {
71410b57cec5SDimitry Andric   // Don't use a raw_null_ostream.  Printing IR is expensive.
71420b57cec5SDimitry Andric   Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
71430b57cec5SDimitry Andric 
71440b57cec5SDimitry Andric   bool Broken = false;
71450b57cec5SDimitry Andric   for (const Function &F : M)
71460b57cec5SDimitry Andric     Broken |= !V.verify(F);
71470b57cec5SDimitry Andric 
71480b57cec5SDimitry Andric   Broken |= !V.verify();
71490b57cec5SDimitry Andric   if (BrokenDebugInfo)
71500b57cec5SDimitry Andric     *BrokenDebugInfo = V.hasBrokenDebugInfo();
71510b57cec5SDimitry Andric   // Note that this function's return value is inverted from what you would
71520b57cec5SDimitry Andric   // expect of a function called "verify".
71530b57cec5SDimitry Andric   return Broken;
71540b57cec5SDimitry Andric }
71550b57cec5SDimitry Andric 
71560b57cec5SDimitry Andric namespace {
71570b57cec5SDimitry Andric 
71580b57cec5SDimitry Andric struct VerifierLegacyPass : public FunctionPass {
71590b57cec5SDimitry Andric   static char ID;
71600b57cec5SDimitry Andric 
71610b57cec5SDimitry Andric   std::unique_ptr<Verifier> V;
71620b57cec5SDimitry Andric   bool FatalErrors = true;
71630b57cec5SDimitry Andric 
VerifierLegacyPass__anon93d097f61311::VerifierLegacyPass71640b57cec5SDimitry Andric   VerifierLegacyPass() : FunctionPass(ID) {
71650b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
71660b57cec5SDimitry Andric   }
VerifierLegacyPass__anon93d097f61311::VerifierLegacyPass71670b57cec5SDimitry Andric   explicit VerifierLegacyPass(bool FatalErrors)
71680b57cec5SDimitry Andric       : FunctionPass(ID),
71690b57cec5SDimitry Andric         FatalErrors(FatalErrors) {
71700b57cec5SDimitry Andric     initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
71710b57cec5SDimitry Andric   }
71720b57cec5SDimitry Andric 
doInitialization__anon93d097f61311::VerifierLegacyPass71730b57cec5SDimitry Andric   bool doInitialization(Module &M) override {
71748bcb0991SDimitry Andric     V = std::make_unique<Verifier>(
71750b57cec5SDimitry Andric         &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
71760b57cec5SDimitry Andric     return false;
71770b57cec5SDimitry Andric   }
71780b57cec5SDimitry Andric 
runOnFunction__anon93d097f61311::VerifierLegacyPass71790b57cec5SDimitry Andric   bool runOnFunction(Function &F) override {
71800b57cec5SDimitry Andric     if (!V->verify(F) && FatalErrors) {
71810b57cec5SDimitry Andric       errs() << "in function " << F.getName() << '\n';
71820b57cec5SDimitry Andric       report_fatal_error("Broken function found, compilation aborted!");
71830b57cec5SDimitry Andric     }
71840b57cec5SDimitry Andric     return false;
71850b57cec5SDimitry Andric   }
71860b57cec5SDimitry Andric 
doFinalization__anon93d097f61311::VerifierLegacyPass71870b57cec5SDimitry Andric   bool doFinalization(Module &M) override {
71880b57cec5SDimitry Andric     bool HasErrors = false;
71890b57cec5SDimitry Andric     for (Function &F : M)
71900b57cec5SDimitry Andric       if (F.isDeclaration())
71910b57cec5SDimitry Andric         HasErrors |= !V->verify(F);
71920b57cec5SDimitry Andric 
71930b57cec5SDimitry Andric     HasErrors |= !V->verify();
71940b57cec5SDimitry Andric     if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
71950b57cec5SDimitry Andric       report_fatal_error("Broken module found, compilation aborted!");
71960b57cec5SDimitry Andric     return false;
71970b57cec5SDimitry Andric   }
71980b57cec5SDimitry Andric 
getAnalysisUsage__anon93d097f61311::VerifierLegacyPass71990b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
72000b57cec5SDimitry Andric     AU.setPreservesAll();
72010b57cec5SDimitry Andric   }
72020b57cec5SDimitry Andric };
72030b57cec5SDimitry Andric 
72040b57cec5SDimitry Andric } // end anonymous namespace
72050b57cec5SDimitry Andric 
72060b57cec5SDimitry Andric /// Helper to issue failure from the TBAA verification
CheckFailed(Tys &&...Args)72070b57cec5SDimitry Andric template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
72080b57cec5SDimitry Andric   if (Diagnostic)
72090b57cec5SDimitry Andric     return Diagnostic->CheckFailed(Args...);
72100b57cec5SDimitry Andric }
72110b57cec5SDimitry Andric 
721281ad6265SDimitry Andric #define CheckTBAA(C, ...)                                                      \
72130b57cec5SDimitry Andric   do {                                                                         \
72140b57cec5SDimitry Andric     if (!(C)) {                                                                \
72150b57cec5SDimitry Andric       CheckFailed(__VA_ARGS__);                                                \
72160b57cec5SDimitry Andric       return false;                                                            \
72170b57cec5SDimitry Andric     }                                                                          \
72180b57cec5SDimitry Andric   } while (false)
72190b57cec5SDimitry Andric 
72200b57cec5SDimitry Andric /// Verify that \p BaseNode can be used as the "base type" in the struct-path
72210b57cec5SDimitry Andric /// TBAA scheme.  This means \p BaseNode is either a scalar node, or a
72220b57cec5SDimitry Andric /// struct-type node describing an aggregate data structure (like a struct).
72230b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
verifyTBAABaseNode(Instruction & I,const MDNode * BaseNode,bool IsNewFormat)72240b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode,
72250b57cec5SDimitry Andric                                  bool IsNewFormat) {
72260b57cec5SDimitry Andric   if (BaseNode->getNumOperands() < 2) {
72270b57cec5SDimitry Andric     CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
72280b57cec5SDimitry Andric     return {true, ~0u};
72290b57cec5SDimitry Andric   }
72300b57cec5SDimitry Andric 
72310b57cec5SDimitry Andric   auto Itr = TBAABaseNodes.find(BaseNode);
72320b57cec5SDimitry Andric   if (Itr != TBAABaseNodes.end())
72330b57cec5SDimitry Andric     return Itr->second;
72340b57cec5SDimitry Andric 
72350b57cec5SDimitry Andric   auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
72360b57cec5SDimitry Andric   auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
72370b57cec5SDimitry Andric   (void)InsertResult;
72380b57cec5SDimitry Andric   assert(InsertResult.second && "We just checked!");
72390b57cec5SDimitry Andric   return Result;
72400b57cec5SDimitry Andric }
72410b57cec5SDimitry Andric 
72420b57cec5SDimitry Andric TBAAVerifier::TBAABaseNodeSummary
verifyTBAABaseNodeImpl(Instruction & I,const MDNode * BaseNode,bool IsNewFormat)72430b57cec5SDimitry Andric TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode,
72440b57cec5SDimitry Andric                                      bool IsNewFormat) {
72450b57cec5SDimitry Andric   const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
72460b57cec5SDimitry Andric 
72470b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2) {
72480b57cec5SDimitry Andric     // Scalar nodes can only be accessed at offset 0.
72490b57cec5SDimitry Andric     return isValidScalarTBAANode(BaseNode)
72500b57cec5SDimitry Andric                ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
72510b57cec5SDimitry Andric                : InvalidNode;
72520b57cec5SDimitry Andric   }
72530b57cec5SDimitry Andric 
72540b57cec5SDimitry Andric   if (IsNewFormat) {
72550b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 3 != 0) {
72560b57cec5SDimitry Andric       CheckFailed("Access tag nodes must have the number of operands that is a "
72570b57cec5SDimitry Andric                   "multiple of 3!", BaseNode);
72580b57cec5SDimitry Andric       return InvalidNode;
72590b57cec5SDimitry Andric     }
72600b57cec5SDimitry Andric   } else {
72610b57cec5SDimitry Andric     if (BaseNode->getNumOperands() % 2 != 1) {
72620b57cec5SDimitry Andric       CheckFailed("Struct tag nodes must have an odd number of operands!",
72630b57cec5SDimitry Andric                   BaseNode);
72640b57cec5SDimitry Andric       return InvalidNode;
72650b57cec5SDimitry Andric     }
72660b57cec5SDimitry Andric   }
72670b57cec5SDimitry Andric 
72680b57cec5SDimitry Andric   // Check the type size field.
72690b57cec5SDimitry Andric   if (IsNewFormat) {
72700b57cec5SDimitry Andric     auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
72710b57cec5SDimitry Andric         BaseNode->getOperand(1));
72720b57cec5SDimitry Andric     if (!TypeSizeNode) {
72730b57cec5SDimitry Andric       CheckFailed("Type size nodes must be constants!", &I, BaseNode);
72740b57cec5SDimitry Andric       return InvalidNode;
72750b57cec5SDimitry Andric     }
72760b57cec5SDimitry Andric   }
72770b57cec5SDimitry Andric 
72780b57cec5SDimitry Andric   // Check the type name field. In the new format it can be anything.
72790b57cec5SDimitry Andric   if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
72800b57cec5SDimitry Andric     CheckFailed("Struct tag nodes have a string as their first operand",
72810b57cec5SDimitry Andric                 BaseNode);
72820b57cec5SDimitry Andric     return InvalidNode;
72830b57cec5SDimitry Andric   }
72840b57cec5SDimitry Andric 
72850b57cec5SDimitry Andric   bool Failed = false;
72860b57cec5SDimitry Andric 
7287bdd1243dSDimitry Andric   std::optional<APInt> PrevOffset;
72880b57cec5SDimitry Andric   unsigned BitWidth = ~0u;
72890b57cec5SDimitry Andric 
72900b57cec5SDimitry Andric   // We've already checked that BaseNode is not a degenerate root node with one
72910b57cec5SDimitry Andric   // operand in \c verifyTBAABaseNode, so this loop should run at least once.
72920b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
72930b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
72940b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
72950b57cec5SDimitry Andric            Idx += NumOpsPerField) {
72960b57cec5SDimitry Andric     const MDOperand &FieldTy = BaseNode->getOperand(Idx);
72970b57cec5SDimitry Andric     const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
72980b57cec5SDimitry Andric     if (!isa<MDNode>(FieldTy)) {
72990b57cec5SDimitry Andric       CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
73000b57cec5SDimitry Andric       Failed = true;
73010b57cec5SDimitry Andric       continue;
73020b57cec5SDimitry Andric     }
73030b57cec5SDimitry Andric 
73040b57cec5SDimitry Andric     auto *OffsetEntryCI =
73050b57cec5SDimitry Andric         mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
73060b57cec5SDimitry Andric     if (!OffsetEntryCI) {
73070b57cec5SDimitry Andric       CheckFailed("Offset entries must be constants!", &I, BaseNode);
73080b57cec5SDimitry Andric       Failed = true;
73090b57cec5SDimitry Andric       continue;
73100b57cec5SDimitry Andric     }
73110b57cec5SDimitry Andric 
73120b57cec5SDimitry Andric     if (BitWidth == ~0u)
73130b57cec5SDimitry Andric       BitWidth = OffsetEntryCI->getBitWidth();
73140b57cec5SDimitry Andric 
73150b57cec5SDimitry Andric     if (OffsetEntryCI->getBitWidth() != BitWidth) {
73160b57cec5SDimitry Andric       CheckFailed(
73170b57cec5SDimitry Andric           "Bitwidth between the offsets and struct type entries must match", &I,
73180b57cec5SDimitry Andric           BaseNode);
73190b57cec5SDimitry Andric       Failed = true;
73200b57cec5SDimitry Andric       continue;
73210b57cec5SDimitry Andric     }
73220b57cec5SDimitry Andric 
73230b57cec5SDimitry Andric     // NB! As far as I can tell, we generate a non-strictly increasing offset
73240b57cec5SDimitry Andric     // sequence only from structs that have zero size bit fields.  When
73250b57cec5SDimitry Andric     // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
73260b57cec5SDimitry Andric     // pick the field lexically the latest in struct type metadata node.  This
73270b57cec5SDimitry Andric     // mirrors the actual behavior of the alias analysis implementation.
73280b57cec5SDimitry Andric     bool IsAscending =
73290b57cec5SDimitry Andric         !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
73300b57cec5SDimitry Andric 
73310b57cec5SDimitry Andric     if (!IsAscending) {
73320b57cec5SDimitry Andric       CheckFailed("Offsets must be increasing!", &I, BaseNode);
73330b57cec5SDimitry Andric       Failed = true;
73340b57cec5SDimitry Andric     }
73350b57cec5SDimitry Andric 
73360b57cec5SDimitry Andric     PrevOffset = OffsetEntryCI->getValue();
73370b57cec5SDimitry Andric 
73380b57cec5SDimitry Andric     if (IsNewFormat) {
73390b57cec5SDimitry Andric       auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
73400b57cec5SDimitry Andric           BaseNode->getOperand(Idx + 2));
73410b57cec5SDimitry Andric       if (!MemberSizeNode) {
73420b57cec5SDimitry Andric         CheckFailed("Member size entries must be constants!", &I, BaseNode);
73430b57cec5SDimitry Andric         Failed = true;
73440b57cec5SDimitry Andric         continue;
73450b57cec5SDimitry Andric       }
73460b57cec5SDimitry Andric     }
73470b57cec5SDimitry Andric   }
73480b57cec5SDimitry Andric 
73490b57cec5SDimitry Andric   return Failed ? InvalidNode
73500b57cec5SDimitry Andric                 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
73510b57cec5SDimitry Andric }
73520b57cec5SDimitry Andric 
IsRootTBAANode(const MDNode * MD)73530b57cec5SDimitry Andric static bool IsRootTBAANode(const MDNode *MD) {
73540b57cec5SDimitry Andric   return MD->getNumOperands() < 2;
73550b57cec5SDimitry Andric }
73560b57cec5SDimitry Andric 
IsScalarTBAANodeImpl(const MDNode * MD,SmallPtrSetImpl<const MDNode * > & Visited)73570b57cec5SDimitry Andric static bool IsScalarTBAANodeImpl(const MDNode *MD,
73580b57cec5SDimitry Andric                                  SmallPtrSetImpl<const MDNode *> &Visited) {
73590b57cec5SDimitry Andric   if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
73600b57cec5SDimitry Andric     return false;
73610b57cec5SDimitry Andric 
73620b57cec5SDimitry Andric   if (!isa<MDString>(MD->getOperand(0)))
73630b57cec5SDimitry Andric     return false;
73640b57cec5SDimitry Andric 
73650b57cec5SDimitry Andric   if (MD->getNumOperands() == 3) {
73660b57cec5SDimitry Andric     auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
73670b57cec5SDimitry Andric     if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
73680b57cec5SDimitry Andric       return false;
73690b57cec5SDimitry Andric   }
73700b57cec5SDimitry Andric 
73710b57cec5SDimitry Andric   auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
73720b57cec5SDimitry Andric   return Parent && Visited.insert(Parent).second &&
73730b57cec5SDimitry Andric          (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
73740b57cec5SDimitry Andric }
73750b57cec5SDimitry Andric 
isValidScalarTBAANode(const MDNode * MD)73760b57cec5SDimitry Andric bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
73770b57cec5SDimitry Andric   auto ResultIt = TBAAScalarNodes.find(MD);
73780b57cec5SDimitry Andric   if (ResultIt != TBAAScalarNodes.end())
73790b57cec5SDimitry Andric     return ResultIt->second;
73800b57cec5SDimitry Andric 
73810b57cec5SDimitry Andric   SmallPtrSet<const MDNode *, 4> Visited;
73820b57cec5SDimitry Andric   bool Result = IsScalarTBAANodeImpl(MD, Visited);
73830b57cec5SDimitry Andric   auto InsertResult = TBAAScalarNodes.insert({MD, Result});
73840b57cec5SDimitry Andric   (void)InsertResult;
73850b57cec5SDimitry Andric   assert(InsertResult.second && "Just checked!");
73860b57cec5SDimitry Andric 
73870b57cec5SDimitry Andric   return Result;
73880b57cec5SDimitry Andric }
73890b57cec5SDimitry Andric 
73900b57cec5SDimitry Andric /// Returns the field node at the offset \p Offset in \p BaseNode.  Update \p
73910b57cec5SDimitry Andric /// Offset in place to be the offset within the field node returned.
73920b57cec5SDimitry Andric ///
73930b57cec5SDimitry Andric /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
getFieldNodeFromTBAABaseNode(Instruction & I,const MDNode * BaseNode,APInt & Offset,bool IsNewFormat)73940b57cec5SDimitry Andric MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
73950b57cec5SDimitry Andric                                                    const MDNode *BaseNode,
73960b57cec5SDimitry Andric                                                    APInt &Offset,
73970b57cec5SDimitry Andric                                                    bool IsNewFormat) {
73980b57cec5SDimitry Andric   assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
73990b57cec5SDimitry Andric 
74000b57cec5SDimitry Andric   // Scalar nodes have only one possible "field" -- their parent in the access
74010b57cec5SDimitry Andric   // hierarchy.  Offset must be zero at this point, but our caller is supposed
740281ad6265SDimitry Andric   // to check that.
74030b57cec5SDimitry Andric   if (BaseNode->getNumOperands() == 2)
74040b57cec5SDimitry Andric     return cast<MDNode>(BaseNode->getOperand(1));
74050b57cec5SDimitry Andric 
74060b57cec5SDimitry Andric   unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
74070b57cec5SDimitry Andric   unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
74080b57cec5SDimitry Andric   for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
74090b57cec5SDimitry Andric            Idx += NumOpsPerField) {
74100b57cec5SDimitry Andric     auto *OffsetEntryCI =
74110b57cec5SDimitry Andric         mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
74120b57cec5SDimitry Andric     if (OffsetEntryCI->getValue().ugt(Offset)) {
74130b57cec5SDimitry Andric       if (Idx == FirstFieldOpNo) {
74140b57cec5SDimitry Andric         CheckFailed("Could not find TBAA parent in struct type node", &I,
74150b57cec5SDimitry Andric                     BaseNode, &Offset);
74160b57cec5SDimitry Andric         return nullptr;
74170b57cec5SDimitry Andric       }
74180b57cec5SDimitry Andric 
74190b57cec5SDimitry Andric       unsigned PrevIdx = Idx - NumOpsPerField;
74200b57cec5SDimitry Andric       auto *PrevOffsetEntryCI =
74210b57cec5SDimitry Andric           mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
74220b57cec5SDimitry Andric       Offset -= PrevOffsetEntryCI->getValue();
74230b57cec5SDimitry Andric       return cast<MDNode>(BaseNode->getOperand(PrevIdx));
74240b57cec5SDimitry Andric     }
74250b57cec5SDimitry Andric   }
74260b57cec5SDimitry Andric 
74270b57cec5SDimitry Andric   unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
74280b57cec5SDimitry Andric   auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
74290b57cec5SDimitry Andric       BaseNode->getOperand(LastIdx + 1));
74300b57cec5SDimitry Andric   Offset -= LastOffsetEntryCI->getValue();
74310b57cec5SDimitry Andric   return cast<MDNode>(BaseNode->getOperand(LastIdx));
74320b57cec5SDimitry Andric }
74330b57cec5SDimitry Andric 
isNewFormatTBAATypeNode(llvm::MDNode * Type)74340b57cec5SDimitry Andric static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) {
74350b57cec5SDimitry Andric   if (!Type || Type->getNumOperands() < 3)
74360b57cec5SDimitry Andric     return false;
74370b57cec5SDimitry Andric 
74380b57cec5SDimitry Andric   // In the new format type nodes shall have a reference to the parent type as
74390b57cec5SDimitry Andric   // its first operand.
7440349cc55cSDimitry Andric   return isa_and_nonnull<MDNode>(Type->getOperand(0));
74410b57cec5SDimitry Andric }
74420b57cec5SDimitry Andric 
visitTBAAMetadata(Instruction & I,const MDNode * MD)74430b57cec5SDimitry Andric bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
744406c3fb27SDimitry Andric   CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands",
744506c3fb27SDimitry Andric             &I, MD);
744606c3fb27SDimitry Andric 
744781ad6265SDimitry Andric   CheckTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
74480b57cec5SDimitry Andric                 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
74490b57cec5SDimitry Andric                 isa<AtomicCmpXchgInst>(I),
74500b57cec5SDimitry Andric             "This instruction shall not have a TBAA access tag!", &I);
74510b57cec5SDimitry Andric 
74520b57cec5SDimitry Andric   bool IsStructPathTBAA =
74530b57cec5SDimitry Andric       isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
74540b57cec5SDimitry Andric 
745581ad6265SDimitry Andric   CheckTBAA(IsStructPathTBAA,
745681ad6265SDimitry Andric             "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
745781ad6265SDimitry Andric             &I);
74580b57cec5SDimitry Andric 
74590b57cec5SDimitry Andric   MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
74600b57cec5SDimitry Andric   MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
74610b57cec5SDimitry Andric 
74620b57cec5SDimitry Andric   bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
74630b57cec5SDimitry Andric 
74640b57cec5SDimitry Andric   if (IsNewFormat) {
746581ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
74660b57cec5SDimitry Andric               "Access tag metadata must have either 4 or 5 operands", &I, MD);
74670b57cec5SDimitry Andric   } else {
746881ad6265SDimitry Andric     CheckTBAA(MD->getNumOperands() < 5,
74690b57cec5SDimitry Andric               "Struct tag metadata must have either 3 or 4 operands", &I, MD);
74700b57cec5SDimitry Andric   }
74710b57cec5SDimitry Andric 
74720b57cec5SDimitry Andric   // Check the access size field.
74730b57cec5SDimitry Andric   if (IsNewFormat) {
74740b57cec5SDimitry Andric     auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
74750b57cec5SDimitry Andric         MD->getOperand(3));
747681ad6265SDimitry Andric     CheckTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD);
74770b57cec5SDimitry Andric   }
74780b57cec5SDimitry Andric 
74790b57cec5SDimitry Andric   // Check the immutability flag.
74800b57cec5SDimitry Andric   unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
74810b57cec5SDimitry Andric   if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
74820b57cec5SDimitry Andric     auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
74830b57cec5SDimitry Andric         MD->getOperand(ImmutabilityFlagOpNo));
748481ad6265SDimitry Andric     CheckTBAA(IsImmutableCI,
748581ad6265SDimitry Andric               "Immutability tag on struct tag metadata must be a constant", &I,
748681ad6265SDimitry Andric               MD);
748781ad6265SDimitry Andric     CheckTBAA(
74880b57cec5SDimitry Andric         IsImmutableCI->isZero() || IsImmutableCI->isOne(),
74890b57cec5SDimitry Andric         "Immutability part of the struct tag metadata must be either 0 or 1",
74900b57cec5SDimitry Andric         &I, MD);
74910b57cec5SDimitry Andric   }
74920b57cec5SDimitry Andric 
749381ad6265SDimitry Andric   CheckTBAA(BaseNode && AccessType,
74940b57cec5SDimitry Andric             "Malformed struct tag metadata: base and access-type "
74950b57cec5SDimitry Andric             "should be non-null and point to Metadata nodes",
74960b57cec5SDimitry Andric             &I, MD, BaseNode, AccessType);
74970b57cec5SDimitry Andric 
74980b57cec5SDimitry Andric   if (!IsNewFormat) {
749981ad6265SDimitry Andric     CheckTBAA(isValidScalarTBAANode(AccessType),
75000b57cec5SDimitry Andric               "Access type node must be a valid scalar type", &I, MD,
75010b57cec5SDimitry Andric               AccessType);
75020b57cec5SDimitry Andric   }
75030b57cec5SDimitry Andric 
75040b57cec5SDimitry Andric   auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
750581ad6265SDimitry Andric   CheckTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
75060b57cec5SDimitry Andric 
75070b57cec5SDimitry Andric   APInt Offset = OffsetCI->getValue();
75080b57cec5SDimitry Andric   bool SeenAccessTypeInPath = false;
75090b57cec5SDimitry Andric 
75100b57cec5SDimitry Andric   SmallPtrSet<MDNode *, 4> StructPath;
75110b57cec5SDimitry Andric 
75120b57cec5SDimitry Andric   for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
75130b57cec5SDimitry Andric        BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
75140b57cec5SDimitry Andric                                                IsNewFormat)) {
75150b57cec5SDimitry Andric     if (!StructPath.insert(BaseNode).second) {
75160b57cec5SDimitry Andric       CheckFailed("Cycle detected in struct path", &I, MD);
75170b57cec5SDimitry Andric       return false;
75180b57cec5SDimitry Andric     }
75190b57cec5SDimitry Andric 
75200b57cec5SDimitry Andric     bool Invalid;
75210b57cec5SDimitry Andric     unsigned BaseNodeBitWidth;
75220b57cec5SDimitry Andric     std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
75230b57cec5SDimitry Andric                                                              IsNewFormat);
75240b57cec5SDimitry Andric 
75250b57cec5SDimitry Andric     // If the base node is invalid in itself, then we've already printed all the
75260b57cec5SDimitry Andric     // errors we wanted to print.
75270b57cec5SDimitry Andric     if (Invalid)
75280b57cec5SDimitry Andric       return false;
75290b57cec5SDimitry Andric 
75300b57cec5SDimitry Andric     SeenAccessTypeInPath |= BaseNode == AccessType;
75310b57cec5SDimitry Andric 
75320b57cec5SDimitry Andric     if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
753381ad6265SDimitry Andric       CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access",
75340b57cec5SDimitry Andric                 &I, MD, &Offset);
75350b57cec5SDimitry Andric 
753681ad6265SDimitry Andric     CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
75370b57cec5SDimitry Andric                   (BaseNodeBitWidth == 0 && Offset == 0) ||
75380b57cec5SDimitry Andric                   (IsNewFormat && BaseNodeBitWidth == ~0u),
75390b57cec5SDimitry Andric               "Access bit-width not the same as description bit-width", &I, MD,
75400b57cec5SDimitry Andric               BaseNodeBitWidth, Offset.getBitWidth());
75410b57cec5SDimitry Andric 
75420b57cec5SDimitry Andric     if (IsNewFormat && SeenAccessTypeInPath)
75430b57cec5SDimitry Andric       break;
75440b57cec5SDimitry Andric   }
75450b57cec5SDimitry Andric 
754681ad6265SDimitry Andric   CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", &I,
754781ad6265SDimitry Andric             MD);
75480b57cec5SDimitry Andric   return true;
75490b57cec5SDimitry Andric }
75500b57cec5SDimitry Andric 
75510b57cec5SDimitry Andric char VerifierLegacyPass::ID = 0;
75520b57cec5SDimitry Andric INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
75530b57cec5SDimitry Andric 
createVerifierPass(bool FatalErrors)75540b57cec5SDimitry Andric FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
75550b57cec5SDimitry Andric   return new VerifierLegacyPass(FatalErrors);
75560b57cec5SDimitry Andric }
75570b57cec5SDimitry Andric 
75580b57cec5SDimitry Andric AnalysisKey VerifierAnalysis::Key;
run(Module & M,ModuleAnalysisManager &)75590b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
75600b57cec5SDimitry Andric                                                ModuleAnalysisManager &) {
75610b57cec5SDimitry Andric   Result Res;
75620b57cec5SDimitry Andric   Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
75630b57cec5SDimitry Andric   return Res;
75640b57cec5SDimitry Andric }
75650b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager &)75660b57cec5SDimitry Andric VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
75670b57cec5SDimitry Andric                                                FunctionAnalysisManager &) {
75680b57cec5SDimitry Andric   return { llvm::verifyFunction(F, &dbgs()), false };
75690b57cec5SDimitry Andric }
75700b57cec5SDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)75710b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
75720b57cec5SDimitry Andric   auto Res = AM.getResult<VerifierAnalysis>(M);
75730b57cec5SDimitry Andric   if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
75740b57cec5SDimitry Andric     report_fatal_error("Broken module found, compilation aborted!");
75750b57cec5SDimitry Andric 
75760b57cec5SDimitry Andric   return PreservedAnalyses::all();
75770b57cec5SDimitry Andric }
75780b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)75790b57cec5SDimitry Andric PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
75800b57cec5SDimitry Andric   auto res = AM.getResult<VerifierAnalysis>(F);
75810b57cec5SDimitry Andric   if (res.IRBroken && FatalErrors)
75820b57cec5SDimitry Andric     report_fatal_error("Broken function found, compilation aborted!");
75830b57cec5SDimitry Andric 
75840b57cec5SDimitry Andric   return PreservedAnalyses::all();
75850b57cec5SDimitry Andric }
7586