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