blob: a362a816ecf49cf190434db328bcad9792891496 [file] [log] [blame]
Nick Lewyckyd489edf2012-02-25 07:20:06 +00001//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner3e6e3e62002-03-29 19:06:18 +000010// This file defines the function verifier interface, that can be used for some
Chris Lattner2f7c9632001-06-06 20:29:01 +000011// sanity checking of input to the system.
12//
Misha Brukman1c9de462004-06-24 21:47:35 +000013// Note that this does not provide full `Java style' security and verifications,
14// instead it just tries to ensure that code is well-formed.
Chris Lattner2f7c9632001-06-06 20:29:01 +000015//
Misha Brukman1c9de462004-06-24 21:47:35 +000016// * Both of a binary operator's parameters are of the same type
Chris Lattnerd46bb6e2002-04-24 19:12:21 +000017// * Verify that the indices of mem access instructions match other operands
Misha Brukman1c9de462004-06-24 21:47:35 +000018// * Verify that arithmetic and other things are only performed on first-class
Chris Lattner8e72d6f2002-08-02 17:37:08 +000019// types. Verify that shifts & logicals only happen on integrals f.e.
Misha Brukman1c9de462004-06-24 21:47:35 +000020// * All of the constants in a switch statement are of the correct type
Chris Lattner8e72d6f2002-08-02 17:37:08 +000021// * The code is in valid SSA form
Misha Brukman1c9de462004-06-24 21:47:35 +000022// * It should be illegal to put a label into any other type (like a structure)
Chris Lattner2f7c9632001-06-06 20:29:01 +000023// or to return one. [except constant arrays!]
Nick Lewyckyf88c84f2008-03-28 06:46:51 +000024// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
Chris Lattnerd02f08d2002-02-20 17:55:43 +000025// * PHI nodes must have an entry for each predecessor, with no extras.
Chris Lattner069a7952002-06-25 15:56:27 +000026// * PHI nodes must be the first thing in a basic block, all grouped together
Chris Lattner4cd9df82002-10-06 21:00:31 +000027// * PHI nodes must have at least one entry
Chris Lattner069a7952002-06-25 15:56:27 +000028// * All basic blocks should only end with terminator insts, not contain them
Chris Lattner3e6e3e62002-03-29 19:06:18 +000029// * The entry node to a function must not have predecessors
Misha Brukmanfa100532003-10-10 17:54:14 +000030// * All Instructions must be embedded into a basic block
Misha Brukman1c9de462004-06-24 21:47:35 +000031// * Functions cannot take a void-typed parameter
Chris Lattneraf95e582002-04-13 22:48:46 +000032// * Verify that a function's argument list agrees with it's declared type.
Chris Lattnerfbf5be52002-03-15 20:25:09 +000033// * It is illegal to specify a name for a void value.
Misha Brukmanfa100532003-10-10 17:54:14 +000034// * It is illegal to have a internal global value with no initializer
Chris Lattner486302a2002-04-12 18:20:49 +000035// * It is illegal to have a ret instruction that returns a value that does not
36// agree with the function return value type.
Chris Lattner338a4622002-05-08 19:49:50 +000037// * Function call argument types match the function prototype
Bill Wendlingfae14752011-08-12 20:24:12 +000038// * A landing pad is defined by a landingpad instruction, and can be jumped to
39// only by the unwind edge of an invoke instruction.
40// * A landingpad instruction must be the first non-PHI instruction in the
41// block.
Vedant Kumar029c3512015-10-21 20:33:31 +000042// * Landingpad instructions must be in a function with a personality function.
Chris Lattnerd46bb6e2002-04-24 19:12:21 +000043// * All other things that are tested by asserts spread about the code...
Chris Lattner2f7c9632001-06-06 20:29:01 +000044//
45//===----------------------------------------------------------------------===//
46
Chandler Carruth5ad5f152014-01-13 09:26:24 +000047#include "llvm/IR/Verifier.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000048#include "llvm/ADT/APFloat.h"
49#include "llvm/ADT/APInt.h"
50#include "llvm/ADT/ArrayRef.h"
51#include "llvm/ADT/DenseMap.h"
52#include "llvm/ADT/ilist.h"
Joseph Tremoulet8ea80862016-01-10 04:31:05 +000053#include "llvm/ADT/MapVector.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000054#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000055#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000057#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/ADT/SmallVector.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000059#include "llvm/ADT/StringMap.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Twine.h"
62#include "llvm/IR/Argument.h"
63#include "llvm/IR/Attributes.h"
64#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000065#include "llvm/IR/CFG.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000066#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000067#include "llvm/IR/CallingConv.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000068#include "llvm/IR/Comdat.h"
69#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000070#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000071#include "llvm/IR/Constants.h"
Matt Arsenault24b49c42013-07-31 17:49:08 +000072#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000073#include "llvm/IR/DebugInfo.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000074#include "llvm/IR/DebugInfoMetadata.h"
75#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000076#include "llvm/IR/DerivedTypes.h"
Adrian Prantle3656182016-05-09 19:57:29 +000077#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000078#include "llvm/IR/Dominators.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000079#include "llvm/IR/Function.h"
80#include "llvm/IR/GlobalAlias.h"
81#include "llvm/IR/GlobalValue.h"
82#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000083#include "llvm/IR/InlineAsm.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000084#include "llvm/IR/InstrTypes.h"
85#include "llvm/IR/Instruction.h"
86#include "llvm/IR/Instructions.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000087#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000088#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000089#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000090#include "llvm/IR/LLVMContext.h"
91#include "llvm/IR/Metadata.h"
92#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +000093#include "llvm/IR/ModuleSlotTracker.h"
Chandler Carruth4d356312014-01-20 11:34:08 +000094#include "llvm/IR/PassManager.h"
Philip Reames38303a32014-12-03 19:53:15 +000095#include "llvm/IR/Statepoint.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +000096#include "llvm/IR/Type.h"
97#include "llvm/IR/Use.h"
98#include "llvm/IR/User.h"
99#include "llvm/IR/Value.h"
Chris Lattner8a923e72008-03-12 17:45:29 +0000100#include "llvm/Pass.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000101#include "llvm/Support/AtomicOrdering.h"
102#include "llvm/Support/Casting.h"
Manman Ren74c61b92013-07-19 00:31:03 +0000103#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000104#include "llvm/Support/Debug.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000105#include "llvm/Support/Dwarf.h"
Torok Edwin6dd27302009-07-08 18:01:40 +0000106#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000107#include "llvm/Support/MathExtras.h"
Chris Lattner24025262009-02-28 21:05:51 +0000108#include "llvm/Support/raw_ostream.h"
Chris Lattnerd02f08d2002-02-20 17:55:43 +0000109#include <algorithm>
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000110#include <cassert>
111#include <cstdint>
112#include <memory>
113#include <string>
114#include <utility>
115
Chris Lattner189d19f2003-11-21 20:23:48 +0000116using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +0000117
Duncan P. N. Exon Smith0633fd72015-03-17 17:28:41 +0000118static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
Manman Ren74c61b92013-07-19 00:31:03 +0000119
Daniel Jaspera44fd302016-12-16 13:53:46 +0000120namespace llvm {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000121
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000122struct VerifierSupport {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000123 raw_ostream *OS;
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000124 const Module &M;
125 ModuleSlotTracker MST;
126 const DataLayout &DL;
127 LLVMContext &Context;
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000128
Duncan P. N. Exon Smith9c3ff192016-04-20 15:55:24 +0000129 /// Track the brokenness of the module while recursively visiting.
130 bool Broken = false;
Adrian Prantl541a9c52016-05-06 19:26:47 +0000131 /// Broken debug info can be "recovered" from by stripping the debug info.
132 bool BrokenDebugInfo = false;
133 /// Whether to treat broken debug info as an error.
134 bool TreatBrokenDebugInfoAsError = true;
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000135
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000136 explicit VerifierSupport(raw_ostream *OS, const Module &M)
137 : OS(OS), M(M), MST(&M), DL(M.getDataLayout()), Context(M.getContext()) {}
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000138
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000139private:
Keno Fischera6c4ce42015-12-01 19:06:36 +0000140 void Write(const Module *M) {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000141 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
Keno Fischera6c4ce42015-12-01 19:06:36 +0000142 }
143
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000144 void Write(const Value *V) {
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000145 if (!V)
146 return;
147 if (isa<Instruction>(V)) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000148 V->print(*OS, MST);
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +0000149 *OS << '\n';
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000150 } else {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000151 V->printAsOperand(*OS, true, MST);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000152 *OS << '\n';
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000153 }
154 }
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000155
Philip Reames9818dd72015-06-26 22:04:34 +0000156 void Write(ImmutableCallSite CS) {
157 Write(CS.getInstruction());
Philip Reamesa3c6f002015-06-26 21:39:44 +0000158 }
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000159
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000160 void Write(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000161 if (!MD)
162 return;
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000163 MD->print(*OS, MST, &M);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000164 *OS << '\n';
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000165 }
166
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +0000167 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
168 Write(MD.get());
169 }
170
Duncan P. N. Exon Smithf238c782015-03-24 17:18:03 +0000171 void Write(const NamedMDNode *NMD) {
172 if (!NMD)
173 return;
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000174 NMD->print(*OS, MST);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000175 *OS << '\n';
Duncan P. N. Exon Smithf238c782015-03-24 17:18:03 +0000176 }
177
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000178 void Write(Type *T) {
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000179 if (!T)
180 return;
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000181 *OS << ' ' << *T;
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000182 }
183
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000184 void Write(const Comdat *C) {
David Majnemerdad0a642014-06-27 18:19:56 +0000185 if (!C)
186 return;
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000187 *OS << *C;
David Majnemerdad0a642014-06-27 18:19:56 +0000188 }
189
Sanjoy Das3336f682016-12-11 20:07:15 +0000190 void Write(const APInt *AI) {
191 if (!AI)
192 return;
193 *OS << *AI << '\n';
194 }
195
196 void Write(const unsigned i) { *OS << i << '\n'; }
197
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000198 template <typename T> void Write(ArrayRef<T> Vs) {
199 for (const T &V : Vs)
200 Write(V);
201 }
202
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000203 template <typename T1, typename... Ts>
204 void WriteTs(const T1 &V1, const Ts &... Vs) {
205 Write(V1);
206 WriteTs(Vs...);
207 }
208
209 template <typename... Ts> void WriteTs() {}
210
211public:
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000212 /// \brief A check failed, so printout out the condition and the message.
213 ///
214 /// This provides a nice place to put a breakpoint if you want to see why
215 /// something is not correct.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000216 void CheckFailed(const Twine &Message) {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000217 if (OS)
218 *OS << Message << '\n';
Duncan P. N. Exon Smith6a607c02015-03-31 02:37:13 +0000219 Broken = true;
David Majnemerdad0a642014-06-27 18:19:56 +0000220 }
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000221
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000222 /// \brief A check failed (with values to print).
223 ///
224 /// This calls the Message-only version so that the above is easier to set a
225 /// breakpoint on.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000226 template <typename T1, typename... Ts>
227 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
228 CheckFailed(Message);
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +0000229 if (OS)
230 WriteTs(V1, Vs...);
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000231 }
Adrian Prantl541a9c52016-05-06 19:26:47 +0000232
233 /// A debug info check failed.
234 void DebugInfoCheckFailed(const Twine &Message) {
235 if (OS)
236 *OS << Message << '\n';
237 Broken |= TreatBrokenDebugInfoAsError;
238 BrokenDebugInfo = true;
239 }
240
241 /// A debug info check failed (with values to print).
242 template <typename T1, typename... Ts>
243 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1,
244 const Ts &... Vs) {
245 DebugInfoCheckFailed(Message);
246 if (OS)
247 WriteTs(V1, Vs...);
248 }
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000249};
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000250
Daniel Jaspera44fd302016-12-16 13:53:46 +0000251} // namespace llvm
252
253namespace {
254
Duncan P. N. Exon Smith67b44da2014-04-15 16:27:32 +0000255class Verifier : public InstVisitor<Verifier>, VerifierSupport {
256 friend class InstVisitor<Verifier>;
257
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000258 DominatorTree DT;
Chris Lattnerc9e79d02004-09-29 20:07:45 +0000259
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000260 /// \brief When verifying a basic block, keep track of all of the
261 /// instructions we have seen so far.
262 ///
263 /// This allows us to do efficient dominance checks for the case when an
264 /// instruction has an operand that is an instruction in the same block.
265 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
Bill Wendlingfae14752011-08-12 20:24:12 +0000266
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000267 /// \brief Keep track of the metadata nodes that have been checked already.
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000268 SmallPtrSet<const Metadata *, 32> MDNodes;
Manman Ren9974c882013-07-23 00:22:51 +0000269
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000270 /// Track all DICompileUnits visited.
271 SmallPtrSet<const Metadata *, 2> CUVisited;
272
David Majnemer654e1302015-07-31 17:58:14 +0000273 /// \brief The result type for a landingpad.
274 Type *LandingPadResultTy;
275
Reid Kleckner60381792015-07-07 22:25:32 +0000276 /// \brief Whether we've seen a call to @llvm.localescape in this function
Reid Klecknere9b89312015-01-13 00:48:10 +0000277 /// already.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000278 bool SawFrameEscape;
279
Adrian Prantl63d96952017-03-07 17:28:54 +0000280 /// Whether the current function has a DISubprogram attached to it.
281 bool HasDebugInfo = false;
282
Reid Kleckner60381792015-07-07 22:25:32 +0000283 /// Stores the count of how many objects were passed to llvm.localescape for a
284 /// given function and the largest index passed to llvm.localrecover.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000285 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
Reid Klecknere9b89312015-01-13 00:48:10 +0000286
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000287 // Maps catchswitches and cleanuppads that unwind to siblings to the
288 // terminators that indicate the unwind, used to detect cycles therein.
289 MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo;
290
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000291 /// Cache of constants visited in search of ConstantExprs.
292 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
293
Sanjoy Dase0aa4142016-05-12 01:17:38 +0000294 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
295 SmallVector<const Function *, 4> DeoptimizeDeclarations;
296
Ivan Krasin3b1c2602016-01-20 08:41:22 +0000297 // Verify that this GlobalValue is only used in this module.
298 // This map is used to avoid visiting uses twice. We can arrive at a user
299 // twice, if they have multiple operands. In particular for very large
300 // constant expressions, we can arrive at a particular user many times.
301 SmallPtrSet<const Value *, 32> GlobalValueVisited;
302
Adrian Prantl612ac862017-02-28 23:48:42 +0000303 // Keeps track of duplicate function argument debug info.
304 SmallVector<const DILocalVariable *, 16> DebugFnArgs;
305
Mehdi Aminia84a8402016-12-16 06:29:14 +0000306 TBAAVerifier TBAAVerifyHelper;
Sanjoy Das3336f682016-12-11 20:07:15 +0000307
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000308 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
Duncan P. N. Exon Smith0ecff952016-04-20 17:27:44 +0000309
Chandler Carruth043949d2014-01-19 02:22:18 +0000310public:
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000311 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
312 const Module &M)
313 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
Mehdi Aminia84a8402016-12-16 06:29:14 +0000314 SawFrameEscape(false), TBAAVerifyHelper(this) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000315 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
316 }
317
318 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
Chris Lattner0e851da2002-04-18 20:37:37 +0000319
Chandler Carruth043949d2014-01-19 02:22:18 +0000320 bool verify(const Function &F) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000321 assert(F.getParent() == &M &&
322 "An instance of this class only works with a specific module!");
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000323
324 // First ensure the function is well-enough formed to compute dominance
Peter Collingbourne71bb7942016-06-06 22:32:52 +0000325 // information, and directly compute a dominance tree. We don't rely on the
326 // pass manager to provide this as it isolates us from a potentially
327 // out-of-date dominator tree and makes it significantly more complex to run
328 // this code outside of a pass manager.
329 // FIXME: It's really gross that we have to cast away constness here.
330 if (!F.empty())
331 DT.recalculate(const_cast<Function &>(F));
332
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000333 for (const BasicBlock &BB : F) {
Duncan P. N. Exon Smith8ec8da42016-04-20 18:27:18 +0000334 if (!BB.empty() && BB.back().isTerminator())
335 continue;
336
337 if (OS) {
338 *OS << "Basic Block in function '" << F.getName()
339 << "' does not have terminator!\n";
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000340 BB.printAsOperand(*OS, true, MST);
Duncan P. N. Exon Smith8ec8da42016-04-20 18:27:18 +0000341 *OS << "\n";
Chandler Carruth76777602014-01-17 10:56:02 +0000342 }
Duncan P. N. Exon Smith8ec8da42016-04-20 18:27:18 +0000343 return false;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000344 }
Chandler Carruth76777602014-01-17 10:56:02 +0000345
Chandler Carruth043949d2014-01-19 02:22:18 +0000346 Broken = false;
347 // FIXME: We strip const here because the inst visitor strips const.
348 visit(const_cast<Function &>(F));
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000349 verifySiblingFuncletUnwinds();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000350 InstsInThisBlock.clear();
Adrian Prantl9b24a452017-03-07 17:28:49 +0000351 DebugFnArgs.clear();
David Majnemer654e1302015-07-31 17:58:14 +0000352 LandingPadResultTy = nullptr;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000353 SawFrameEscape = false;
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000354 SiblingFuncletInfo.clear();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000355
Chandler Carruth043949d2014-01-19 02:22:18 +0000356 return !Broken;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000357 }
358
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000359 /// Verify the module that this instance of \c Verifier was initialized with.
360 bool verify() {
Chandler Carruth043949d2014-01-19 02:22:18 +0000361 Broken = false;
362
Peter Collingbournebb738172016-06-06 23:21:27 +0000363 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
364 for (const Function &F : M)
365 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
366 DeoptimizeDeclarations.push_back(&F);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000367
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000368 // Now that we've visited every function, verify that we never asked to
369 // recover a frame index that wasn't escaped.
370 verifyFrameRecoverIndices();
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000371 for (const GlobalVariable &GV : M.globals())
372 visitGlobalVariable(GV);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000373
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000374 for (const GlobalAlias &GA : M.aliases())
375 visitGlobalAlias(GA);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000376
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000377 for (const NamedMDNode &NMD : M.named_metadata())
378 visitNamedMDNode(NMD);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000379
David Majnemerdad0a642014-06-27 18:19:56 +0000380 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
381 visitComdat(SMEC.getValue());
382
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000383 visitModuleFlags(M);
384 visitModuleIdents(M);
385
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000386 verifyCompileUnits();
387
Sanjoy Dase0aa4142016-05-12 01:17:38 +0000388 verifyDeoptimizeCallingConvs();
389
Chandler Carruth043949d2014-01-19 02:22:18 +0000390 return !Broken;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000391 }
Chris Lattner9713b842002-04-28 16:04:26 +0000392
Chandler Carruth043949d2014-01-19 02:22:18 +0000393private:
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000394 // Verification methods...
Chandler Carruth043949d2014-01-19 02:22:18 +0000395 void visitGlobalValue(const GlobalValue &GV);
396 void visitGlobalVariable(const GlobalVariable &GV);
397 void visitGlobalAlias(const GlobalAlias &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000398 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
Craig Topper71b7b682014-08-21 05:55:13 +0000399 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
Rafael Espindola64c1e182014-06-03 02:41:57 +0000400 const GlobalAlias &A, const Constant &C);
Chandler Carruth043949d2014-01-19 02:22:18 +0000401 void visitNamedMDNode(const NamedMDNode &NMD);
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000402 void visitMDNode(const MDNode &MD);
403 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
404 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
David Majnemerdad0a642014-06-27 18:19:56 +0000405 void visitComdat(const Comdat &C);
Chandler Carruth043949d2014-01-19 02:22:18 +0000406 void visitModuleIdents(const Module &M);
407 void visitModuleFlags(const Module &M);
408 void visitModuleFlag(const MDNode *Op,
409 DenseMap<const MDString *, const MDNode *> &SeenIDs,
410 SmallVectorImpl<const MDNode *> &Requirements);
411 void visitFunction(const Function &F);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000412 void visitBasicBlock(BasicBlock &BB);
Sanjoy Das26f28a22016-11-09 19:36:39 +0000413 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
414 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
Sanjoy Das3336f682016-12-11 20:07:15 +0000415
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +0000416 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +0000417#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
418#include "llvm/IR/Metadata.def"
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000419 void visitDIScope(const DIScope &N);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000420 void visitDIVariable(const DIVariable &N);
421 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
422 void visitDITemplateParameter(const DITemplateParameter &N);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000423
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000424 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
425
Chandler Carruth043949d2014-01-19 02:22:18 +0000426 // InstVisitor overrides...
427 using InstVisitor<Verifier>::visit;
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000428 void visit(Instruction &I);
429
430 void visitTruncInst(TruncInst &I);
431 void visitZExtInst(ZExtInst &I);
432 void visitSExtInst(SExtInst &I);
433 void visitFPTruncInst(FPTruncInst &I);
434 void visitFPExtInst(FPExtInst &I);
435 void visitFPToUIInst(FPToUIInst &I);
436 void visitFPToSIInst(FPToSIInst &I);
437 void visitUIToFPInst(UIToFPInst &I);
438 void visitSIToFPInst(SIToFPInst &I);
439 void visitIntToPtrInst(IntToPtrInst &I);
440 void visitPtrToIntInst(PtrToIntInst &I);
441 void visitBitCastInst(BitCastInst &I);
442 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
443 void visitPHINode(PHINode &PN);
444 void visitBinaryOperator(BinaryOperator &B);
445 void visitICmpInst(ICmpInst &IC);
446 void visitFCmpInst(FCmpInst &FC);
447 void visitExtractElementInst(ExtractElementInst &EI);
448 void visitInsertElementInst(InsertElementInst &EI);
449 void visitShuffleVectorInst(ShuffleVectorInst &EI);
450 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
451 void visitCallInst(CallInst &CI);
452 void visitInvokeInst(InvokeInst &II);
453 void visitGetElementPtrInst(GetElementPtrInst &GEP);
454 void visitLoadInst(LoadInst &LI);
455 void visitStoreInst(StoreInst &SI);
456 void verifyDominatesUse(Instruction &I, unsigned i);
457 void visitInstruction(Instruction &I);
458 void visitTerminatorInst(TerminatorInst &I);
459 void visitBranchInst(BranchInst &BI);
460 void visitReturnInst(ReturnInst &RI);
461 void visitSwitchInst(SwitchInst &SI);
462 void visitIndirectBrInst(IndirectBrInst &BI);
463 void visitSelectInst(SelectInst &SI);
464 void visitUserOp1(Instruction &I);
465 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
Philip Reames007561a2015-06-26 22:21:52 +0000466 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
Andrew Kaylora0a11642017-01-26 23:27:59 +0000467 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +0000468 template <class DbgIntrinsicTy>
469 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000470 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
471 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
472 void visitFenceInst(FenceInst &FI);
473 void visitAllocaInst(AllocaInst &AI);
474 void visitExtractValueInst(ExtractValueInst &EVI);
475 void visitInsertValueInst(InsertValueInst &IVI);
David Majnemer85a549d2015-08-11 02:48:30 +0000476 void visitEHPadPredecessors(Instruction &I);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000477 void visitLandingPadInst(LandingPadInst &LPI);
David Majnemerba6665d2016-08-01 18:06:34 +0000478 void visitResumeInst(ResumeInst &RI);
David Majnemer654e1302015-07-31 17:58:14 +0000479 void visitCatchPadInst(CatchPadInst &CPI);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000480 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
David Majnemer654e1302015-07-31 17:58:14 +0000481 void visitCleanupPadInst(CleanupPadInst &CPI);
Joseph Tremoulet81e81962016-01-10 04:30:02 +0000482 void visitFuncletPadInst(FuncletPadInst &FPI);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000483 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
David Majnemer654e1302015-07-31 17:58:14 +0000484 void visitCleanupReturnInst(CleanupReturnInst &CRI);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000485
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000486 void verifyCallSite(CallSite CS);
Manman Ren9bfd0d02016-04-01 21:41:15 +0000487 void verifySwiftErrorCallSite(CallSite CS, const Value *SwiftErrorVal);
488 void verifySwiftErrorValue(const Value *SwiftErrorVal);
Reid Kleckner5772b772014-04-24 20:14:34 +0000489 void verifyMustTailCall(CallInst &CI);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000490 bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000491 unsigned ArgNo, std::string &Suffix);
Reid Klecknerb5180542017-03-21 16:57:19 +0000492 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
Reid Klecknera77172a2017-04-14 00:06:06 +0000493 void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000494 const Value *V);
Reid Klecknera77172a2017-04-14 00:06:06 +0000495 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
Reid Klecknerb5180542017-03-21 16:57:19 +0000496 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000497 const Value *V);
Benjamin Kramer7ab4fe32016-06-12 17:46:23 +0000498 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000499
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000500 void visitConstantExprsRecursively(const Constant *EntryC);
501 void visitConstantExpr(const ConstantExpr *CE);
Sanjay Patelbbdab7a2016-01-31 16:32:23 +0000502 void verifyStatepoint(ImmutableCallSite CS);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000503 void verifyFrameRecoverIndices();
Joseph Tremoulet8ea80862016-01-10 04:31:05 +0000504 void verifySiblingFuncletUnwinds();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000505
Adrian Prantl941fa752016-12-05 18:04:47 +0000506 void verifyFragmentExpression(const DbgInfoIntrinsic &I);
Adrian Prantl612ac862017-02-28 23:48:42 +0000507 void verifyFnArgs(const DbgInfoIntrinsic &I);
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000508
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000509 /// Module-level debug info verification...
Adrian Prantlfaebbb02016-03-28 21:06:26 +0000510 void verifyCompileUnits();
Sanjoy Dase0aa4142016-05-12 01:17:38 +0000511
512 /// Module-level verification that all @llvm.experimental.deoptimize
513 /// declarations share the same calling convention.
514 void verifyDeoptimizeCallingConvs();
Chandler Carruthbf2b6522014-01-17 11:09:34 +0000515};
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000516
517} // end anonymous namespace
Chris Lattner189d19f2003-11-21 20:23:48 +0000518
Adrian Prantl541a9c52016-05-06 19:26:47 +0000519/// We know that cond should be true, if not print an error message.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000520#define Assert(C, ...) \
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000521 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
Chris Lattner2f7c9632001-06-06 20:29:01 +0000522
Adrian Prantl541a9c52016-05-06 19:26:47 +0000523/// We know that a debug info condition should be true, if not print
524/// an error message.
525#define AssertDI(C, ...) \
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000526 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
Adrian Prantl541a9c52016-05-06 19:26:47 +0000527
Chris Lattnere5a22c02008-08-28 04:02:44 +0000528void Verifier::visit(Instruction &I) {
529 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000530 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
Chris Lattnere5a22c02008-08-28 04:02:44 +0000531 InstVisitor<Verifier>::visit(I);
532}
533
Keno Fischer60f82a22016-01-14 22:20:56 +0000534// Helper to recursively iterate over indirect users. By
535// returning false, the callback can ask to stop recursing
536// further.
537static void forEachUser(const Value *User,
538 SmallPtrSet<const Value *, 32> &Visited,
539 llvm::function_ref<bool(const Value *)> Callback) {
540 if (!Visited.insert(User).second)
541 return;
Rafael Espindola257a3532016-01-15 19:00:20 +0000542 for (const Value *TheNextUser : User->materialized_users())
Keno Fischer60f82a22016-01-14 22:20:56 +0000543 if (Callback(TheNextUser))
544 forEachUser(TheNextUser, Visited, Callback);
545}
Chris Lattnere5a22c02008-08-28 04:02:44 +0000546
Chandler Carruth043949d2014-01-19 02:22:18 +0000547void Verifier::visitGlobalValue(const GlobalValue &GV) {
Rafael Espindola4787ba32016-05-11 13:51:39 +0000548 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000549 "Global is external, but doesn't have external or weak linkage!", &GV);
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000550
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000551 Assert(GV.getAlignment() <= Value::MaximumAlignment,
552 "huge alignment values are unsupported", &GV);
553 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
554 "Only global variables can have appending linkage!", &GV);
Chris Lattner3ac483b2003-04-16 20:42:40 +0000555
556 if (GV.hasAppendingLinkage()) {
Chandler Carruth043949d2014-01-19 02:22:18 +0000557 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
David Blaikie60310f22015-05-08 00:42:26 +0000558 Assert(GVar && GVar->getValueType()->isArrayTy(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000559 "Only global arrays can have appending linkage!", GVar);
Chris Lattner3ac483b2003-04-16 20:42:40 +0000560 }
Peter Collingbourne46eb0f52015-07-05 20:52:40 +0000561
562 if (GV.isDeclarationForLinker())
563 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
Keno Fischer60f82a22016-01-14 22:20:56 +0000564
Ivan Krasin3b1c2602016-01-20 08:41:22 +0000565 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
Keno Fischer60f82a22016-01-14 22:20:56 +0000566 if (const Instruction *I = dyn_cast<Instruction>(V)) {
567 if (!I->getParent() || !I->getParent()->getParent())
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000568 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
569 I);
570 else if (I->getParent()->getParent()->getParent() != &M)
571 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
572 I->getParent()->getParent(),
Keno Fischer60f82a22016-01-14 22:20:56 +0000573 I->getParent()->getParent()->getParent());
574 return false;
575 } else if (const Function *F = dyn_cast<Function>(V)) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000576 if (F->getParent() != &M)
577 CheckFailed("Global is used by function in a different module", &GV, &M,
578 F, F->getParent());
Keno Fischer60f82a22016-01-14 22:20:56 +0000579 return false;
580 }
581 return true;
582 });
Chris Lattner3ac483b2003-04-16 20:42:40 +0000583}
584
Chandler Carruth043949d2014-01-19 02:22:18 +0000585void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
Chris Lattnerd79f3d52007-09-19 17:14:45 +0000586 if (GV.hasInitializer()) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000587 Assert(GV.getInitializer()->getType() == GV.getValueType(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000588 "Global variable initializer type does not match global "
589 "variable type!",
590 &GV);
Chris Lattner0aff0b22009-08-05 05:41:44 +0000591 // If the global has common linkage, it must have a zero initializer and
592 // cannot be constant.
593 if (GV.hasCommonLinkage()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000594 Assert(GV.getInitializer()->isNullValue(),
595 "'common' global must have a zero initializer!", &GV);
596 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
597 &GV);
598 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
Chris Lattner0aff0b22009-08-05 05:41:44 +0000599 }
Chris Lattnerd79f3d52007-09-19 17:14:45 +0000600 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000601
Nick Lewycky466d0c12011-04-08 07:30:21 +0000602 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
603 GV.getName() == "llvm.global_dtors")) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000604 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
605 "invalid linkage for intrinsic global variable", &GV);
Nick Lewycky466d0c12011-04-08 07:30:21 +0000606 // Don't worry about emitting an error for it not being an array,
607 // visitGlobalValue will complain on appending non-array.
David Blaikie60310f22015-05-08 00:42:26 +0000608 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
Chris Lattner229907c2011-07-18 04:54:35 +0000609 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
610 PointerType *FuncPtrTy =
Sanjoy Das4b54b7f2016-08-02 01:34:50 +0000611 FunctionType::get(Type::getVoidTy(Context), false)->getPointerTo();
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000612 // FIXME: Reject the 2-field form in LLVM 4.0.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000613 Assert(STy &&
614 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
615 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
616 STy->getTypeAtIndex(1) == FuncPtrTy,
617 "wrong type for intrinsic global variable", &GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000618 if (STy->getNumElements() == 3) {
619 Type *ETy = STy->getTypeAtIndex(2);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000620 Assert(ETy->isPointerTy() &&
621 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
622 "wrong type for intrinsic global variable", &GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000623 }
Nick Lewycky466d0c12011-04-08 07:30:21 +0000624 }
625 }
626
Rafael Espindola8bd2c222013-04-22 15:16:51 +0000627 if (GV.hasName() && (GV.getName() == "llvm.used" ||
Rafael Espindola9aadcc42013-07-19 18:44:51 +0000628 GV.getName() == "llvm.compiler.used")) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000629 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
630 "invalid linkage for intrinsic global variable", &GV);
David Blaikie0c28fd72015-05-20 21:46:30 +0000631 Type *GVType = GV.getValueType();
Rafael Espindola74f2e462013-04-22 14:58:02 +0000632 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
633 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000634 Assert(PTy, "wrong type for intrinsic global variable", &GV);
Rafael Espindola74f2e462013-04-22 14:58:02 +0000635 if (GV.hasInitializer()) {
Chandler Carruth043949d2014-01-19 02:22:18 +0000636 const Constant *Init = GV.getInitializer();
637 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000638 Assert(InitArray, "wrong initalizer for intrinsic global variable",
639 Init);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000640 for (Value *Op : InitArray->operands()) {
641 Value *V = Op->stripPointerCastsNoFollowAliases();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000642 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
643 isa<GlobalAlias>(V),
644 "invalid llvm.used member", V);
645 Assert(V->hasName(), "members of llvm.used must be named", V);
Rafael Espindola74f2e462013-04-22 14:58:02 +0000646 }
647 }
648 }
649 }
650
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000651 Assert(!GV.hasDLLImportStorageClass() ||
652 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
653 GV.hasAvailableExternallyLinkage(),
654 "Global is marked as dllimport, but not external", &GV);
Nico Rieck7157bb72014-01-14 15:22:47 +0000655
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000656 // Visit any debug info attachments.
657 SmallVector<MDNode *, 1> MDs;
658 GV.getMetadata(LLVMContext::MD_dbg, MDs);
Adrian Prantldc6e0162016-12-20 02:33:30 +0000659 for (auto *MD : MDs) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000660 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
661 visitDIGlobalVariableExpression(*GVE);
662 else
Adrian Prantlfd37e792017-02-23 23:54:29 +0000663 AssertDI(false, "!dbg attachment of global variable must be a "
664 "DIGlobalVariableExpression");
Adrian Prantldc6e0162016-12-20 02:33:30 +0000665 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000666
Matt Arsenault24b49c42013-07-31 17:49:08 +0000667 if (!GV.hasInitializer()) {
668 visitGlobalValue(GV);
669 return;
670 }
671
672 // Walk any aggregate initializers looking for bitcasts between address spaces
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000673 visitConstantExprsRecursively(GV.getInitializer());
Matt Arsenault24b49c42013-07-31 17:49:08 +0000674
Chris Lattnere3400652004-12-15 20:23:49 +0000675 visitGlobalValue(GV);
676}
677
Rafael Espindola64c1e182014-06-03 02:41:57 +0000678void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
679 SmallPtrSet<const GlobalAlias*, 4> Visited;
680 Visited.insert(&GA);
681 visitAliaseeSubExpr(Visited, GA, C);
682}
683
Craig Topper71b7b682014-08-21 05:55:13 +0000684void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
Rafael Espindola64c1e182014-06-03 02:41:57 +0000685 const GlobalAlias &GA, const Constant &C) {
686 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
Rafael Espindola89345772015-11-26 19:22:59 +0000687 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
688 &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000689
690 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000691 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000692
Sanjoy Das5ce32722016-04-08 00:48:30 +0000693 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias",
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000694 &GA);
Bob Wilson2f7cc012014-06-12 01:46:54 +0000695 } else {
696 // Only continue verifying subexpressions of GlobalAliases.
697 // Do not recurse into global initializers.
698 return;
Rafael Espindola64c1e182014-06-03 02:41:57 +0000699 }
700 }
701
702 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +0000703 visitConstantExprsRecursively(CE);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000704
705 for (const Use &U : C.operands()) {
706 Value *V = &*U;
707 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
708 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
709 else if (const auto *C2 = dyn_cast<Constant>(V))
710 visitAliaseeSubExpr(Visited, GA, *C2);
711 }
712}
713
Chandler Carruth043949d2014-01-19 02:22:18 +0000714void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000715 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
716 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
717 "weak_odr, or external linkage!",
718 &GA);
Rafael Espindola64c1e182014-06-03 02:41:57 +0000719 const Constant *Aliasee = GA.getAliasee();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000720 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
721 Assert(GA.getType() == Aliasee->getType(),
722 "Alias and aliasee types should match!", &GA);
Anton Korobeynikova50eed42008-05-08 23:11:06 +0000723
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000724 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
725 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
Matt Arsenault828b5652013-07-20 17:46:05 +0000726
Rafael Espindola64c1e182014-06-03 02:41:57 +0000727 visitAliaseeSubExpr(GA, *Aliasee);
Anton Korobeynikov25b2e822008-03-22 08:36:14 +0000728
Anton Korobeynikova97b6942007-04-25 14:27:10 +0000729 visitGlobalValue(GA);
730}
731
Chandler Carruth043949d2014-01-19 02:22:18 +0000732void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
Adrian Prantlb3510af2016-10-05 22:15:37 +0000733 // There used to be various other llvm.dbg.* nodes, but we don't support
734 // upgrading them and we want to reserve the namespace for future uses.
735 if (NMD.getName().startswith("llvm.dbg."))
736 AssertDI(NMD.getName() == "llvm.dbg.cu",
737 "unrecognized named metadata node in the llvm.dbg namespace",
738 &NMD);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000739 for (const MDNode *MD : NMD.operands()) {
Adrian Prantlb3510af2016-10-05 22:15:37 +0000740 if (NMD.getName() == "llvm.dbg.cu")
Adrian Prantl541a9c52016-05-06 19:26:47 +0000741 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
Duncan P. N. Exon Smithf238c782015-03-24 17:18:03 +0000742
Duncan P. N. Exon Smithd23ddbd2015-03-31 02:27:32 +0000743 if (!MD)
744 continue;
745
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000746 visitMDNode(*MD);
Duncan Sands76d62172010-04-29 16:10:30 +0000747 }
748}
749
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000750void Verifier::visitMDNode(const MDNode &MD) {
Duncan Sands76d62172010-04-29 16:10:30 +0000751 // Only visit each node once. Metadata can be mutually recursive, so this
752 // avoids infinite recursion here, as well as being an optimization.
David Blaikie70573dc2014-11-19 07:49:26 +0000753 if (!MDNodes.insert(&MD).second)
Duncan Sands76d62172010-04-29 16:10:30 +0000754 return;
755
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +0000756 switch (MD.getMetadataID()) {
757 default:
758 llvm_unreachable("Invalid MDNode subclass");
759 case Metadata::MDTupleKind:
760 break;
761#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
762 case Metadata::CLASS##Kind: \
763 visit##CLASS(cast<CLASS>(MD)); \
764 break;
765#include "llvm/IR/Metadata.def"
766 }
767
Sanjay Patel1f26bcf2016-02-25 16:44:27 +0000768 for (const Metadata *Op : MD.operands()) {
Duncan Sands76d62172010-04-29 16:10:30 +0000769 if (!Op)
770 continue;
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000771 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
772 &MD, Op);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000773 if (auto *N = dyn_cast<MDNode>(Op)) {
774 visitMDNode(*N);
Duncan Sands76d62172010-04-29 16:10:30 +0000775 continue;
776 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000777 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
778 visitValueAsMetadata(*V, nullptr);
779 continue;
780 }
Duncan Sands76d62172010-04-29 16:10:30 +0000781 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000782
783 // Check these last, so we diagnose problems in operands first.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000784 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
785 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000786}
787
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000788void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000789 Assert(MD.getValue(), "Expected valid value", &MD);
790 Assert(!MD.getValue()->getType()->isMetadataTy(),
791 "Unexpected metadata round-trip through values", &MD, MD.getValue());
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000792
793 auto *L = dyn_cast<LocalAsMetadata>(&MD);
794 if (!L)
795 return;
796
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000797 Assert(F, "function-local metadata used outside a function", L);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000798
799 // If this was an instruction, bb, or argument, verify that it is in the
800 // function that we expect.
801 Function *ActualF = nullptr;
802 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000803 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000804 ActualF = I->getParent()->getParent();
805 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
806 ActualF = BB->getParent();
807 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
808 ActualF = A->getParent();
809 assert(ActualF && "Unimplemented function local metadata case!");
810
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000811 Assert(ActualF == F, "function-local metadata used in wrong function", L);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000812}
813
Duncan P. N. Exon Smithac3ed7a2015-02-09 21:30:05 +0000814void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000815 Metadata *MD = MDV.getMetadata();
816 if (auto *N = dyn_cast<MDNode>(MD)) {
817 visitMDNode(*N);
818 return;
819 }
820
821 // Only visit each node once. Metadata can be mutually recursive, so this
822 // avoids infinite recursion here, as well as being an optimization.
823 if (!MDNodes.insert(MD).second)
824 return;
825
826 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
827 visitValueAsMetadata(*V, F);
Duncan Sands76d62172010-04-29 16:10:30 +0000828}
829
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000830static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
831static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
832static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +0000833
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000834void Verifier::visitDILocation(const DILocation &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000835 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
836 "location requires a valid scope", &N, N.getRawScope());
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +0000837 if (auto *IA = N.getRawInlinedAt())
Adrian Prantl541a9c52016-05-06 19:26:47 +0000838 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
Duncan P. N. Exon Smith692bdb92015-02-10 01:32:56 +0000839}
840
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000841void Verifier::visitGenericDINode(const GenericDINode &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000842 AssertDI(N.getTag(), "invalid tag", &N);
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +0000843}
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000844
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000845void Verifier::visitDIScope(const DIScope &N) {
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000846 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +0000847 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000848}
849
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000850void Verifier::visitDISubrange(const DISubrange &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000851 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
852 AssertDI(N.getCount() >= -1, "invalid subrange count", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000853}
854
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000855void Verifier::visitDIEnumerator(const DIEnumerator &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000856 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000857}
858
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000859void Verifier::visitDIBasicType(const DIBasicType &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000860 AssertDI(N.getTag() == dwarf::DW_TAG_base_type ||
861 N.getTag() == dwarf::DW_TAG_unspecified_type,
862 "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000863}
864
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000865void Verifier::visitDIDerivedType(const DIDerivedType &N) {
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000866 // Common scope checks.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000867 visitDIScope(N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000868
Adrian Prantl541a9c52016-05-06 19:26:47 +0000869 AssertDI(N.getTag() == dwarf::DW_TAG_typedef ||
870 N.getTag() == dwarf::DW_TAG_pointer_type ||
871 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
872 N.getTag() == dwarf::DW_TAG_reference_type ||
873 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
874 N.getTag() == dwarf::DW_TAG_const_type ||
875 N.getTag() == dwarf::DW_TAG_volatile_type ||
876 N.getTag() == dwarf::DW_TAG_restrict_type ||
Victor Leschuke1156c22016-10-31 19:09:38 +0000877 N.getTag() == dwarf::DW_TAG_atomic_type ||
Adrian Prantl541a9c52016-05-06 19:26:47 +0000878 N.getTag() == dwarf::DW_TAG_member ||
879 N.getTag() == dwarf::DW_TAG_inheritance ||
880 N.getTag() == dwarf::DW_TAG_friend,
881 "invalid tag", &N);
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000882 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000883 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
884 N.getRawExtraData());
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000885 }
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000886
Adrian Prantl541a9c52016-05-06 19:26:47 +0000887 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
888 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
889 N.getRawBaseType());
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +0000890
891 if (N.getDWARFAddressSpace()) {
892 AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
893 N.getTag() == dwarf::DW_TAG_reference_type,
894 "DWARF address space only applies to pointer or reference types",
895 &N);
896 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000897}
898
Duncan P. N. Exon Smith85866b2a2015-03-31 01:28:58 +0000899static bool hasConflictingReferenceFlags(unsigned Flags) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000900 return (Flags & DINode::FlagLValueReference) &&
901 (Flags & DINode::FlagRValueReference);
Duncan P. N. Exon Smith85866b2a2015-03-31 01:28:58 +0000902}
903
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000904void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
905 auto *Params = dyn_cast<MDTuple>(&RawParams);
Adrian Prantl541a9c52016-05-06 19:26:47 +0000906 AssertDI(Params, "invalid template params", &N, &RawParams);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000907 for (Metadata *Op : Params->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000908 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
909 &N, Params, Op);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000910 }
911}
912
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000913void Verifier::visitDICompositeType(const DICompositeType &N) {
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000914 // Common scope checks.
915 visitDIScope(N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000916
Adrian Prantl541a9c52016-05-06 19:26:47 +0000917 AssertDI(N.getTag() == dwarf::DW_TAG_array_type ||
918 N.getTag() == dwarf::DW_TAG_structure_type ||
919 N.getTag() == dwarf::DW_TAG_union_type ||
920 N.getTag() == dwarf::DW_TAG_enumeration_type ||
921 N.getTag() == dwarf::DW_TAG_class_type,
922 "invalid tag", &N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000923
Adrian Prantl541a9c52016-05-06 19:26:47 +0000924 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
925 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N,
926 N.getRawBaseType());
Duncan P. N. Exon Smith338aef02015-07-24 20:16:36 +0000927
Adrian Prantl541a9c52016-05-06 19:26:47 +0000928 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
929 "invalid composite elements", &N, N.getRawElements());
930 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
931 N.getRawVTableHolder());
932 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
933 "invalid reference flags", &N);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +0000934 if (auto *Params = N.getRawTemplateParams())
935 visitTemplateParams(N, *Params);
Duncan P. N. Exon Smithdbfc0102015-07-24 19:57:19 +0000936
937 if (N.getTag() == dwarf::DW_TAG_class_type ||
938 N.getTag() == dwarf::DW_TAG_union_type) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000939 AssertDI(N.getFile() && !N.getFile()->getFilename().empty(),
940 "class/union requires a filename", &N, N.getFile());
Duncan P. N. Exon Smithdbfc0102015-07-24 19:57:19 +0000941 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000942}
943
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000944void Verifier::visitDISubroutineType(const DISubroutineType &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000945 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
Duncan P. N. Exon Smitha8b3a1f2015-03-28 02:43:53 +0000946 if (auto *Types = N.getRawTypeArray()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000947 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
Duncan P. N. Exon Smitha8b3a1f2015-03-28 02:43:53 +0000948 for (Metadata *Ty : N.getTypeArray()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000949 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
Duncan P. N. Exon Smitha8b3a1f2015-03-28 02:43:53 +0000950 }
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000951 }
Adrian Prantl541a9c52016-05-06 19:26:47 +0000952 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
953 "invalid reference flags", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000954}
955
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000956void Verifier::visitDIFile(const DIFile &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000957 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
Amjad Aboud7faeecc2016-12-25 10:12:09 +0000958 AssertDI((N.getChecksumKind() != DIFile::CSK_None ||
959 N.getChecksum().empty()), "invalid checksum kind", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +0000960}
961
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000962void Verifier::visitDICompileUnit(const DICompileUnit &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000963 AssertDI(N.isDistinct(), "compile units must be distinct", &N);
964 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000965
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000966 // Don't bother verifying the compilation directory or producer string
967 // as those could be empty.
Adrian Prantl541a9c52016-05-06 19:26:47 +0000968 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
969 N.getRawFile());
970 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
971 N.getFile());
Duncan P. N. Exon Smithcd07efa12015-03-31 00:47:15 +0000972
Adrian Prantl541a9c52016-05-06 19:26:47 +0000973 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
974 "invalid emission kind", &N);
Adrian Prantlb939a252016-03-31 23:56:58 +0000975
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000976 if (auto *Array = N.getRawEnumTypes()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000977 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000978 for (Metadata *Op : N.getEnumTypes()->operands()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000979 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
Adrian Prantl541a9c52016-05-06 19:26:47 +0000980 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
981 "invalid enum type", &N, N.getEnumTypes(), Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000982 }
983 }
984 if (auto *Array = N.getRawRetainedTypes()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000985 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000986 for (Metadata *Op : N.getRetainedTypes()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000987 AssertDI(Op && (isa<DIType>(Op) ||
988 (isa<DISubprogram>(Op) &&
Eugene Zelenko3e3a0572016-08-13 00:50:41 +0000989 !cast<DISubprogram>(Op)->isDefinition())),
Adrian Prantl541a9c52016-05-06 19:26:47 +0000990 "invalid retained type", &N, Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000991 }
992 }
993 if (auto *Array = N.getRawGlobalVariables()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +0000994 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000995 for (Metadata *Op : N.getGlobalVariables()->operands()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000996 AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)),
997 "invalid global variable ref", &N, Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +0000998 }
999 }
1000 if (auto *Array = N.getRawImportedEntities()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001001 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001002 for (Metadata *Op : N.getImportedEntities()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001003 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref",
1004 &N, Op);
Duncan P. N. Exon Smith53855f02015-03-27 23:05:04 +00001005 }
1006 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00001007 if (auto *Array = N.getRawMacros()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001008 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001009 for (Metadata *Op : N.getMacros()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001010 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001011 }
1012 }
Adrian Prantlfaebbb02016-03-28 21:06:26 +00001013 CUVisited.insert(&N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001014}
1015
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001016void Verifier::visitDISubprogram(const DISubprogram &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001017 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1018 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
Davide Italiano5f1c87b2016-04-06 18:46:39 +00001019 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001020 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Justin Bognerefc3fbf2017-02-17 23:57:42 +00001021 else
1022 AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001023 if (auto *T = N.getRawType())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001024 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1025 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1026 N.getRawContainingType());
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +00001027 if (auto *Params = N.getRawTemplateParams())
1028 visitTemplateParams(N, *Params);
Adrian Prantl75819ae2016-04-15 15:57:41 +00001029 if (auto *S = N.getRawDeclaration())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001030 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1031 "invalid subprogram declaration", &N, S);
Duncan P. N. Exon Smith936c5632015-04-06 17:04:58 +00001032 if (auto *RawVars = N.getRawVariables()) {
1033 auto *Vars = dyn_cast<MDTuple>(RawVars);
Adrian Prantl541a9c52016-05-06 19:26:47 +00001034 AssertDI(Vars, "invalid variable list", &N, RawVars);
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001035 for (Metadata *Op : Vars->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001036 AssertDI(Op && isa<DILocalVariable>(Op), "invalid local variable", &N,
1037 Vars, Op);
Duncan P. N. Exon Smith869db502015-03-30 16:19:15 +00001038 }
1039 }
Adrian Prantl541a9c52016-05-06 19:26:47 +00001040 AssertDI(!hasConflictingReferenceFlags(N.getFlags()),
1041 "invalid reference flags", &N);
Duncan P. N. Exon Smith3ee34e12015-03-31 02:09:55 +00001042
Adrian Prantl75819ae2016-04-15 15:57:41 +00001043 auto *Unit = N.getRawUnit();
1044 if (N.isDefinition()) {
1045 // Subprogram definitions (not part of the type hierarchy).
Adrian Prantl541a9c52016-05-06 19:26:47 +00001046 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1047 AssertDI(Unit, "subprogram definitions must have a compile unit", &N);
1048 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
Adrian Prantl75819ae2016-04-15 15:57:41 +00001049 } else {
1050 // Subprogram declarations (part of the type hierarchy).
Adrian Prantl541a9c52016-05-06 19:26:47 +00001051 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N);
Adrian Prantl75819ae2016-04-15 15:57:41 +00001052 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001053}
1054
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001055void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001056 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1057 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1058 "invalid local scope", &N, N.getRawScope());
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001059}
1060
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001061void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1062 visitDILexicalBlockBase(N);
Duncan P. N. Exon Smith0e202b92015-03-30 16:37:48 +00001063
Adrian Prantl541a9c52016-05-06 19:26:47 +00001064 AssertDI(N.getLine() || !N.getColumn(),
1065 "cannot have column info without line info", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001066}
1067
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001068void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1069 visitDILexicalBlockBase(N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001070}
1071
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001072void Verifier::visitDINamespace(const DINamespace &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001073 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001074 if (auto *S = N.getRawScope())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001075 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001076}
1077
Amjad Abouda9bcf162015-12-10 12:56:35 +00001078void Verifier::visitDIMacro(const DIMacro &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001079 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1080 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1081 "invalid macinfo type", &N);
1082 AssertDI(!N.getName().empty(), "anonymous macro", &N);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00001083 if (!N.getValue().empty()) {
1084 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1085 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00001086}
1087
1088void Verifier::visitDIMacroFile(const DIMacroFile &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001089 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1090 "invalid macinfo type", &N);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001091 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001092 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001093
1094 if (auto *Array = N.getRawElements()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001095 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001096 for (Metadata *Op : N.getElements()->operands()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001097 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001098 }
1099 }
1100}
1101
Adrian Prantlab1243f2015-06-29 23:03:47 +00001102void Verifier::visitDIModule(const DIModule &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001103 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1104 AssertDI(!N.getName().empty(), "anonymous module", &N);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001105}
1106
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001107void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001108 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001109}
1110
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001111void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1112 visitDITemplateParameter(N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001113
Adrian Prantl541a9c52016-05-06 19:26:47 +00001114 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1115 &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001116}
1117
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001118void Verifier::visitDITemplateValueParameter(
1119 const DITemplateValueParameter &N) {
1120 visitDITemplateParameter(N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001121
Adrian Prantl541a9c52016-05-06 19:26:47 +00001122 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1123 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1124 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1125 "invalid tag", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001126}
1127
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001128void Verifier::visitDIVariable(const DIVariable &N) {
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001129 if (auto *S = N.getRawScope())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001130 AssertDI(isa<DIScope>(S), "invalid scope", &N, S);
1131 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001132 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001133 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001134}
1135
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001136void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001137 // Checks common to all variables.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001138 visitDIVariable(N);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001139
Adrian Prantl541a9c52016-05-06 19:26:47 +00001140 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1141 AssertDI(!N.getName().empty(), "missing global variable name", &N);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001142 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001143 AssertDI(isa<DIDerivedType>(Member),
1144 "invalid static data member declaration", &N, Member);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001145 }
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001146}
1147
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001148void Verifier::visitDILocalVariable(const DILocalVariable &N) {
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001149 // Checks common to all variables.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001150 visitDIVariable(N);
Duncan P. N. Exon Smith3d2afaa2015-03-27 17:29:58 +00001151
Adrian Prantl541a9c52016-05-06 19:26:47 +00001152 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1153 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1154 "local variable requires a valid scope", &N, N.getRawScope());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001155}
1156
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001157void Verifier::visitDIExpression(const DIExpression &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001158 AssertDI(N.isValid(), "invalid expression", &N);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001159}
1160
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001161void Verifier::visitDIGlobalVariableExpression(
1162 const DIGlobalVariableExpression &GVE) {
1163 AssertDI(GVE.getVariable(), "missing variable");
1164 if (auto *Var = GVE.getVariable())
1165 visitDIGlobalVariable(*Var);
1166 if (auto *Expr = GVE.getExpression())
1167 visitDIExpression(*Expr);
1168}
1169
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001170void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001171 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001172 if (auto *T = N.getRawType())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001173 AssertDI(isType(T), "invalid type ref", &N, T);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001174 if (auto *F = N.getRawFile())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001175 AssertDI(isa<DIFile>(F), "invalid file", &N, F);
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001176}
1177
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001178void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00001179 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module ||
1180 N.getTag() == dwarf::DW_TAG_imported_declaration,
1181 "invalid tag", &N);
Duncan P. N. Exon Smithf9b47752015-03-30 17:21:38 +00001182 if (auto *S = N.getRawScope())
Adrian Prantl541a9c52016-05-06 19:26:47 +00001183 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1184 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
1185 N.getRawEntity());
Duncan P. N. Exon Smithe4725be2015-02-10 01:40:40 +00001186}
Duncan P. N. Exon Smithb0a19ad2015-02-10 01:09:50 +00001187
David Majnemerdad0a642014-06-27 18:19:56 +00001188void Verifier::visitComdat(const Comdat &C) {
David Majnemerebc74112014-07-13 04:56:11 +00001189 // The Module is invalid if the GlobalValue has private linkage. Entities
1190 // with private linkage don't have entries in the symbol table.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001191 if (const GlobalValue *GV = M.getNamedValue(C.getName()))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001192 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1193 GV);
David Majnemerdad0a642014-06-27 18:19:56 +00001194}
1195
Chandler Carruth043949d2014-01-19 02:22:18 +00001196void Verifier::visitModuleIdents(const Module &M) {
Rafael Espindola0018a592013-10-16 01:49:05 +00001197 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1198 if (!Idents)
1199 return;
1200
1201 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1202 // Scan each llvm.ident entry and make sure that this requirement is met.
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001203 for (const MDNode *N : Idents->operands()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001204 Assert(N->getNumOperands() == 1,
1205 "incorrect number of operands in llvm.ident metadata", N);
1206 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1207 ("invalid value for llvm.ident metadata entry operand"
1208 "(the operand should be a string)"),
1209 N->getOperand(0));
Rafael Espindola0018a592013-10-16 01:49:05 +00001210 }
1211}
1212
Chandler Carruth043949d2014-01-19 02:22:18 +00001213void Verifier::visitModuleFlags(const Module &M) {
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001214 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1215 if (!Flags) return;
1216
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001217 // Scan each flag, and track the flags and requirements.
Chandler Carruth043949d2014-01-19 02:22:18 +00001218 DenseMap<const MDString*, const MDNode*> SeenIDs;
1219 SmallVector<const MDNode*, 16> Requirements;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001220 for (const MDNode *MDN : Flags->operands())
1221 visitModuleFlag(MDN, SeenIDs, Requirements);
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001222
1223 // Validate that the requirements in the module are valid.
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001224 for (const MDNode *Requirement : Requirements) {
Chandler Carruth043949d2014-01-19 02:22:18 +00001225 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001226 const Metadata *ReqValue = Requirement->getOperand(1);
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001227
Chandler Carruth043949d2014-01-19 02:22:18 +00001228 const MDNode *Op = SeenIDs.lookup(Flag);
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001229 if (!Op) {
1230 CheckFailed("invalid requirement on flag, flag is not present in module",
1231 Flag);
1232 continue;
1233 }
1234
1235 if (Op->getOperand(2) != ReqValue) {
1236 CheckFailed(("invalid requirement on flag, "
1237 "flag does not have the required value"),
1238 Flag);
1239 continue;
1240 }
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001241 }
1242}
1243
Chandler Carruth043949d2014-01-19 02:22:18 +00001244void
1245Verifier::visitModuleFlag(const MDNode *Op,
1246 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1247 SmallVectorImpl<const MDNode *> &Requirements) {
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001248 // Each module flag should have three arguments, the merge behavior (a
1249 // constant int), the flag ID (an MDString), and the value.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001250 Assert(Op->getNumOperands() == 3,
1251 "incorrect number of operands in module flag", Op);
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001252 Module::ModFlagBehavior MFB;
1253 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001254 Assert(
David Majnemerd7677e72015-02-11 09:13:06 +00001255 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001256 "invalid behavior operand in module flag (expected constant integer)",
1257 Op->getOperand(0));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001258 Assert(false,
1259 "invalid behavior operand in module flag (unexpected constant)",
1260 Op->getOperand(0));
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001261 }
David Majnemer04b4ed32015-02-16 08:14:22 +00001262 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001263 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1264 Op->getOperand(1));
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001265
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001266 // Sanity check the values for behaviors with additional requirements.
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001267 switch (MFB) {
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001268 case Module::Error:
1269 case Module::Warning:
1270 case Module::Override:
1271 // These behavior types accept any value.
1272 break;
1273
1274 case Module::Require: {
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001275 // The value should itself be an MDNode with two operands, a flag ID (an
1276 // MDString), and a value.
1277 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001278 Assert(Value && Value->getNumOperands() == 2,
1279 "invalid value for 'require' module flag (expected metadata pair)",
1280 Op->getOperand(2));
1281 Assert(isa<MDString>(Value->getOperand(0)),
1282 ("invalid value for 'require' module flag "
1283 "(first value operand should be a string)"),
1284 Value->getOperand(0));
Daniel Dunbarc36547d2013-01-15 20:52:06 +00001285
1286 // Append it to the list of requirements, to check once all module flags are
1287 // scanned.
1288 Requirements.push_back(Value);
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001289 break;
1290 }
1291
1292 case Module::Append:
1293 case Module::AppendUnique: {
1294 // These behavior types require the operand be an MDNode.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001295 Assert(isa<MDNode>(Op->getOperand(2)),
1296 "invalid value for 'append'-type module flag "
1297 "(expected a metadata node)",
1298 Op->getOperand(2));
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001299 break;
1300 }
1301 }
1302
1303 // Unless this is a "requires" flag, check the ID is unique.
Alexey Samsonovaf023ad2014-09-08 19:16:28 +00001304 if (MFB != Module::Require) {
Daniel Dunbard77d9fb2013-01-16 21:38:56 +00001305 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001306 Assert(Inserted,
1307 "module flag identifiers must be unique (or of 'require' type)", ID);
Daniel Dunbar25c4b572013-01-15 01:22:53 +00001308 }
1309}
1310
Reid Klecknera77172a2017-04-14 00:06:06 +00001311/// Return true if this attribute kind only applies to functions.
1312static bool isFuncOnlyAttr(Attribute::AttrKind Kind) {
1313 switch (Kind) {
1314 case Attribute::NoReturn:
1315 case Attribute::NoUnwind:
1316 case Attribute::NoInline:
1317 case Attribute::AlwaysInline:
1318 case Attribute::OptimizeForSize:
1319 case Attribute::StackProtect:
1320 case Attribute::StackProtectReq:
1321 case Attribute::StackProtectStrong:
1322 case Attribute::SafeStack:
1323 case Attribute::NoRedZone:
1324 case Attribute::NoImplicitFloat:
1325 case Attribute::Naked:
1326 case Attribute::InlineHint:
1327 case Attribute::StackAlignment:
1328 case Attribute::UWTable:
1329 case Attribute::NonLazyBind:
1330 case Attribute::ReturnsTwice:
1331 case Attribute::SanitizeAddress:
1332 case Attribute::SanitizeThread:
1333 case Attribute::SanitizeMemory:
1334 case Attribute::MinSize:
1335 case Attribute::NoDuplicate:
1336 case Attribute::Builtin:
1337 case Attribute::NoBuiltin:
1338 case Attribute::Cold:
1339 case Attribute::OptimizeNone:
1340 case Attribute::JumpTable:
1341 case Attribute::Convergent:
1342 case Attribute::ArgMemOnly:
1343 case Attribute::NoRecurse:
1344 case Attribute::InaccessibleMemOnly:
1345 case Attribute::InaccessibleMemOrArgMemOnly:
1346 case Attribute::AllocSize:
1347 return true;
1348 default:
1349 break;
1350 }
1351 return false;
1352}
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001353
Reid Klecknera77172a2017-04-14 00:06:06 +00001354/// Return true if this is a function attribute that can also appear on
1355/// arguments.
1356static bool isFuncOrArgAttr(Attribute::AttrKind Kind) {
1357 return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly ||
1358 Kind == Attribute::ReadNone;
1359}
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001360
Reid Klecknera77172a2017-04-14 00:06:06 +00001361void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction,
1362 const Value *V) {
1363 for (Attribute A : Attrs) {
1364 if (A.isStringAttribute())
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001365 continue;
1366
Reid Klecknera77172a2017-04-14 00:06:06 +00001367 if (isFuncOnlyAttr(A.getKindAsEnum())) {
1368 if (!IsFunction) {
1369 CheckFailed("Attribute '" + A.getAsString() +
1370 "' only applies to functions!",
1371 V);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001372 return;
1373 }
Reid Klecknera77172a2017-04-14 00:06:06 +00001374 } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) {
1375 CheckFailed("Attribute '" + A.getAsString() +
1376 "' does not apply to functions!",
1377 V);
Nick Lewyckyc2ec0722013-07-06 00:29:58 +00001378 return;
Bill Wendlinge3a60a92013-04-18 20:15:25 +00001379 }
1380 }
1381}
1382
Duncan Sandsc3a79922009-06-11 08:11:03 +00001383// VerifyParameterAttrs - Check the given attributes for an argument or return
Duncan Sands0009c442008-01-12 16:42:01 +00001384// value of the specified type. The value V is printed in error messages.
Reid Klecknera77172a2017-04-14 00:06:06 +00001385void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
1386 const Value *V) {
1387 if (!Attrs.hasAttributes())
Duncan Sands0009c442008-01-12 16:42:01 +00001388 return;
1389
Reid Klecknera77172a2017-04-14 00:06:06 +00001390 verifyAttributeTypes(Attrs, /*IsFunction=*/false, V);
Duncan Sandsc3a79922009-06-11 08:11:03 +00001391
Reid Klecknera534a382013-12-19 02:14:12 +00001392 // Check for mutually incompatible attributes. Only inreg is compatible with
1393 // sret.
1394 unsigned AttrCount = 0;
Reid Klecknera77172a2017-04-14 00:06:06 +00001395 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
1396 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
1397 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
1398 Attrs.hasAttribute(Attribute::InReg);
1399 AttrCount += Attrs.hasAttribute(Attribute::Nest);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001400 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1401 "and 'sret' are incompatible!",
1402 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001403
Reid Klecknera77172a2017-04-14 00:06:06 +00001404 Assert(!(Attrs.hasAttribute(Attribute::InAlloca) &&
1405 Attrs.hasAttribute(Attribute::ReadOnly)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001406 "Attributes "
1407 "'inalloca and readonly' are incompatible!",
1408 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001409
Reid Klecknera77172a2017-04-14 00:06:06 +00001410 Assert(!(Attrs.hasAttribute(Attribute::StructRet) &&
1411 Attrs.hasAttribute(Attribute::Returned)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001412 "Attributes "
1413 "'sret and returned' are incompatible!",
1414 V);
Stephen Lin6c70dc72013-04-23 16:31:56 +00001415
Reid Klecknera77172a2017-04-14 00:06:06 +00001416 Assert(!(Attrs.hasAttribute(Attribute::ZExt) &&
1417 Attrs.hasAttribute(Attribute::SExt)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001418 "Attributes "
1419 "'zeroext and signext' are incompatible!",
1420 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001421
Reid Klecknera77172a2017-04-14 00:06:06 +00001422 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1423 Attrs.hasAttribute(Attribute::ReadOnly)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001424 "Attributes "
1425 "'readnone and readonly' are incompatible!",
1426 V);
Bill Wendling9864a652012-10-09 20:11:19 +00001427
Reid Klecknera77172a2017-04-14 00:06:06 +00001428 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) &&
1429 Attrs.hasAttribute(Attribute::WriteOnly)),
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001430 "Attributes "
1431 "'readnone and writeonly' are incompatible!",
1432 V);
1433
Reid Klecknera77172a2017-04-14 00:06:06 +00001434 Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
1435 Attrs.hasAttribute(Attribute::WriteOnly)),
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001436 "Attributes "
1437 "'readonly and writeonly' are incompatible!",
1438 V);
1439
Reid Klecknera77172a2017-04-14 00:06:06 +00001440 Assert(!(Attrs.hasAttribute(Attribute::NoInline) &&
1441 Attrs.hasAttribute(Attribute::AlwaysInline)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001442 "Attributes "
1443 "'noinline and alwaysinline' are incompatible!",
1444 V);
Duncan Sands0009c442008-01-12 16:42:01 +00001445
Reid Klecknera77172a2017-04-14 00:06:06 +00001446 AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty);
1447 Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs),
1448 "Wrong types for attribute: " +
1449 AttributeSet::get(Context, IncompatibleAttrs).getAsString(),
1450 V);
Dan Gohman6d618722008-08-27 14:48:06 +00001451
Reid Klecknera534a382013-12-19 02:14:12 +00001452 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
Craig Toppere3dcce92015-08-01 22:20:21 +00001453 SmallPtrSet<Type*, 4> Visited;
Owen Anderson08f46e12015-03-13 06:41:26 +00001454 if (!PTy->getElementType()->isSized(&Visited)) {
Reid Klecknera77172a2017-04-14 00:06:06 +00001455 Assert(!Attrs.hasAttribute(Attribute::ByVal) &&
1456 !Attrs.hasAttribute(Attribute::InAlloca),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001457 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1458 V);
Reid Klecknera534a382013-12-19 02:14:12 +00001459 }
Manman Ren9bfd0d02016-04-01 21:41:15 +00001460 if (!isa<PointerType>(PTy->getElementType()))
Reid Klecknera77172a2017-04-14 00:06:06 +00001461 Assert(!Attrs.hasAttribute(Attribute::SwiftError),
Manman Ren9bfd0d02016-04-01 21:41:15 +00001462 "Attribute 'swifterror' only applies to parameters "
1463 "with pointer to pointer type!",
1464 V);
Reid Klecknera534a382013-12-19 02:14:12 +00001465 } else {
Reid Klecknera77172a2017-04-14 00:06:06 +00001466 Assert(!Attrs.hasAttribute(Attribute::ByVal),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001467 "Attribute 'byval' only applies to parameters with pointer type!",
1468 V);
Reid Klecknera77172a2017-04-14 00:06:06 +00001469 Assert(!Attrs.hasAttribute(Attribute::SwiftError),
Manman Ren9bfd0d02016-04-01 21:41:15 +00001470 "Attribute 'swifterror' only applies to parameters "
1471 "with pointer type!",
1472 V);
Reid Klecknera534a382013-12-19 02:14:12 +00001473 }
Duncan Sands0009c442008-01-12 16:42:01 +00001474}
1475
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001476// Check parameter attributes against a function type.
Duncan Sands8c582282007-12-21 19:19:01 +00001477// The value V is printed in error messages.
Reid Klecknerb5180542017-03-21 16:57:19 +00001478void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
Duncan Sands0009c442008-01-12 16:42:01 +00001479 const Value *V) {
Chris Lattner8a923e72008-03-12 17:45:29 +00001480 if (Attrs.isEmpty())
Duncan Sands8c582282007-12-21 19:19:01 +00001481 return;
1482
Duncan Sands8c582282007-12-21 19:19:01 +00001483 bool SawNest = false;
Stephen Linb8bd2322013-04-20 05:14:40 +00001484 bool SawReturned = false;
Reid Kleckner79418562014-05-09 22:32:13 +00001485 bool SawSRet = false;
Manman Renf46262e2016-03-29 17:37:21 +00001486 bool SawSwiftSelf = false;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001487 bool SawSwiftError = false;
Duncan Sands8c582282007-12-21 19:19:01 +00001488
Reid Klecknera77172a2017-04-14 00:06:06 +00001489 // Verify return value attributes.
1490 AttributeSet RetAttrs = Attrs.getRetAttributes();
1491 Assert((!RetAttrs.hasAttribute(Attribute::ByVal) &&
1492 !RetAttrs.hasAttribute(Attribute::Nest) &&
1493 !RetAttrs.hasAttribute(Attribute::StructRet) &&
1494 !RetAttrs.hasAttribute(Attribute::NoCapture) &&
1495 !RetAttrs.hasAttribute(Attribute::Returned) &&
1496 !RetAttrs.hasAttribute(Attribute::InAlloca) &&
1497 !RetAttrs.hasAttribute(Attribute::SwiftSelf) &&
1498 !RetAttrs.hasAttribute(Attribute::SwiftError)),
1499 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', "
1500 "'returned', 'swiftself', and 'swifterror' do not apply to return "
1501 "values!",
1502 V);
1503 Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) &&
1504 !RetAttrs.hasAttribute(Attribute::WriteOnly) &&
1505 !RetAttrs.hasAttribute(Attribute::ReadNone)),
1506 "Attribute '" + RetAttrs.getAsString() +
1507 "' does not apply to function returns",
1508 V);
1509 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
Duncan Sands8c582282007-12-21 19:19:01 +00001510
Reid Klecknera77172a2017-04-14 00:06:06 +00001511 // Verify parameter attributes.
1512 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1513 Type *Ty = FT->getParamType(i);
1514 AttributeSet ArgAttrs = Attrs.getParamAttributes(i);
Duncan Sandsc3a79922009-06-11 08:11:03 +00001515
Reid Klecknera77172a2017-04-14 00:06:06 +00001516 verifyParameterAttrs(ArgAttrs, Ty, V);
Duncan Sands8c582282007-12-21 19:19:01 +00001517
Reid Klecknera77172a2017-04-14 00:06:06 +00001518 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001519 Assert(!SawNest, "More than one parameter has attribute nest!", V);
Duncan Sands8c582282007-12-21 19:19:01 +00001520 SawNest = true;
1521 }
1522
Reid Klecknera77172a2017-04-14 00:06:06 +00001523 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001524 Assert(!SawReturned, "More than one parameter has attribute returned!",
1525 V);
1526 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
Reid Klecknera77172a2017-04-14 00:06:06 +00001527 "Incompatible argument and return types for 'returned' attribute",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001528 V);
Stephen Linb8bd2322013-04-20 05:14:40 +00001529 SawReturned = true;
1530 }
1531
Reid Klecknera77172a2017-04-14 00:06:06 +00001532 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001533 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
Reid Klecknera77172a2017-04-14 00:06:06 +00001534 Assert(i == 0 || i == 1,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001535 "Attribute 'sret' is not on first or second parameter!", V);
Reid Kleckner79418562014-05-09 22:32:13 +00001536 SawSRet = true;
1537 }
Reid Kleckner60d3a832014-01-16 22:59:24 +00001538
Reid Klecknera77172a2017-04-14 00:06:06 +00001539 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
Manman Renf46262e2016-03-29 17:37:21 +00001540 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
1541 SawSwiftSelf = true;
1542 }
1543
Reid Klecknera77172a2017-04-14 00:06:06 +00001544 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
Manman Ren9bfd0d02016-04-01 21:41:15 +00001545 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!",
1546 V);
1547 SawSwiftError = true;
1548 }
1549
Reid Klecknera77172a2017-04-14 00:06:06 +00001550 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
1551 Assert(i == FT->getNumParams() - 1,
1552 "inalloca isn't on the last parameter!", V);
Reid Kleckner60d3a832014-01-16 22:59:24 +00001553 }
Duncan Sands8c582282007-12-21 19:19:01 +00001554 }
Devang Patel9cc98122008-10-01 23:41:25 +00001555
Reid Klecknerb5180542017-03-21 16:57:19 +00001556 if (!Attrs.hasAttributes(AttributeList::FunctionIndex))
Bill Wendling77543892013-01-18 21:11:39 +00001557 return;
1558
Reid Klecknera77172a2017-04-14 00:06:06 +00001559 verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V);
Bill Wendling9864a652012-10-09 20:11:19 +00001560
Reid Klecknera77172a2017-04-14 00:06:06 +00001561 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1562 Attrs.hasFnAttribute(Attribute::ReadOnly)),
1563 "Attributes 'readnone and readonly' are incompatible!", V);
Bill Wendling9864a652012-10-09 20:11:19 +00001564
Reid Klecknera77172a2017-04-14 00:06:06 +00001565 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1566 Attrs.hasFnAttribute(Attribute::WriteOnly)),
1567 "Attributes 'readnone and writeonly' are incompatible!", V);
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001568
Reid Klecknera77172a2017-04-14 00:06:06 +00001569 Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) &&
1570 Attrs.hasFnAttribute(Attribute::WriteOnly)),
1571 "Attributes 'readonly and writeonly' are incompatible!", V);
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001572
Reid Klecknera77172a2017-04-14 00:06:06 +00001573 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1574 Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)),
1575 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
1576 "incompatible!",
1577 V);
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001578
Reid Klecknera77172a2017-04-14 00:06:06 +00001579 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) &&
1580 Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)),
1581 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001582
Reid Klecknera77172a2017-04-14 00:06:06 +00001583 Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) &&
1584 Attrs.hasFnAttribute(Attribute::AlwaysInline)),
1585 "Attributes 'noinline and alwaysinline' are incompatible!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001586
Reid Klecknera77172a2017-04-14 00:06:06 +00001587 if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) {
1588 Assert(Attrs.hasFnAttribute(Attribute::NoInline),
1589 "Attribute 'optnone' requires 'noinline'!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001590
Reid Klecknera77172a2017-04-14 00:06:06 +00001591 Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001592 "Attributes 'optsize and optnone' are incompatible!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001593
Reid Klecknera77172a2017-04-14 00:06:06 +00001594 Assert(!Attrs.hasFnAttribute(Attribute::MinSize),
1595 "Attributes 'minsize and optnone' are incompatible!", V);
Andrea Di Biagio377496b2013-08-23 11:53:55 +00001596 }
Tom Roeder44cb65f2014-06-05 19:29:43 +00001597
Reid Klecknera77172a2017-04-14 00:06:06 +00001598 if (Attrs.hasFnAttribute(Attribute::JumpTable)) {
Tom Roeder44cb65f2014-06-05 19:29:43 +00001599 const GlobalValue *GV = cast<GlobalValue>(V);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001600 Assert(GV->hasGlobalUnnamedAddr(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001601 "Attribute 'jumptable' requires 'unnamed_addr'", V);
Tom Roeder44cb65f2014-06-05 19:29:43 +00001602 }
George Burgess IV278199f2016-04-12 01:05:35 +00001603
Reid Klecknera77172a2017-04-14 00:06:06 +00001604 if (Attrs.hasFnAttribute(Attribute::AllocSize)) {
George Burgess IV278199f2016-04-12 01:05:35 +00001605 std::pair<unsigned, Optional<unsigned>> Args =
Reid Klecknerb5180542017-03-21 16:57:19 +00001606 Attrs.getAllocSizeArgs(AttributeList::FunctionIndex);
George Burgess IV278199f2016-04-12 01:05:35 +00001607
1608 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
1609 if (ParamNo >= FT->getNumParams()) {
1610 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
1611 return false;
1612 }
1613
1614 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
1615 CheckFailed("'allocsize' " + Name +
1616 " argument must refer to an integer parameter",
1617 V);
1618 return false;
1619 }
1620
1621 return true;
1622 };
1623
1624 if (!CheckParam("element size", Args.first))
1625 return;
1626
1627 if (Args.second && !CheckParam("number of elements", *Args.second))
1628 return;
1629 }
Duncan Sands8c582282007-12-21 19:19:01 +00001630}
1631
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001632void Verifier::verifyFunctionMetadata(
Benjamin Kramer7ab4fe32016-06-12 17:46:23 +00001633 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00001634 for (const auto &Pair : MDs) {
1635 if (Pair.first == LLVMContext::MD_prof) {
1636 MDNode *MD = Pair.second;
Dehao Chena60cdd32017-02-28 18:09:44 +00001637 Assert(MD->getNumOperands() >= 2,
1638 "!prof annotations should have no less than 2 operands", MD);
Diego Novillo2567f3d2015-05-13 15:13:45 +00001639
1640 // Check first operand.
1641 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1642 MD);
1643 Assert(isa<MDString>(MD->getOperand(0)),
1644 "expected string with name of the !prof annotation", MD);
1645 MDString *MDS = cast<MDString>(MD->getOperand(0));
1646 StringRef ProfName = MDS->getString();
1647 Assert(ProfName.equals("function_entry_count"),
1648 "first operand should be 'function_entry_count'", MD);
1649
1650 // Check second operand.
1651 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1652 MD);
1653 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1654 "expected integer argument to function_entry_count", MD);
1655 }
1656 }
1657}
1658
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00001659void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
1660 if (!ConstantExprVisited.insert(EntryC).second)
1661 return;
1662
1663 SmallVector<const Constant *, 16> Stack;
1664 Stack.push_back(EntryC);
1665
1666 while (!Stack.empty()) {
1667 const Constant *C = Stack.pop_back_val();
1668
1669 // Check this constant expression.
1670 if (const auto *CE = dyn_cast<ConstantExpr>(C))
1671 visitConstantExpr(CE);
1672
Keno Fischerf6d17b92016-01-14 22:42:02 +00001673 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
1674 // Global Values get visited separately, but we do need to make sure
1675 // that the global value is in the correct module
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001676 Assert(GV->getParent() == &M, "Referencing global in another module!",
1677 EntryC, &M, GV, GV->getParent());
Keno Fischerf6d17b92016-01-14 22:42:02 +00001678 continue;
1679 }
1680
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00001681 // Visit all sub-expressions.
1682 for (const Use &U : C->operands()) {
1683 const auto *OpC = dyn_cast<Constant>(U);
1684 if (!OpC)
1685 continue;
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00001686 if (!ConstantExprVisited.insert(OpC).second)
1687 continue;
1688 Stack.push_back(OpC);
1689 }
1690 }
1691}
1692
1693void Verifier::visitConstantExpr(const ConstantExpr *CE) {
Sanjoy Dase1129ee2016-08-02 02:55:57 +00001694 if (CE->getOpcode() == Instruction::BitCast)
1695 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1696 CE->getType()),
1697 "Invalid bitcast", CE);
Rafael Espindolaa4a94f12014-12-16 19:29:29 +00001698
Sanjoy Dase1129ee2016-08-02 02:55:57 +00001699 if (CE->getOpcode() == Instruction::IntToPtr ||
1700 CE->getOpcode() == Instruction::PtrToInt) {
1701 auto *PtrTy = CE->getOpcode() == Instruction::IntToPtr
1702 ? CE->getType()
1703 : CE->getOperand(0)->getType();
1704 StringRef Msg = CE->getOpcode() == Instruction::IntToPtr
1705 ? "inttoptr not supported for non-integral pointers"
1706 : "ptrtoint not supported for non-integral pointers";
1707 Assert(
1708 !DL.isNonIntegralPointerType(cast<PointerType>(PtrTy->getScalarType())),
1709 Msg);
1710 }
Matt Arsenault24b49c42013-07-31 17:49:08 +00001711}
1712
Reid Klecknerb5180542017-03-21 16:57:19 +00001713bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
Bill Wendling0aed1132013-01-30 06:54:41 +00001714 if (Attrs.getNumSlots() == 0)
Devang Patel82fed672008-09-23 22:35:17 +00001715 return true;
Nick Lewycky3fc89802009-09-07 20:44:51 +00001716
Devang Patel82fed672008-09-23 22:35:17 +00001717 unsigned LastSlot = Attrs.getNumSlots() - 1;
Bill Wendling25e65a62013-01-25 21:30:53 +00001718 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
Reid Klecknerb5180542017-03-21 16:57:19 +00001719 if (LastIndex <= Params ||
1720 (LastIndex == AttributeList::FunctionIndex &&
1721 (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
Devang Patel82fed672008-09-23 22:35:17 +00001722 return true;
Matt Arsenaultc4c92262013-07-20 17:46:00 +00001723
Devang Patel82fed672008-09-23 22:35:17 +00001724 return false;
1725}
Nick Lewycky3fc89802009-09-07 20:44:51 +00001726
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001727/// Verify that statepoint intrinsic is well formed.
1728void Verifier::verifyStatepoint(ImmutableCallSite CS) {
Philip Reames0285c742015-02-03 23:18:47 +00001729 assert(CS.getCalledFunction() &&
1730 CS.getCalledFunction()->getIntrinsicID() ==
1731 Intrinsic::experimental_gc_statepoint);
Philip Reames1ffa9372015-01-30 23:28:05 +00001732
Philip Reames0285c742015-02-03 23:18:47 +00001733 const Instruction &CI = *CS.getInstruction();
1734
Igor Laevsky39d662f2015-07-11 10:30:36 +00001735 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1736 !CS.onlyAccessesArgMemory(),
1737 "gc.statepoint must read and write all memory to preserve "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001738 "reordering restrictions required by safepoint semantics",
1739 &CI);
1740
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001741 const Value *IDV = CS.getArgument(0);
1742 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1743 &CI);
1744
1745 const Value *NumPatchBytesV = CS.getArgument(1);
1746 Assert(isa<ConstantInt>(NumPatchBytesV),
1747 "gc.statepoint number of patchable bytes must be a constant integer",
1748 &CI);
Sanjoy Das9af34eb2015-05-13 20:11:59 +00001749 const int64_t NumPatchBytes =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001750 cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1751 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1752 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1753 "positive",
1754 &CI);
1755
1756 const Value *Target = CS.getArgument(2);
Craig Toppere3dcce92015-08-01 22:20:21 +00001757 auto *PT = dyn_cast<PointerType>(Target->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001758 Assert(PT && PT->getElementType()->isFunctionTy(),
1759 "gc.statepoint callee must be of function pointer type", &CI, Target);
Quentin Colombet3e93ebe2015-05-09 00:02:06 +00001760 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
Philip Reames1ffa9372015-01-30 23:28:05 +00001761
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001762 const Value *NumCallArgsV = CS.getArgument(3);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001763 Assert(isa<ConstantInt>(NumCallArgsV),
1764 "gc.statepoint number of arguments to underlying call "
1765 "must be constant integer",
1766 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001767 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001768 Assert(NumCallArgs >= 0,
1769 "gc.statepoint number of arguments to underlying call "
1770 "must be positive",
1771 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001772 const int NumParams = (int)TargetFuncType->getNumParams();
1773 if (TargetFuncType->isVarArg()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001774 Assert(NumCallArgs >= NumParams,
1775 "gc.statepoint mismatch in number of vararg call args", &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001776
1777 // TODO: Remove this limitation
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001778 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1779 "gc.statepoint doesn't support wrapping non-void "
1780 "vararg functions yet",
1781 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001782 } else
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001783 Assert(NumCallArgs == NumParams,
1784 "gc.statepoint mismatch in number of call args", &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001785
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001786 const Value *FlagsV = CS.getArgument(4);
Pat Gavlincc0431d2015-05-08 18:07:42 +00001787 Assert(isa<ConstantInt>(FlagsV),
1788 "gc.statepoint flags must be constant integer", &CI);
1789 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1790 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1791 "unknown flag used in gc.statepoint flags argument", &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001792
1793 // Verify that the types of the call parameter arguments match
1794 // the type of the wrapped callee.
1795 for (int i = 0; i < NumParams; i++) {
1796 Type *ParamType = TargetFuncType->getParamType(i);
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001797 Type *ArgType = CS.getArgument(5 + i)->getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001798 Assert(ArgType == ParamType,
1799 "gc.statepoint call argument does not match wrapped "
1800 "function type",
1801 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001802 }
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001803
1804 const int EndCallArgsInx = 4 + NumCallArgs;
Pat Gavlincc0431d2015-05-08 18:07:42 +00001805
1806 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1807 Assert(isa<ConstantInt>(NumTransitionArgsV),
1808 "gc.statepoint number of transition arguments "
1809 "must be constant integer",
1810 &CI);
1811 const int NumTransitionArgs =
1812 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1813 Assert(NumTransitionArgs >= 0,
1814 "gc.statepoint number of transition arguments must be positive", &CI);
1815 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1816
1817 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001818 Assert(isa<ConstantInt>(NumDeoptArgsV),
1819 "gc.statepoint number of deoptimization arguments "
1820 "must be constant integer",
1821 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001822 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001823 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1824 "must be positive",
1825 &CI);
Philip Reames1ffa9372015-01-30 23:28:05 +00001826
Pat Gavlincc0431d2015-05-08 18:07:42 +00001827 const int ExpectedNumArgs =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00001828 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
Pat Gavlincc0431d2015-05-08 18:07:42 +00001829 Assert(ExpectedNumArgs <= (int)CS.arg_size(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001830 "gc.statepoint too few arguments according to length fields", &CI);
1831
Philip Reames1ffa9372015-01-30 23:28:05 +00001832 // Check that the only uses of this gc.statepoint are gc.result or
1833 // gc.relocate calls which are tied to this statepoint and thus part
1834 // of the same statepoint sequence
Philip Reames0285c742015-02-03 23:18:47 +00001835 for (const User *U : CI.users()) {
Philip Reames1ffa9372015-01-30 23:28:05 +00001836 const CallInst *Call = dyn_cast<const CallInst>(U);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001837 Assert(Call, "illegal use of statepoint token", &CI, U);
Philip Reames1ffa9372015-01-30 23:28:05 +00001838 if (!Call) continue;
Philip Reames92d1f0c2016-04-12 18:05:10 +00001839 Assert(isa<GCRelocateInst>(Call) || isa<GCResultInst>(Call),
Sanjoy Das25fb5bd2016-08-11 00:56:46 +00001840 "gc.result or gc.relocate are the only value uses "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001841 "of a gc.statepoint",
1842 &CI, U);
Philip Reames92d1f0c2016-04-12 18:05:10 +00001843 if (isa<GCResultInst>(Call)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001844 Assert(Call->getArgOperand(0) == &CI,
1845 "gc.result connected to wrong gc.statepoint", &CI, Call);
Manuel Jacob83eefa62016-01-05 04:03:00 +00001846 } else if (isa<GCRelocateInst>(Call)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001847 Assert(Call->getArgOperand(0) == &CI,
1848 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
Philip Reames1ffa9372015-01-30 23:28:05 +00001849 }
1850 }
1851
1852 // Note: It is legal for a single derived pointer to be listed multiple
1853 // times. It's non-optimal, but it is legal. It can also happen after
1854 // insertion if we strip a bitcast away.
1855 // Note: It is really tempting to check that each base is relocated and
1856 // that a derived pointer is never reused as a base pointer. This turns
1857 // out to be problematic since optimizations run after safepoint insertion
1858 // can recognize equality properties that the insertion logic doesn't know
1859 // about. See example statepoint.ll in the verifier subdirectory
1860}
1861
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001862void Verifier::verifyFrameRecoverIndices() {
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001863 for (auto &Counts : FrameEscapeInfo) {
1864 Function *F = Counts.first;
1865 unsigned EscapedObjectCount = Counts.second.first;
1866 unsigned MaxRecoveredIndex = Counts.second.second;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001867 Assert(MaxRecoveredIndex <= EscapedObjectCount,
Reid Kleckner60381792015-07-07 22:25:32 +00001868 "all indices passed to llvm.localrecover must be less than the "
1869 "number of arguments passed ot llvm.localescape in the parent "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001870 "function",
1871 F);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001872 }
1873}
1874
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00001875static Instruction *getSuccPad(TerminatorInst *Terminator) {
1876 BasicBlock *UnwindDest;
1877 if (auto *II = dyn_cast<InvokeInst>(Terminator))
1878 UnwindDest = II->getUnwindDest();
1879 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
1880 UnwindDest = CSI->getUnwindDest();
1881 else
1882 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
1883 return UnwindDest->getFirstNonPHI();
1884}
1885
1886void Verifier::verifySiblingFuncletUnwinds() {
1887 SmallPtrSet<Instruction *, 8> Visited;
1888 SmallPtrSet<Instruction *, 8> Active;
1889 for (const auto &Pair : SiblingFuncletInfo) {
1890 Instruction *PredPad = Pair.first;
1891 if (Visited.count(PredPad))
1892 continue;
1893 Active.insert(PredPad);
1894 TerminatorInst *Terminator = Pair.second;
1895 do {
1896 Instruction *SuccPad = getSuccPad(Terminator);
1897 if (Active.count(SuccPad)) {
1898 // Found a cycle; report error
1899 Instruction *CyclePad = SuccPad;
1900 SmallVector<Instruction *, 8> CycleNodes;
1901 do {
1902 CycleNodes.push_back(CyclePad);
1903 TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad];
1904 if (CycleTerminator != CyclePad)
1905 CycleNodes.push_back(CycleTerminator);
1906 CyclePad = getSuccPad(CycleTerminator);
1907 } while (CyclePad != SuccPad);
1908 Assert(false, "EH pads can't handle each other's exceptions",
1909 ArrayRef<Instruction *>(CycleNodes));
1910 }
1911 // Don't re-walk a node we've already checked
1912 if (!Visited.insert(SuccPad).second)
1913 break;
1914 // Walk to this successor if it has a map entry.
1915 PredPad = SuccPad;
1916 auto TermI = SiblingFuncletInfo.find(PredPad);
1917 if (TermI == SiblingFuncletInfo.end())
1918 break;
1919 Terminator = TermI->second;
1920 Active.insert(PredPad);
1921 } while (true);
1922 // Each node only has one successor, so we've walked all the active
1923 // nodes' successors.
1924 Active.clear();
1925 }
1926}
1927
Chris Lattner0e851da2002-04-18 20:37:37 +00001928// visitFunction - Verify that a function is ok.
Chris Lattnerd02f08d2002-02-20 17:55:43 +00001929//
Chandler Carruth043949d2014-01-19 02:22:18 +00001930void Verifier::visitFunction(const Function &F) {
Peter Collingbournebb738172016-06-06 23:21:27 +00001931 visitGlobalValue(F);
1932
Chris Lattner2ad5aa82005-05-08 22:27:09 +00001933 // Check function arguments.
Chris Lattner229907c2011-07-18 04:54:35 +00001934 FunctionType *FT = F.getFunctionType();
Chris Lattner45ffa212007-08-18 06:13:19 +00001935 unsigned NumArgs = F.arg_size();
Chris Lattneraf95e582002-04-13 22:48:46 +00001936
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00001937 Assert(&Context == &F.getContext(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001938 "Function context does not match Module context!", &F);
Nick Lewycky62f864d2010-02-15 21:52:04 +00001939
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001940 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1941 Assert(FT->getNumParams() == NumArgs,
1942 "# formal arguments must match # of arguments for function type!", &F,
1943 FT);
1944 Assert(F.getReturnType()->isFirstClassType() ||
1945 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1946 "Functions cannot return aggregate values!", &F);
Chris Lattneraf95e582002-04-13 22:48:46 +00001947
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001948 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1949 "Invalid struct return type!", &F);
Devang Patel9d9178592008-03-03 21:46:28 +00001950
Reid Klecknerb5180542017-03-21 16:57:19 +00001951 AttributeList Attrs = F.getAttributes();
Duncan Sandsb99f44a2008-01-11 22:36:48 +00001952
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001953 Assert(verifyAttributeCount(Attrs, FT->getNumParams()),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001954 "Attribute after last parameter!", &F);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00001955
Duncan Sands8c582282007-12-21 19:19:01 +00001956 // Check function attributes.
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00001957 verifyFunctionAttrs(FT, Attrs, &F);
Duncan Sands07c90662007-07-27 15:09:54 +00001958
Michael Gottesman41748d72013-06-27 00:25:01 +00001959 // On function declarations/definitions, we do not support the builtin
1960 // attribute. We do not check this in VerifyFunctionAttrs since that is
1961 // checking for Attributes that can/can not ever be on functions.
Reid Klecknera77172a2017-04-14 00:06:06 +00001962 Assert(!Attrs.hasFnAttribute(Attribute::Builtin),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001963 "Attribute 'builtin' can only be applied to a callsite.", &F);
Michael Gottesman41748d72013-06-27 00:25:01 +00001964
Chris Lattneref13ee32006-05-19 21:25:17 +00001965 // Check that this function meets the restrictions on this calling convention.
Reid Kleckner329d4a22014-08-29 21:25:28 +00001966 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1967 // restrictions can be lifted.
Chris Lattneref13ee32006-05-19 21:25:17 +00001968 switch (F.getCallingConv()) {
1969 default:
Chris Lattneref13ee32006-05-19 21:25:17 +00001970 case CallingConv::C:
1971 break;
Matt Arsenault33339682017-04-04 18:43:11 +00001972 case CallingConv::AMDGPU_KERNEL:
1973 case CallingConv::SPIR_KERNEL:
1974 Assert(F.getReturnType()->isVoidTy(),
1975 "Calling convention requires void return type", &F);
1976 LLVM_FALLTHROUGH;
1977 case CallingConv::AMDGPU_VS:
1978 case CallingConv::AMDGPU_GS:
1979 case CallingConv::AMDGPU_PS:
1980 case CallingConv::AMDGPU_CS:
1981 Assert(!F.hasStructRetAttr(),
1982 "Calling convention does not allow sret", &F);
1983 LLVM_FALLTHROUGH;
Chris Lattneref13ee32006-05-19 21:25:17 +00001984 case CallingConv::Fast:
1985 case CallingConv::Cold:
Elena Demikhovskyd6afb032012-10-24 14:46:16 +00001986 case CallingConv::Intel_OCL_BI:
Che-Liang Chiou29947902010-09-25 07:46:17 +00001987 case CallingConv::PTX_Kernel:
1988 case CallingConv::PTX_Device:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00001989 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1990 "perfect forwarding!",
1991 &F);
Chris Lattneref13ee32006-05-19 21:25:17 +00001992 break;
1993 }
Nick Lewycky3fc89802009-09-07 20:44:51 +00001994
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001995 bool isLLVMdotName = F.getName().size() >= 5 &&
1996 F.getName().substr(0, 5) == "llvm.";
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001997
Chris Lattneraf95e582002-04-13 22:48:46 +00001998 // Check that the argument values match the function type for this function...
Chris Lattner149376d2002-10-13 20:57:00 +00001999 unsigned i = 0;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002000 for (const Argument &Arg : F.args()) {
2001 Assert(Arg.getType() == FT->getParamType(i),
2002 "Argument value does not match function argument type!", &Arg,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002003 FT->getParamType(i));
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002004 Assert(Arg.getType()->isFirstClassType(),
2005 "Function arguments must have first-class types!", &Arg);
David Majnemerb611e3f2015-08-14 05:09:07 +00002006 if (!isLLVMdotName) {
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002007 Assert(!Arg.getType()->isMetadataTy(),
2008 "Function takes metadata but isn't an intrinsic", &Arg, &F);
2009 Assert(!Arg.getType()->isTokenTy(),
2010 "Function takes token but isn't an intrinsic", &Arg, &F);
David Majnemerb611e3f2015-08-14 05:09:07 +00002011 }
Manman Ren9bfd0d02016-04-01 21:41:15 +00002012
2013 // Check that swifterror argument is only used by loads and stores.
Reid Klecknerf021fab2017-04-13 23:12:13 +00002014 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
Manman Ren9bfd0d02016-04-01 21:41:15 +00002015 verifySwiftErrorValue(&Arg);
2016 }
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002017 ++i;
Dan Gohman4051bf42008-08-27 14:44:57 +00002018 }
Chris Lattneraf95e582002-04-13 22:48:46 +00002019
David Majnemerb611e3f2015-08-14 05:09:07 +00002020 if (!isLLVMdotName)
2021 Assert(!F.getReturnType()->isTokenTy(),
2022 "Functions returns a token but isn't an intrinsic", &F);
2023
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002024 // Get the function metadata attachments.
2025 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2026 F.getAllMetadata(MDs);
2027 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002028 verifyFunctionMetadata(MDs);
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002029
Keno Fischer2ac0c272015-11-16 05:13:30 +00002030 // Check validity of the personality function
2031 if (F.hasPersonalityFn()) {
2032 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
2033 if (Per)
2034 Assert(Per->getParent() == F.getParent(),
Keno Fischera6c4ce42015-12-01 19:06:36 +00002035 "Referencing personality function in another module!",
2036 &F, F.getParent(), Per, Per->getParent());
Keno Fischer2ac0c272015-11-16 05:13:30 +00002037 }
2038
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002039 if (F.isMaterializable()) {
2040 // Function has a body somewhere we can't see.
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002041 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
2042 MDs.empty() ? nullptr : MDs.front().second);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002043 } else if (F.isDeclaration()) {
Peter Collingbourne21521892016-06-21 23:42:48 +00002044 for (const auto &I : MDs) {
2045 AssertDI(I.first != LLVMContext::MD_dbg,
2046 "function declaration may not have a !dbg attachment", &F);
2047 Assert(I.first != LLVMContext::MD_prof,
2048 "function declaration may not have a !prof attachment", &F);
2049
2050 // Verify the metadata itself.
2051 visitMDNode(*I.second);
2052 }
David Majnemer7fddecc2015-06-17 20:52:32 +00002053 Assert(!F.hasPersonalityFn(),
2054 "Function declaration shouldn't have a personality routine", &F);
Chris Lattnerd79f3d52007-09-19 17:14:45 +00002055 } else {
Chris Lattnercb813312006-12-13 04:45:46 +00002056 // Verify that this function (which has a body) is not named "llvm.*". It
2057 // is not legal to define intrinsics.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002058 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002059
Chris Lattner149376d2002-10-13 20:57:00 +00002060 // Check the entry node
Chandler Carruth043949d2014-01-19 02:22:18 +00002061 const BasicBlock *Entry = &F.getEntryBlock();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002062 Assert(pred_empty(Entry),
2063 "Entry block to function must not have predecessors!", Entry);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002064
Chris Lattner27471742009-11-01 04:08:01 +00002065 // The address of the entry block cannot be taken, unless it is dead.
2066 if (Entry->hasAddressTaken()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002067 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
2068 "blockaddress may not be used with the entry block!", Entry);
Chris Lattner27471742009-11-01 04:08:01 +00002069 }
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002070
Peter Collingbourne6dbee002016-06-14 23:13:15 +00002071 unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002072 // Visit metadata attachments.
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002073 for (const auto &I : MDs) {
2074 // Verify that the attachment is legal.
2075 switch (I.first) {
2076 default:
2077 break;
2078 case LLVMContext::MD_dbg:
Peter Collingbourne382d81c2016-06-01 01:17:57 +00002079 ++NumDebugAttachments;
2080 AssertDI(NumDebugAttachments == 1,
2081 "function must have a single !dbg attachment", &F, I.second);
Adrian Prantl541a9c52016-05-06 19:26:47 +00002082 AssertDI(isa<DISubprogram>(I.second),
2083 "function !dbg attachment must be a subprogram", &F, I.second);
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002084 break;
Peter Collingbourne6dbee002016-06-14 23:13:15 +00002085 case LLVMContext::MD_prof:
2086 ++NumProfAttachments;
2087 Assert(NumProfAttachments == 1,
2088 "function must have a single !prof attachment", &F, I.second);
2089 break;
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002090 }
2091
2092 // Verify the metadata itself.
Duncan P. N. Exon Smith327e9bd2015-04-24 21:53:27 +00002093 visitMDNode(*I.second);
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00002094 }
Chris Lattner149376d2002-10-13 20:57:00 +00002095 }
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002096
Chris Lattner7730dcc2009-09-11 17:05:29 +00002097 // If this function is actually an intrinsic, verify that it is only used in
2098 // direct call/invokes, never having its "address taken".
Rafael Espindola257a3532016-01-15 19:00:20 +00002099 // Only do this if the module is materialized, otherwise we don't have all the
2100 // uses.
2101 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00002102 const User *U;
2103 if (F.hasAddressTaken(&U))
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00002104 Assert(false, "Invalid user of intrinsic instruction!", U);
Chris Lattner7730dcc2009-09-11 17:05:29 +00002105 }
Nico Rieck7157bb72014-01-14 15:22:47 +00002106
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002107 Assert(!F.hasDLLImportStorageClass() ||
2108 (F.isDeclaration() && F.hasExternalLinkage()) ||
2109 F.hasAvailableExternallyLinkage(),
2110 "Function is marked as dllimport, but not external.", &F);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002111
2112 auto *N = F.getSubprogram();
Adrian Prantl63d96952017-03-07 17:28:54 +00002113 HasDebugInfo = (N != nullptr);
Adrian Prantl39c6fa62017-03-07 17:50:51 +00002114 if (!HasDebugInfo)
Peter Collingbourned4bff302015-11-05 22:03:56 +00002115 return;
2116
2117 // Check that all !dbg attachments lead to back to N (or, at least, another
2118 // subprogram that describes the same function).
2119 //
2120 // FIXME: Check this incrementally while visiting !dbg attachments.
2121 // FIXME: Only check when N is the canonical subprogram for F.
2122 SmallPtrSet<const MDNode *, 32> Seen;
2123 for (auto &BB : F)
2124 for (auto &I : BB) {
2125 // Be careful about using DILocation here since we might be dealing with
2126 // broken code (this is the Verifier after all).
2127 DILocation *DL =
2128 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
2129 if (!DL)
2130 continue;
2131 if (!Seen.insert(DL).second)
2132 continue;
2133
2134 DILocalScope *Scope = DL->getInlinedAtScope();
2135 if (Scope && !Seen.insert(Scope).second)
2136 continue;
2137
2138 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
Keno Fischer0ef8ccf2015-12-06 23:05:38 +00002139
2140 // Scope and SP could be the same MDNode and we don't want to skip
2141 // validation in that case
2142 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002143 continue;
2144
2145 // FIXME: Once N is canonical, check "SP == &N".
Adrian Prantla2ef0472016-09-14 17:30:37 +00002146 AssertDI(SP->describes(&F),
2147 "!dbg attachment points at wrong subprogram for function", N, &F,
2148 &I, DL, Scope, SP);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002149 }
Chris Lattnerd02f08d2002-02-20 17:55:43 +00002150}
2151
Chris Lattner0e851da2002-04-18 20:37:37 +00002152// verifyBasicBlock - Verify that a basic block is well formed...
2153//
Chris Lattner069a7952002-06-25 15:56:27 +00002154void Verifier::visitBasicBlock(BasicBlock &BB) {
Chris Lattnerc9e79d02004-09-29 20:07:45 +00002155 InstsInThisBlock.clear();
2156
Alkis Evlogimenosbe526cf2004-12-04 02:30:42 +00002157 // Ensure that basic blocks have terminators!
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002158 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
Alkis Evlogimenosbe526cf2004-12-04 02:30:42 +00002159
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002160 // Check constraints that this basic block imposes on all of the PHI nodes in
2161 // it.
2162 if (isa<PHINode>(BB.front())) {
Chris Lattner59a8d2c2007-02-10 08:33:11 +00002163 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
2164 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002165 std::sort(Preds.begin(), Preds.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002166 PHINode *PN;
Chris Lattner307e1df2004-06-05 17:44:48 +00002167 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002168 // Ensure that PHI nodes have at least one entry!
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002169 Assert(PN->getNumIncomingValues() != 0,
2170 "PHI nodes must have at least one entry. If the block is dead, "
2171 "the PHI should be removed!",
2172 PN);
2173 Assert(PN->getNumIncomingValues() == Preds.size(),
2174 "PHINode should have one entry for each predecessor of its "
2175 "parent basic block!",
2176 PN);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002177
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002178 // Get and sort all incoming values in the PHI node...
Chris Lattner59a8d2c2007-02-10 08:33:11 +00002179 Values.clear();
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002180 Values.reserve(PN->getNumIncomingValues());
2181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2182 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
2183 PN->getIncomingValue(i)));
2184 std::sort(Values.begin(), Values.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002185
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002186 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2187 // Check to make sure that if there is more than one entry for a
2188 // particular basic block in this PHI node, that the incoming values are
2189 // all identical.
2190 //
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002191 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
2192 Values[i].second == Values[i - 1].second,
2193 "PHI node has multiple entries for the same basic block with "
2194 "different incoming values!",
2195 PN, Values[i].first, Values[i].second, Values[i - 1].second);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002196
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002197 // Check to make sure that the predecessors and PHI node entries are
2198 // matched up.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002199 Assert(Values[i].first == Preds[i],
2200 "PHI node entries do not match predecessors!", PN,
2201 Values[i].first, Preds[i]);
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002202 }
2203 }
2204 }
Adrian Prantl940257f2014-11-21 00:39:43 +00002205
2206 // Check that all instructions have their parent pointers set up correctly.
Zachary Turner8325a5c2014-11-21 01:19:09 +00002207 for (auto &I : BB)
2208 {
Adrian Prantl940257f2014-11-21 00:39:43 +00002209 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
Zachary Turner8325a5c2014-11-21 01:19:09 +00002210 }
Chris Lattner069a7952002-06-25 15:56:27 +00002211}
Chris Lattnerfbf5be52002-03-15 20:25:09 +00002212
Chris Lattner069a7952002-06-25 15:56:27 +00002213void Verifier::visitTerminatorInst(TerminatorInst &I) {
2214 // Ensure that terminators only exist at the end of the basic block.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002215 Assert(&I == I.getParent()->getTerminator(),
2216 "Terminator found in the middle of a basic block!", I.getParent());
Chris Lattner7af3ee92002-07-18 00:13:42 +00002217 visitInstruction(I);
Chris Lattner069a7952002-06-25 15:56:27 +00002218}
2219
Nick Lewycky1d9a8152010-02-15 22:09:09 +00002220void Verifier::visitBranchInst(BranchInst &BI) {
2221 if (BI.isConditional()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002222 Assert(BI.getCondition()->getType()->isIntegerTy(1),
2223 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
Nick Lewycky1d9a8152010-02-15 22:09:09 +00002224 }
2225 visitTerminatorInst(BI);
2226}
2227
Chris Lattner069a7952002-06-25 15:56:27 +00002228void Verifier::visitReturnInst(ReturnInst &RI) {
2229 Function *F = RI.getParent()->getParent();
Devang Patel59643e52008-02-23 00:35:18 +00002230 unsigned N = RI.getNumOperands();
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002231 if (F->getReturnType()->isVoidTy())
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002232 Assert(N == 0,
2233 "Found return instr that returns non-void in Function of void "
2234 "return type!",
2235 &RI, F->getReturnType());
Jay Foad11522092011-04-04 07:44:02 +00002236 else
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002237 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2238 "Function return type does not match operand "
2239 "type of return inst!",
2240 &RI, F->getReturnType());
Nick Lewycky3fc89802009-09-07 20:44:51 +00002241
Misha Brukman7eb05a12003-08-18 14:43:39 +00002242 // Check to make sure that the return value has necessary properties for
Chris Lattner069a7952002-06-25 15:56:27 +00002243 // terminators...
2244 visitTerminatorInst(RI);
Chris Lattnerd02f08d2002-02-20 17:55:43 +00002245}
2246
Chris Lattnerab5aa142004-05-21 16:47:21 +00002247void Verifier::visitSwitchInst(SwitchInst &SI) {
2248 // Check to make sure that all of the constants in the switch instruction
2249 // have the same type as the switched-on value.
Chris Lattner229907c2011-07-18 04:54:35 +00002250 Type *SwitchTy = SI.getCondition()->getType();
Bob Wilsone4077362013-09-09 19:14:35 +00002251 SmallPtrSet<ConstantInt*, 32> Constants;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002252 for (auto &Case : SI.cases()) {
2253 Assert(Case.getCaseValue()->getType() == SwitchTy,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002254 "Switch constants must all be same type as switch value!", &SI);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002255 Assert(Constants.insert(Case.getCaseValue()).second,
2256 "Duplicate integer as switch case", &SI, Case.getCaseValue());
Stepan Dyatkovskiye89dafd2012-05-21 10:44:40 +00002257 }
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002258
Chris Lattnerab5aa142004-05-21 16:47:21 +00002259 visitTerminatorInst(SI);
2260}
2261
Dan Gohmand0a1e3d2010-08-02 23:08:33 +00002262void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002263 Assert(BI.getAddress()->getType()->isPointerTy(),
2264 "Indirectbr operand must have pointer type!", &BI);
Dan Gohmand0a1e3d2010-08-02 23:08:33 +00002265 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002266 Assert(BI.getDestination(i)->getType()->isLabelTy(),
2267 "Indirectbr destinations must all have pointer type!", &BI);
Dan Gohmand0a1e3d2010-08-02 23:08:33 +00002268
2269 visitTerminatorInst(BI);
2270}
2271
Chris Lattner75648e72004-03-12 05:54:31 +00002272void Verifier::visitSelectInst(SelectInst &SI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002273 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2274 SI.getOperand(2)),
2275 "Invalid operands for select instruction!", &SI);
Chris Lattner88107952008-12-29 00:12:50 +00002276
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002277 Assert(SI.getTrueValue()->getType() == SI.getType(),
2278 "Select values must have same type as select instruction!", &SI);
Chris Lattnercde15fb2004-09-29 21:19:28 +00002279 visitInstruction(SI);
Chris Lattner75648e72004-03-12 05:54:31 +00002280}
2281
Misha Brukmanc566ca362004-03-02 00:22:19 +00002282/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2283/// a pass, if any exist, it's an error.
2284///
Chris Lattner903a25d2002-11-21 16:54:22 +00002285void Verifier::visitUserOp1(Instruction &I) {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00002286 Assert(false, "User-defined operators should not live outside of a pass!", &I);
Chris Lattner903a25d2002-11-21 16:54:22 +00002287}
Chris Lattner0e851da2002-04-18 20:37:37 +00002288
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002289void Verifier::visitTruncInst(TruncInst &I) {
2290 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002291 Type *SrcTy = I.getOperand(0)->getType();
2292 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002293
2294 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002295 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2296 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002297
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002298 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2299 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2300 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2301 "trunc source and destination must both be a vector or neither", &I);
2302 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002303
2304 visitInstruction(I);
2305}
2306
2307void Verifier::visitZExtInst(ZExtInst &I) {
2308 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002309 Type *SrcTy = I.getOperand(0)->getType();
2310 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002311
2312 // Get the size of the types in bits, we'll need this later
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002313 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2314 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2315 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2316 "zext source and destination must both be a vector or neither", &I);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002317 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2318 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002319
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002320 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002321
2322 visitInstruction(I);
2323}
2324
2325void Verifier::visitSExtInst(SExtInst &I) {
2326 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002327 Type *SrcTy = I.getOperand(0)->getType();
2328 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002329
2330 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002331 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2332 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002333
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002334 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2335 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2336 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2337 "sext source and destination must both be a vector or neither", &I);
2338 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002339
2340 visitInstruction(I);
2341}
2342
2343void Verifier::visitFPTruncInst(FPTruncInst &I) {
2344 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002345 Type *SrcTy = I.getOperand(0)->getType();
2346 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002347 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002348 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2349 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002350
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002351 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2352 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2353 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2354 "fptrunc source and destination must both be a vector or neither", &I);
2355 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002356
2357 visitInstruction(I);
2358}
2359
2360void Verifier::visitFPExtInst(FPExtInst &I) {
2361 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002362 Type *SrcTy = I.getOperand(0)->getType();
2363 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002364
2365 // Get the size of the types in bits, we'll need this later
Dan Gohman7ccc52f2009-06-15 22:12:54 +00002366 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2367 unsigned DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002368
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002369 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2370 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2371 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2372 "fpext source and destination must both be a vector or neither", &I);
2373 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002374
2375 visitInstruction(I);
2376}
2377
2378void Verifier::visitUIToFPInst(UIToFPInst &I) {
2379 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002380 Type *SrcTy = I.getOperand(0)->getType();
2381 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002382
Duncan Sands19d0b472010-02-16 11:11:14 +00002383 bool SrcVec = SrcTy->isVectorTy();
2384 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002385
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002386 Assert(SrcVec == DstVec,
2387 "UIToFP source and dest must both be vector or scalar", &I);
2388 Assert(SrcTy->isIntOrIntVectorTy(),
2389 "UIToFP source must be integer or integer vector", &I);
2390 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2391 &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002392
2393 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002394 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2395 cast<VectorType>(DestTy)->getNumElements(),
2396 "UIToFP source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002397
2398 visitInstruction(I);
2399}
2400
2401void Verifier::visitSIToFPInst(SIToFPInst &I) {
2402 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002403 Type *SrcTy = I.getOperand(0)->getType();
2404 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002405
Duncan Sands19d0b472010-02-16 11:11:14 +00002406 bool SrcVec = SrcTy->isVectorTy();
2407 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002408
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002409 Assert(SrcVec == DstVec,
2410 "SIToFP source and dest must both be vector or scalar", &I);
2411 Assert(SrcTy->isIntOrIntVectorTy(),
2412 "SIToFP source must be integer or integer vector", &I);
2413 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2414 &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002415
2416 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002417 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2418 cast<VectorType>(DestTy)->getNumElements(),
2419 "SIToFP source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002420
2421 visitInstruction(I);
2422}
2423
2424void Verifier::visitFPToUIInst(FPToUIInst &I) {
2425 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002426 Type *SrcTy = I.getOperand(0)->getType();
2427 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002428
Duncan Sands19d0b472010-02-16 11:11:14 +00002429 bool SrcVec = SrcTy->isVectorTy();
2430 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002431
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002432 Assert(SrcVec == DstVec,
2433 "FPToUI source and dest must both be vector or scalar", &I);
2434 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2435 &I);
2436 Assert(DestTy->isIntOrIntVectorTy(),
2437 "FPToUI result must be integer or integer vector", &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002438
2439 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002440 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2441 cast<VectorType>(DestTy)->getNumElements(),
2442 "FPToUI source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002443
2444 visitInstruction(I);
2445}
2446
2447void Verifier::visitFPToSIInst(FPToSIInst &I) {
2448 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002449 Type *SrcTy = I.getOperand(0)->getType();
2450 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002451
Duncan Sands19d0b472010-02-16 11:11:14 +00002452 bool SrcVec = SrcTy->isVectorTy();
2453 bool DstVec = DestTy->isVectorTy();
Nate Begemand4d45c22007-11-17 03:58:34 +00002454
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002455 Assert(SrcVec == DstVec,
2456 "FPToSI source and dest must both be vector or scalar", &I);
2457 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2458 &I);
2459 Assert(DestTy->isIntOrIntVectorTy(),
2460 "FPToSI result must be integer or integer vector", &I);
Nate Begemand4d45c22007-11-17 03:58:34 +00002461
2462 if (SrcVec && DstVec)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002463 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2464 cast<VectorType>(DestTy)->getNumElements(),
2465 "FPToSI source and dest vector length mismatch", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002466
2467 visitInstruction(I);
2468}
2469
2470void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2471 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002472 Type *SrcTy = I.getOperand(0)->getType();
2473 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002474
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002475 Assert(SrcTy->getScalarType()->isPointerTy(),
2476 "PtrToInt source must be pointer", &I);
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002477
2478 if (auto *PTy = dyn_cast<PointerType>(SrcTy->getScalarType()))
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00002479 Assert(!DL.isNonIntegralPointerType(PTy),
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002480 "ptrtoint not supported for non-integral pointers");
2481
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002482 Assert(DestTy->getScalarType()->isIntegerTy(),
2483 "PtrToInt result must be integral", &I);
2484 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2485 &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002486
2487 if (SrcTy->isVectorTy()) {
2488 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2489 VectorType *VDest = dyn_cast<VectorType>(DestTy);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002490 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2491 "PtrToInt Vector width mismatch", &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002492 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002493
2494 visitInstruction(I);
2495}
2496
2497void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2498 // Get the source and destination types
Chris Lattner229907c2011-07-18 04:54:35 +00002499 Type *SrcTy = I.getOperand(0)->getType();
2500 Type *DestTy = I.getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002501
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002502 Assert(SrcTy->getScalarType()->isIntegerTy(),
2503 "IntToPtr source must be an integral", &I);
2504 Assert(DestTy->getScalarType()->isPointerTy(),
2505 "IntToPtr result must be a pointer", &I);
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002506
2507 if (auto *PTy = dyn_cast<PointerType>(DestTy->getScalarType()))
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00002508 Assert(!DL.isNonIntegralPointerType(PTy),
Sanjoy Dasc6af5ea2016-07-28 23:43:38 +00002509 "inttoptr not supported for non-integral pointers");
2510
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002511 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2512 &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002513 if (SrcTy->isVectorTy()) {
2514 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2515 VectorType *VDest = dyn_cast<VectorType>(DestTy);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002516 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2517 "IntToPtr Vector width mismatch", &I);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002518 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002519 visitInstruction(I);
2520}
2521
2522void Verifier::visitBitCastInst(BitCastInst &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002523 Assert(
Rafael Espindolaa4a94f12014-12-16 19:29:29 +00002524 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2525 "Invalid bitcast", &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002526 visitInstruction(I);
2527}
2528
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002529void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2530 Type *SrcTy = I.getOperand(0)->getType();
2531 Type *DestTy = I.getType();
2532
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002533 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2534 &I);
2535 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2536 &I);
2537 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2538 "AddrSpaceCast must be between different address spaces", &I);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002539 if (SrcTy->isVectorTy())
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002540 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2541 "AddrSpaceCast vector pointer number of elements mismatch", &I);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002542 visitInstruction(I);
2543}
2544
Misha Brukmanc566ca362004-03-02 00:22:19 +00002545/// visitPHINode - Ensure that a PHI node is well formed.
2546///
Chris Lattner069a7952002-06-25 15:56:27 +00002547void Verifier::visitPHINode(PHINode &PN) {
2548 // Ensure that the PHI nodes are all grouped together at the top of the block.
2549 // This can be tested by checking whether the instruction before this is
Misha Brukmanfa100532003-10-10 17:54:14 +00002550 // either nonexistent (because this is begin()) or is a PHI node. If not,
Chris Lattner069a7952002-06-25 15:56:27 +00002551 // then there is some other instruction before a PHI.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002552 Assert(&PN == &PN.getParent()->front() ||
2553 isa<PHINode>(--BasicBlock::iterator(&PN)),
2554 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
Chris Lattner069a7952002-06-25 15:56:27 +00002555
David Majnemerb611e3f2015-08-14 05:09:07 +00002556 // Check that a PHI doesn't yield a Token.
2557 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2558
Nick Lewyckyb2b04672009-09-08 01:23:52 +00002559 // Check that all of the values of the PHI node have the same type as the
2560 // result, and that the incoming blocks are really basic blocks.
Pete Cooper833f34d2015-05-12 20:05:31 +00002561 for (Value *IncValue : PN.incoming_values()) {
2562 Assert(PN.getType() == IncValue->getType(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002563 "PHI node operands are not the same type as the result!", &PN);
Nick Lewyckyb2b04672009-09-08 01:23:52 +00002564 }
Chris Lattner3b93c912003-11-12 07:13:37 +00002565
Chris Lattnerdf9779c2003-10-05 17:44:18 +00002566 // All other PHI node constraints are checked in the visitBasicBlock method.
Chris Lattner0e851da2002-04-18 20:37:37 +00002567
2568 visitInstruction(PN);
2569}
2570
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002571void Verifier::verifyCallSite(CallSite CS) {
Duncan Sands8c582282007-12-21 19:19:01 +00002572 Instruction *I = CS.getInstruction();
2573
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002574 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2575 "Called function must be a pointer!", I);
Chris Lattner229907c2011-07-18 04:54:35 +00002576 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattner338a4622002-05-08 19:49:50 +00002577
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002578 Assert(FPTy->getElementType()->isFunctionTy(),
2579 "Called function is not pointer to function type!", I);
David Blaikie348de692015-04-23 21:36:23 +00002580
2581 Assert(FPTy->getElementType() == CS.getFunctionType(),
2582 "Called function is not the same type as the call!", I);
2583
2584 FunctionType *FTy = CS.getFunctionType();
Chris Lattner338a4622002-05-08 19:49:50 +00002585
2586 // Verify that the correct number of arguments are being passed
2587 if (FTy->isVarArg())
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002588 Assert(CS.arg_size() >= FTy->getNumParams(),
2589 "Called function requires more parameters than were provided!", I);
Chris Lattner338a4622002-05-08 19:49:50 +00002590 else
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002591 Assert(CS.arg_size() == FTy->getNumParams(),
2592 "Incorrect number of arguments passed to called function!", I);
Chris Lattner338a4622002-05-08 19:49:50 +00002593
Chris Lattner609de002010-05-10 20:58:42 +00002594 // Verify that all arguments to the call match the function type.
Chris Lattner338a4622002-05-08 19:49:50 +00002595 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002596 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2597 "Call parameter type does not match function signature!",
2598 CS.getArgument(i), FTy->getParamType(i), I);
Duncan Sands8c582282007-12-21 19:19:01 +00002599
Reid Klecknerb5180542017-03-21 16:57:19 +00002600 AttributeList Attrs = CS.getAttributes();
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002601
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002602 Assert(verifyAttributeCount(Attrs, CS.arg_size()),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002603 "Attribute after last parameter!", I);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002604
Duncan Sands8c582282007-12-21 19:19:01 +00002605 // Verify call attributes.
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002606 verifyFunctionAttrs(FTy, Attrs, I);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002607
David Majnemer91db08b2014-04-30 17:22:00 +00002608 // Conservatively check the inalloca argument.
2609 // We have a bug if we can find that there is an underlying alloca without
2610 // inalloca.
2611 if (CS.hasInAllocaArgument()) {
2612 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2613 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002614 Assert(AI->isUsedWithInAlloca(),
2615 "inalloca argument for call has mismatched alloca", AI, I);
David Majnemer91db08b2014-04-30 17:22:00 +00002616 }
2617
Manman Ren9bfd0d02016-04-01 21:41:15 +00002618 // For each argument of the callsite, if it has the swifterror argument,
Arnold Schwaighofer6c57f4f2016-09-10 19:42:53 +00002619 // make sure the underlying alloca/parameter it comes from has a swifterror as
2620 // well.
Manman Ren9bfd0d02016-04-01 21:41:15 +00002621 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2622 if (CS.paramHasAttr(i+1, Attribute::SwiftError)) {
2623 Value *SwiftErrorArg = CS.getArgument(i);
Arnold Schwaighofer6c57f4f2016-09-10 19:42:53 +00002624 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
Manman Ren9bfd0d02016-04-01 21:41:15 +00002625 Assert(AI->isSwiftError(),
2626 "swifterror argument for call has mismatched alloca", AI, I);
Arnold Schwaighofer6c57f4f2016-09-10 19:42:53 +00002627 continue;
2628 }
2629 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
2630 Assert(ArgI, "swifterror argument should come from an alloca or parameter", SwiftErrorArg, I);
2631 Assert(ArgI->hasSwiftErrorAttr(),
2632 "swifterror argument for call has mismatched parameter", ArgI, I);
Manman Ren9bfd0d02016-04-01 21:41:15 +00002633 }
2634
Stephen Linb8bd2322013-04-20 05:14:40 +00002635 if (FTy->isVarArg()) {
2636 // FIXME? is 'nest' even legal here?
2637 bool SawNest = false;
2638 bool SawReturned = false;
2639
Reid Klecknera77172a2017-04-14 00:06:06 +00002640 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
2641 if (Attrs.hasParamAttribute(Idx, Attribute::Nest))
Stephen Linb8bd2322013-04-20 05:14:40 +00002642 SawNest = true;
Reid Klecknera77172a2017-04-14 00:06:06 +00002643 if (Attrs.hasParamAttribute(Idx, Attribute::Returned))
Stephen Linb8bd2322013-04-20 05:14:40 +00002644 SawReturned = true;
2645 }
2646
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002647 // Check attributes on the varargs part.
Reid Klecknera77172a2017-04-14 00:06:06 +00002648 for (unsigned Idx = FTy->getNumParams(); Idx < CS.arg_size(); ++Idx) {
2649 Type *Ty = CS.getArgument(Idx)->getType();
2650 AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx);
2651 verifyParameterAttrs(ArgAttrs, Ty, I);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00002652
Reid Klecknera77172a2017-04-14 00:06:06 +00002653 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002654 Assert(!SawNest, "More than one parameter has attribute nest!", I);
Stephen Linb8bd2322013-04-20 05:14:40 +00002655 SawNest = true;
2656 }
2657
Reid Klecknera77172a2017-04-14 00:06:06 +00002658 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002659 Assert(!SawReturned, "More than one parameter has attribute returned!",
2660 I);
2661 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2662 "Incompatible argument and return types for 'returned' "
2663 "attribute",
2664 I);
Stephen Linb8bd2322013-04-20 05:14:40 +00002665 SawReturned = true;
2666 }
Duncan Sands0009c442008-01-12 16:42:01 +00002667
Reid Klecknera77172a2017-04-14 00:06:06 +00002668 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002669 "Attribute 'sret' cannot be used for vararg call arguments!", I);
Reid Kleckner60d3a832014-01-16 22:59:24 +00002670
Reid Klecknera77172a2017-04-14 00:06:06 +00002671 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
2672 Assert(Idx == CS.arg_size() - 1, "inalloca isn't on the last argument!",
2673 I);
Duncan Sandsb99f44a2008-01-11 22:36:48 +00002674 }
Stephen Linb8bd2322013-04-20 05:14:40 +00002675 }
Duncan Sands8c582282007-12-21 19:19:01 +00002676
Nick Lewyckyadbc2842009-05-30 05:06:04 +00002677 // Verify that there's no metadata unless it's a direct call to an intrinsic.
Craig Topperc6207612014-04-09 06:08:46 +00002678 if (CS.getCalledFunction() == nullptr ||
Chris Lattner609de002010-05-10 20:58:42 +00002679 !CS.getCalledFunction()->getName().startswith("llvm.")) {
David Majnemerb611e3f2015-08-14 05:09:07 +00002680 for (Type *ParamTy : FTy->params()) {
2681 Assert(!ParamTy->isMetadataTy(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002682 "Function has metadata parameter but isn't an intrinsic", I);
David Majnemerb611e3f2015-08-14 05:09:07 +00002683 Assert(!ParamTy->isTokenTy(),
2684 "Function has token parameter but isn't an intrinsic", I);
2685 }
Nick Lewyckyadbc2842009-05-30 05:06:04 +00002686 }
2687
David Majnemerb611e3f2015-08-14 05:09:07 +00002688 // Verify that indirect calls don't return tokens.
2689 if (CS.getCalledFunction() == nullptr)
2690 Assert(!FTy->getReturnType()->isTokenTy(),
2691 "Return type cannot be token for indirect call!");
2692
Philip Reamesa3c6f002015-06-26 21:39:44 +00002693 if (Function *F = CS.getCalledFunction())
2694 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
Philip Reames007561a2015-06-26 22:21:52 +00002695 visitIntrinsicCallSite(ID, CS);
Philip Reamesa3c6f002015-06-26 21:39:44 +00002696
Sanjoy Dasa34ce952016-01-20 19:50:25 +00002697 // Verify that a callsite has at most one "deopt", at most one "funclet" and
2698 // at most one "gc-transition" operand bundle.
2699 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
2700 FoundGCTransitionBundle = false;
Sanjoy Dascdafd842015-11-11 21:38:02 +00002701 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
David Majnemer3bb88c02015-12-15 21:27:27 +00002702 OperandBundleUse BU = CS.getOperandBundleAt(i);
2703 uint32_t Tag = BU.getTagID();
2704 if (Tag == LLVMContext::OB_deopt) {
Sanjoy Dascdafd842015-11-11 21:38:02 +00002705 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2706 FoundDeoptBundle = true;
Sanjoy Dasa34ce952016-01-20 19:50:25 +00002707 } else if (Tag == LLVMContext::OB_gc_transition) {
2708 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
2709 I);
2710 FoundGCTransitionBundle = true;
2711 } else if (Tag == LLVMContext::OB_funclet) {
David Majnemer3bb88c02015-12-15 21:27:27 +00002712 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I);
2713 FoundFuncletBundle = true;
2714 Assert(BU.Inputs.size() == 1,
2715 "Expected exactly one funclet bundle operand", I);
2716 Assert(isa<FuncletPadInst>(BU.Inputs.front()),
2717 "Funclet bundle operands should correspond to a FuncletPadInst",
2718 I);
2719 }
Sanjoy Dascdafd842015-11-11 21:38:02 +00002720 }
2721
Adrian Prantl93035c82016-04-24 22:23:13 +00002722 // Verify that each inlinable callsite of a debug-info-bearing function in a
2723 // debug-info-bearing function has a debug location attached to it. Failure to
2724 // do so causes assertion failures when the inliner sets up inline scope info.
2725 if (I->getFunction()->getSubprogram() && CS.getCalledFunction() &&
2726 CS.getCalledFunction()->getSubprogram())
Adrian Prantlfb80e792017-03-06 21:05:14 +00002727 AssertDI(I->getDebugLoc(), "inlinable function call in a function with "
2728 "debug info must have a !dbg location",
2729 I);
Adrian Prantl93035c82016-04-24 22:23:13 +00002730
Duncan Sands8c582282007-12-21 19:19:01 +00002731 visitInstruction(*I);
2732}
2733
Reid Kleckner5772b772014-04-24 20:14:34 +00002734/// Two types are "congruent" if they are identical, or if they are both pointer
2735/// types with different pointee types and the same address space.
2736static bool isTypeCongruent(Type *L, Type *R) {
2737 if (L == R)
2738 return true;
2739 PointerType *PL = dyn_cast<PointerType>(L);
2740 PointerType *PR = dyn_cast<PointerType>(R);
2741 if (!PL || !PR)
2742 return false;
2743 return PL->getAddressSpace() == PR->getAddressSpace();
2744}
2745
Reid Klecknerb5180542017-03-21 16:57:19 +00002746static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) {
Reid Klecknerd20c9702014-05-15 23:58:57 +00002747 static const Attribute::AttrKind ABIAttrs[] = {
2748 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
Manman Ren9bfd0d02016-04-01 21:41:15 +00002749 Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf,
2750 Attribute::SwiftError};
Reid Klecknerd20c9702014-05-15 23:58:57 +00002751 AttrBuilder Copy;
2752 for (auto AK : ABIAttrs) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00002753 if (Attrs.hasParamAttribute(I, AK))
Reid Klecknerd20c9702014-05-15 23:58:57 +00002754 Copy.addAttribute(AK);
2755 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00002756 if (Attrs.hasParamAttribute(I, Attribute::Alignment))
Reid Klecknerd20c9702014-05-15 23:58:57 +00002757 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2758 return Copy;
2759}
2760
Reid Kleckner5772b772014-04-24 20:14:34 +00002761void Verifier::verifyMustTailCall(CallInst &CI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002762 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002763
2764 // - The caller and callee prototypes must match. Pointer types of
2765 // parameters or return types may differ in pointee type, but not
2766 // address space.
2767 Function *F = CI.getParent()->getParent();
David Blaikie5bacf372015-04-24 21:16:07 +00002768 FunctionType *CallerTy = F->getFunctionType();
2769 FunctionType *CalleeTy = CI.getFunctionType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002770 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2771 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2772 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2773 "cannot guarantee tail call due to mismatched varargs", &CI);
2774 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2775 "cannot guarantee tail call due to mismatched return types", &CI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002776 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002777 Assert(
Reid Kleckner5772b772014-04-24 20:14:34 +00002778 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2779 "cannot guarantee tail call due to mismatched parameter types", &CI);
2780 }
2781
2782 // - The calling conventions of the caller and callee must match.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002783 Assert(F->getCallingConv() == CI.getCallingConv(),
2784 "cannot guarantee tail call due to mismatched calling conv", &CI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002785
2786 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2787 // returned, and inalloca, must match.
Reid Klecknerb5180542017-03-21 16:57:19 +00002788 AttributeList CallerAttrs = F->getAttributes();
2789 AttributeList CalleeAttrs = CI.getAttributes();
Reid Kleckner5772b772014-04-24 20:14:34 +00002790 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
Reid Klecknerd20c9702014-05-15 23:58:57 +00002791 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2792 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002793 Assert(CallerABIAttrs == CalleeABIAttrs,
2794 "cannot guarantee tail call due to mismatched ABI impacting "
2795 "function attributes",
2796 &CI, CI.getOperand(I));
Reid Kleckner5772b772014-04-24 20:14:34 +00002797 }
2798
2799 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2800 // or a pointer bitcast followed by a ret instruction.
2801 // - The ret instruction must return the (possibly bitcasted) value
2802 // produced by the call or void.
2803 Value *RetVal = &CI;
2804 Instruction *Next = CI.getNextNode();
2805
2806 // Handle the optional bitcast.
2807 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002808 Assert(BI->getOperand(0) == RetVal,
2809 "bitcast following musttail call must use the call", BI);
Reid Kleckner5772b772014-04-24 20:14:34 +00002810 RetVal = BI;
2811 Next = BI->getNextNode();
2812 }
2813
2814 // Check the return.
2815 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002816 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2817 &CI);
2818 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2819 "musttail call result must be returned", Ret);
Reid Kleckner5772b772014-04-24 20:14:34 +00002820}
2821
Duncan Sands8c582282007-12-21 19:19:01 +00002822void Verifier::visitCallInst(CallInst &CI) {
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002823 verifyCallSite(&CI);
Chris Lattner7af3ee92002-07-18 00:13:42 +00002824
Reid Kleckner5772b772014-04-24 20:14:34 +00002825 if (CI.isMustTailCall())
2826 verifyMustTailCall(CI);
Duncan Sands8c582282007-12-21 19:19:01 +00002827}
2828
2829void Verifier::visitInvokeInst(InvokeInst &II) {
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00002830 verifyCallSite(&II);
Bill Wendlingf4bbc042011-09-21 22:57:02 +00002831
David Majnemer654e1302015-07-31 17:58:14 +00002832 // Verify that the first non-PHI instruction of the unwind destination is an
2833 // exception handling instruction.
2834 Assert(
2835 II.getUnwindDest()->isEHPad(),
2836 "The unwind destination does not have an exception handling instruction!",
2837 &II);
Bill Wendlingf4bbc042011-09-21 22:57:02 +00002838
Dan Gohman9c6e1882010-08-02 23:09:14 +00002839 visitTerminatorInst(II);
Chris Lattner21ea83b2002-04-18 22:11:52 +00002840}
Chris Lattner0e851da2002-04-18 20:37:37 +00002841
Misha Brukmanc566ca362004-03-02 00:22:19 +00002842/// visitBinaryOperator - Check that both arguments to the binary operator are
2843/// of the same type!
2844///
Chris Lattner069a7952002-06-25 15:56:27 +00002845void Verifier::visitBinaryOperator(BinaryOperator &B) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002846 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2847 "Both operands to a binary operator are not of the same type!", &B);
Chris Lattner0e851da2002-04-18 20:37:37 +00002848
Reid Spencer2341c222007-02-02 02:16:23 +00002849 switch (B.getOpcode()) {
Dan Gohman5208dd82009-06-05 16:10:00 +00002850 // Check that integer arithmetic operators are only used with
2851 // integral operands.
2852 case Instruction::Add:
2853 case Instruction::Sub:
2854 case Instruction::Mul:
2855 case Instruction::SDiv:
2856 case Instruction::UDiv:
2857 case Instruction::SRem:
2858 case Instruction::URem:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002859 Assert(B.getType()->isIntOrIntVectorTy(),
2860 "Integer arithmetic operators only work with integral types!", &B);
2861 Assert(B.getType() == B.getOperand(0)->getType(),
2862 "Integer arithmetic operators must have same type "
2863 "for operands and result!",
2864 &B);
Dan Gohman5208dd82009-06-05 16:10:00 +00002865 break;
2866 // Check that floating-point arithmetic operators are only used with
2867 // floating-point operands.
2868 case Instruction::FAdd:
2869 case Instruction::FSub:
2870 case Instruction::FMul:
2871 case Instruction::FDiv:
2872 case Instruction::FRem:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002873 Assert(B.getType()->isFPOrFPVectorTy(),
2874 "Floating-point arithmetic operators only work with "
2875 "floating-point types!",
2876 &B);
2877 Assert(B.getType() == B.getOperand(0)->getType(),
2878 "Floating-point arithmetic operators must have same type "
2879 "for operands and result!",
2880 &B);
Dan Gohman5208dd82009-06-05 16:10:00 +00002881 break;
Chris Lattner1f419252002-09-09 20:26:04 +00002882 // Check that logical operators are only used with integral operands.
Reid Spencer2341c222007-02-02 02:16:23 +00002883 case Instruction::And:
2884 case Instruction::Or:
2885 case Instruction::Xor:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002886 Assert(B.getType()->isIntOrIntVectorTy(),
2887 "Logical operators only work with integral types!", &B);
2888 Assert(B.getType() == B.getOperand(0)->getType(),
2889 "Logical operators must have same type for operands and result!",
2890 &B);
Reid Spencer2341c222007-02-02 02:16:23 +00002891 break;
2892 case Instruction::Shl:
2893 case Instruction::LShr:
2894 case Instruction::AShr:
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002895 Assert(B.getType()->isIntOrIntVectorTy(),
2896 "Shifts only work with integral types!", &B);
2897 Assert(B.getType() == B.getOperand(0)->getType(),
2898 "Shift return type must be same as operands!", &B);
Reid Spencer2341c222007-02-02 02:16:23 +00002899 break;
Dan Gohman5208dd82009-06-05 16:10:00 +00002900 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00002901 llvm_unreachable("Unknown BinaryOperator opcode!");
Chris Lattner1f419252002-09-09 20:26:04 +00002902 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002903
Chris Lattner0e851da2002-04-18 20:37:37 +00002904 visitInstruction(B);
2905}
2906
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002907void Verifier::visitICmpInst(ICmpInst &IC) {
Reid Spencerd9436b62006-11-20 01:22:35 +00002908 // Check that the operands are the same type
Chris Lattner229907c2011-07-18 04:54:35 +00002909 Type *Op0Ty = IC.getOperand(0)->getType();
2910 Type *Op1Ty = IC.getOperand(1)->getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002911 Assert(Op0Ty == Op1Ty,
2912 "Both operands to ICmp instruction are not of the same type!", &IC);
Reid Spencerd9436b62006-11-20 01:22:35 +00002913 // Check that the operands are the right type
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002914 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2915 "Invalid operand types for ICmp instruction", &IC);
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002916 // Check that the predicate is valid.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002917 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2918 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2919 "Invalid predicate in ICmp instruction!", &IC);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00002920
Reid Spencerd9436b62006-11-20 01:22:35 +00002921 visitInstruction(IC);
2922}
2923
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002924void Verifier::visitFCmpInst(FCmpInst &FC) {
Reid Spencerd9436b62006-11-20 01:22:35 +00002925 // Check that the operands are the same type
Chris Lattner229907c2011-07-18 04:54:35 +00002926 Type *Op0Ty = FC.getOperand(0)->getType();
2927 Type *Op1Ty = FC.getOperand(1)->getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002928 Assert(Op0Ty == Op1Ty,
2929 "Both operands to FCmp instruction are not of the same type!", &FC);
Reid Spencerd9436b62006-11-20 01:22:35 +00002930 // Check that the operands are the right type
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002931 Assert(Op0Ty->isFPOrFPVectorTy(),
2932 "Invalid operand types for FCmp instruction", &FC);
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002933 // Check that the predicate is valid.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002934 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2935 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2936 "Invalid predicate in FCmp instruction!", &FC);
Nick Lewyckyc72d2852010-08-22 23:45:14 +00002937
Reid Spencerd9436b62006-11-20 01:22:35 +00002938 visitInstruction(FC);
2939}
2940
Robert Bocchino23004482006-01-10 19:05:34 +00002941void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002942 Assert(
2943 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2944 "Invalid extractelement operands!", &EI);
Robert Bocchino23004482006-01-10 19:05:34 +00002945 visitInstruction(EI);
2946}
2947
Robert Bocchinoca27f032006-01-17 20:07:22 +00002948void Verifier::visitInsertElementInst(InsertElementInst &IE) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002949 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2950 IE.getOperand(2)),
2951 "Invalid insertelement operands!", &IE);
Robert Bocchinoca27f032006-01-17 20:07:22 +00002952 visitInstruction(IE);
2953}
2954
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002955void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002956 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2957 SV.getOperand(2)),
2958 "Invalid shufflevector operands!", &SV);
Chris Lattnerbbe0a422006-04-08 01:18:18 +00002959 visitInstruction(SV);
2960}
2961
Chris Lattner069a7952002-06-25 15:56:27 +00002962void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Duncan Sandsa71ae962012-02-03 17:28:51 +00002963 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
Nadav Rotem3924cb02011-12-05 06:29:09 +00002964
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002965 Assert(isa<PointerType>(TargetTy),
2966 "GEP base pointer is not a vector or a vector of pointers", &GEP);
David Blaikiecc2cd582015-04-17 22:32:17 +00002967 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
Chris Lattner84d82c72007-02-10 08:30:29 +00002968 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
Chris Lattner229907c2011-07-18 04:54:35 +00002969 Type *ElTy =
David Blaikied288fb82015-03-30 21:41:43 +00002970 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002971 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
Nadav Rotem3924cb02011-12-05 06:29:09 +00002972
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002973 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
David Blaikied0a24822015-04-17 22:32:20 +00002974 GEP.getResultElementType() == ElTy,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00002975 "GEP is not of right type for indices!", &GEP, ElTy);
Duncan Sandse6beec62012-11-13 12:59:33 +00002976
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002977 if (GEP.getType()->isVectorTy()) {
Duncan Sandse6beec62012-11-13 12:59:33 +00002978 // Additional checks for vector GEPs.
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002979 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2980 if (GEP.getPointerOperandType()->isVectorTy())
2981 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2982 "Vector GEP result width doesn't match operand's", &GEP);
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00002983 for (Value *Idx : Idxs) {
2984 Type *IndexTy = Idx->getType();
Elena Demikhovsky37a4da82015-07-09 07:42:48 +00002985 if (IndexTy->isVectorTy()) {
2986 unsigned IndexWidth = IndexTy->getVectorNumElements();
2987 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2988 }
2989 Assert(IndexTy->getScalarType()->isIntegerTy(),
2990 "All GEP indices should be of integer type");
Duncan Sandse6beec62012-11-13 12:59:33 +00002991 }
Nadav Rotem3924cb02011-12-05 06:29:09 +00002992 }
Chris Lattnerd46bb6e2002-04-24 19:12:21 +00002993 visitInstruction(GEP);
2994}
2995
Rafael Espindolae3c5f3e2012-05-31 16:04:26 +00002996static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2997 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2998}
2999
Sanjoy Das26f28a22016-11-09 19:36:39 +00003000void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
3001 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
Philip Reamesbf9676f2014-10-20 23:52:07 +00003002 "precondition violation");
3003
3004 unsigned NumOperands = Range->getNumOperands();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003005 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003006 unsigned NumRanges = NumOperands / 2;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003007 Assert(NumRanges >= 1, "It should have at least one range!", Range);
3008
Philip Reamesbf9676f2014-10-20 23:52:07 +00003009 ConstantRange LastRange(1); // Dummy initial value
3010 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003011 ConstantInt *Low =
3012 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003013 Assert(Low, "The lower limit must be an integer!", Low);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003014 ConstantInt *High =
3015 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003016 Assert(High, "The upper limit must be an integer!", High);
3017 Assert(High->getType() == Low->getType() && High->getType() == Ty,
3018 "Range types must match instruction type!", &I);
3019
Philip Reamesbf9676f2014-10-20 23:52:07 +00003020 APInt HighV = High->getValue();
3021 APInt LowV = Low->getValue();
3022 ConstantRange CurRange(LowV, HighV);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003023 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
3024 "Range must not be empty!", Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003025 if (i != 0) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003026 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
3027 "Intervals are overlapping", Range);
3028 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
3029 Range);
3030 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
3031 Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003032 }
3033 LastRange = ConstantRange(LowV, HighV);
3034 }
3035 if (NumRanges > 2) {
3036 APInt FirstLow =
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003037 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
Philip Reamesbf9676f2014-10-20 23:52:07 +00003038 APInt FirstHigh =
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003039 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
Philip Reamesbf9676f2014-10-20 23:52:07 +00003040 ConstantRange FirstRange(FirstLow, FirstHigh);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003041 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
3042 "Intervals are overlapping", Range);
3043 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
3044 Range);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003045 }
3046}
3047
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003048void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
3049 unsigned Size = DL.getTypeSizeInBits(Ty);
JF Bastiend1fb5852015-12-17 22:09:19 +00003050 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
3051 Assert(!(Size & (Size - 1)),
3052 "atomic memory access' operand must have a power-of-two size", Ty, I);
3053}
3054
Chris Lattner069a7952002-06-25 15:56:27 +00003055void Verifier::visitLoadInst(LoadInst &LI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003056 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003057 Assert(PTy, "Load operand must be a pointer.", &LI);
David Blaikie15d9a4c2015-04-06 20:59:48 +00003058 Type *ElTy = LI.getType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003059 Assert(LI.getAlignment() <= Value::MaximumAlignment,
3060 "huge alignment values are unsupported", &LI);
Sanjoy Dasc2cf6ef2016-06-01 16:13:10 +00003061 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI);
Eli Friedman59b66882011-08-09 23:02:53 +00003062 if (LI.isAtomic()) {
JF Bastien800f87a2016-04-06 21:19:33 +00003063 Assert(LI.getOrdering() != AtomicOrdering::Release &&
3064 LI.getOrdering() != AtomicOrdering::AcquireRelease,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003065 "Load cannot have Release ordering", &LI);
3066 Assert(LI.getAlignment() != 0,
3067 "Atomic load must specify explicit alignment", &LI);
JF Bastiend1fb5852015-12-17 22:09:19 +00003068 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
3069 ElTy->isFloatingPointTy(),
3070 "atomic load operand must have integer, pointer, or floating point "
3071 "type!",
3072 ElTy, &LI);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003073 checkAtomicMemAccessSize(ElTy, &LI);
Eli Friedman59b66882011-08-09 23:02:53 +00003074 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003075 Assert(LI.getSynchScope() == CrossThread,
3076 "Non-atomic load cannot have SynchronizationScope specified", &LI);
Eli Friedman59b66882011-08-09 23:02:53 +00003077 }
Rafael Espindolaef9f5502012-03-24 00:14:51 +00003078
Chris Lattnerd46bb6e2002-04-24 19:12:21 +00003079 visitInstruction(LI);
3080}
3081
Chris Lattner069a7952002-06-25 15:56:27 +00003082void Verifier::visitStoreInst(StoreInst &SI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003083 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003084 Assert(PTy, "Store operand must be a pointer.", &SI);
Chris Lattner229907c2011-07-18 04:54:35 +00003085 Type *ElTy = PTy->getElementType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003086 Assert(ElTy == SI.getOperand(0)->getType(),
3087 "Stored value type does not match pointer operand type!", &SI, ElTy);
3088 Assert(SI.getAlignment() <= Value::MaximumAlignment,
3089 "huge alignment values are unsupported", &SI);
Sanjoy Dasc2cf6ef2016-06-01 16:13:10 +00003090 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI);
Eli Friedman59b66882011-08-09 23:02:53 +00003091 if (SI.isAtomic()) {
JF Bastien800f87a2016-04-06 21:19:33 +00003092 Assert(SI.getOrdering() != AtomicOrdering::Acquire &&
3093 SI.getOrdering() != AtomicOrdering::AcquireRelease,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003094 "Store cannot have Acquire ordering", &SI);
3095 Assert(SI.getAlignment() != 0,
3096 "Atomic store must specify explicit alignment", &SI);
JF Bastiend1fb5852015-12-17 22:09:19 +00003097 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
3098 ElTy->isFloatingPointTy(),
3099 "atomic store operand must have integer, pointer, or floating point "
3100 "type!",
3101 ElTy, &SI);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003102 checkAtomicMemAccessSize(ElTy, &SI);
Eli Friedman59b66882011-08-09 23:02:53 +00003103 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003104 Assert(SI.getSynchScope() == CrossThread,
3105 "Non-atomic store cannot have SynchronizationScope specified", &SI);
Eli Friedman59b66882011-08-09 23:02:53 +00003106 }
Chris Lattnerd46bb6e2002-04-24 19:12:21 +00003107 visitInstruction(SI);
3108}
3109
Manman Ren9bfd0d02016-04-01 21:41:15 +00003110/// Check that SwiftErrorVal is used as a swifterror argument in CS.
3111void Verifier::verifySwiftErrorCallSite(CallSite CS,
3112 const Value *SwiftErrorVal) {
3113 unsigned Idx = 0;
3114 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3115 I != E; ++I, ++Idx) {
3116 if (*I == SwiftErrorVal) {
3117 Assert(CS.paramHasAttr(Idx+1, Attribute::SwiftError),
3118 "swifterror value when used in a callsite should be marked "
3119 "with swifterror attribute",
3120 SwiftErrorVal, CS);
3121 }
3122 }
3123}
3124
3125void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
3126 // Check that swifterror value is only used by loads, stores, or as
3127 // a swifterror argument.
3128 for (const User *U : SwiftErrorVal->users()) {
3129 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3130 isa<InvokeInst>(U),
3131 "swifterror value can only be loaded and stored from, or "
3132 "as a swifterror argument!",
3133 SwiftErrorVal, U);
3134 // If it is used by a store, check it is the second operand.
3135 if (auto StoreI = dyn_cast<StoreInst>(U))
3136 Assert(StoreI->getOperand(1) == SwiftErrorVal,
3137 "swifterror value should be the second operand when used "
3138 "by stores", SwiftErrorVal, U);
3139 if (auto CallI = dyn_cast<CallInst>(U))
3140 verifySwiftErrorCallSite(const_cast<CallInst*>(CallI), SwiftErrorVal);
3141 if (auto II = dyn_cast<InvokeInst>(U))
3142 verifySwiftErrorCallSite(const_cast<InvokeInst*>(II), SwiftErrorVal);
3143 }
3144}
3145
Victor Hernandez8acf2952009-10-23 21:09:37 +00003146void Verifier::visitAllocaInst(AllocaInst &AI) {
Craig Toppere3dcce92015-08-01 22:20:21 +00003147 SmallPtrSet<Type*, 4> Visited;
Chris Lattner229907c2011-07-18 04:54:35 +00003148 PointerType *PTy = AI.getType();
Matt Arsenault3c1fc762017-04-10 22:27:50 +00003149 // TODO: Relax this restriction?
3150 Assert(PTy->getAddressSpace() == DL.getAllocaAddrSpace(),
3151 "Allocation instruction pointer not in the stack address space!",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003152 &AI);
David Blaikie5bacf372015-04-24 21:16:07 +00003153 Assert(AI.getAllocatedType()->isSized(&Visited),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003154 "Cannot allocate unsized type", &AI);
3155 Assert(AI.getArraySize()->getType()->isIntegerTy(),
3156 "Alloca array size must have integer type", &AI);
3157 Assert(AI.getAlignment() <= Value::MaximumAlignment,
3158 "huge alignment values are unsupported", &AI);
Reid Klecknera534a382013-12-19 02:14:12 +00003159
Manman Ren9bfd0d02016-04-01 21:41:15 +00003160 if (AI.isSwiftError()) {
3161 verifySwiftErrorValue(&AI);
3162 }
3163
Christopher Lamb55c6d4f2007-12-17 01:00:21 +00003164 visitInstruction(AI);
3165}
3166
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003167void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
Tim Northovere94a5182014-03-11 10:48:52 +00003168
3169 // FIXME: more conditions???
JF Bastien800f87a2016-04-06 21:19:33 +00003170 Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003171 "cmpxchg instructions must be atomic.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003172 Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003173 "cmpxchg instructions must be atomic.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003174 Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003175 "cmpxchg instructions cannot be unordered.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003176 Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003177 "cmpxchg instructions cannot be unordered.", &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003178 Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()),
3179 "cmpxchg instructions failure argument shall be no stronger than the "
3180 "success argument",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003181 &CXI);
JF Bastien800f87a2016-04-06 21:19:33 +00003182 Assert(CXI.getFailureOrdering() != AtomicOrdering::Release &&
3183 CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003184 "cmpxchg failure ordering cannot include release semantics", &CXI);
Tim Northovere94a5182014-03-11 10:48:52 +00003185
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003186 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003187 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003188 Type *ElTy = PTy->getElementType();
Philip Reames1960cfd2016-02-19 00:06:41 +00003189 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy(),
3190 "cmpxchg operand must have integer or pointer type",
3191 ElTy, &CXI);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003192 checkAtomicMemAccessSize(ElTy, &CXI);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003193 Assert(ElTy == CXI.getOperand(1)->getType(),
3194 "Expected value type does not match pointer operand type!", &CXI,
3195 ElTy);
3196 Assert(ElTy == CXI.getOperand(2)->getType(),
3197 "Stored value type does not match pointer operand type!", &CXI, ElTy);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003198 visitInstruction(CXI);
3199}
3200
3201void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
JF Bastien800f87a2016-04-06 21:19:33 +00003202 Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003203 "atomicrmw instructions must be atomic.", &RMWI);
JF Bastien800f87a2016-04-06 21:19:33 +00003204 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered,
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003205 "atomicrmw instructions cannot be unordered.", &RMWI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003206 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003207 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003208 Type *ElTy = PTy->getElementType();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003209 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
3210 &RMWI, ElTy);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003211 checkAtomicMemAccessSize(ElTy, &RMWI);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003212 Assert(ElTy == RMWI.getOperand(1)->getType(),
3213 "Argument value type does not match pointer operand type!", &RMWI,
3214 ElTy);
3215 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
3216 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
3217 "Invalid binary operation!", &RMWI);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00003218 visitInstruction(RMWI);
3219}
3220
Eli Friedmanfee02c62011-07-25 23:16:38 +00003221void Verifier::visitFenceInst(FenceInst &FI) {
3222 const AtomicOrdering Ordering = FI.getOrdering();
JF Bastien800f87a2016-04-06 21:19:33 +00003223 Assert(Ordering == AtomicOrdering::Acquire ||
3224 Ordering == AtomicOrdering::Release ||
3225 Ordering == AtomicOrdering::AcquireRelease ||
3226 Ordering == AtomicOrdering::SequentiallyConsistent,
3227 "fence instructions may only have acquire, release, acq_rel, or "
3228 "seq_cst ordering.",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003229 &FI);
Eli Friedmanfee02c62011-07-25 23:16:38 +00003230 visitInstruction(FI);
3231}
3232
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003233void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003234 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
3235 EVI.getIndices()) == EVI.getType(),
3236 "Invalid ExtractValueInst operands!", &EVI);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00003237
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003238 visitInstruction(EVI);
Devang Patel295711f2008-02-19 22:15:16 +00003239}
3240
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003241void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003242 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
3243 IVI.getIndices()) ==
3244 IVI.getOperand(1)->getType(),
3245 "Invalid InsertValueInst operands!", &IVI);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00003246
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003247 visitInstruction(IVI);
3248}
Chris Lattner0e851da2002-04-18 20:37:37 +00003249
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003250static Value *getParentPad(Value *EHPad) {
3251 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3252 return FPI->getParentPad();
3253
3254 return cast<CatchSwitchInst>(EHPad)->getParentPad();
3255}
3256
David Majnemer85a549d2015-08-11 02:48:30 +00003257void Verifier::visitEHPadPredecessors(Instruction &I) {
3258 assert(I.isEHPad());
Bill Wendlingfae14752011-08-12 20:24:12 +00003259
David Majnemer85a549d2015-08-11 02:48:30 +00003260 BasicBlock *BB = I.getParent();
3261 Function *F = BB->getParent();
3262
3263 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
3264
3265 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3266 // The landingpad instruction defines its parent as a landing pad block. The
3267 // landing pad block may be branched to only by the unwind edge of an
3268 // invoke.
3269 for (BasicBlock *PredBB : predecessors(BB)) {
3270 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
3271 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
3272 "Block containing LandingPadInst must be jumped to "
3273 "only by the unwind edge of an invoke.",
3274 LPI);
3275 }
3276 return;
3277 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003278 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3279 if (!pred_empty(BB))
3280 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3281 "Block containg CatchPadInst must be jumped to "
3282 "only by its catchswitch.",
3283 CPI);
Joseph Tremouleta9a05cb2016-01-10 04:32:03 +00003284 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3285 "Catchswitch cannot unwind to one of its catchpads",
3286 CPI->getCatchSwitch(), CPI);
David Majnemer8a1c45d2015-12-12 05:38:55 +00003287 return;
3288 }
David Majnemer85a549d2015-08-11 02:48:30 +00003289
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003290 // Verify that each pred has a legal terminator with a legal to/from EH
3291 // pad relationship.
3292 Instruction *ToPad = &I;
3293 Value *ToPadParent = getParentPad(ToPad);
David Majnemer85a549d2015-08-11 02:48:30 +00003294 for (BasicBlock *PredBB : predecessors(BB)) {
3295 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003296 Value *FromPad;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003297 if (auto *II = dyn_cast<InvokeInst>(TI)) {
David Majnemer85a549d2015-08-11 02:48:30 +00003298 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003299 "EH pad must be jumped to via an unwind edge", ToPad, II);
3300 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3301 FromPad = Bundle->Inputs[0];
3302 else
3303 FromPad = ConstantTokenNone::get(II->getContext());
3304 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
David Majnemer45ebda42016-03-01 18:59:50 +00003305 FromPad = CRI->getOperand(0);
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003306 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3307 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3308 FromPad = CSI;
3309 } else {
3310 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3311 }
3312
3313 // The edge may exit from zero or more nested pads.
David Majnemerf08579f2016-03-01 01:19:05 +00003314 SmallSet<Value *, 8> Seen;
Joseph Tremoulete28885e2016-01-10 04:28:38 +00003315 for (;; FromPad = getParentPad(FromPad)) {
3316 Assert(FromPad != ToPad,
3317 "EH pad cannot handle exceptions raised within it", FromPad, TI);
3318 if (FromPad == ToPadParent) {
3319 // This is a legal unwind edge.
3320 break;
3321 }
3322 Assert(!isa<ConstantTokenNone>(FromPad),
3323 "A single unwind edge may only enter one EH pad", TI);
David Majnemerf08579f2016-03-01 01:19:05 +00003324 Assert(Seen.insert(FromPad).second,
3325 "EH pad jumps through a cycle of pads", FromPad);
David Majnemer8a1c45d2015-12-12 05:38:55 +00003326 }
David Majnemer85a549d2015-08-11 02:48:30 +00003327 }
3328}
3329
3330void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
Bill Wendlingfae14752011-08-12 20:24:12 +00003331 // The landingpad instruction is ill-formed if it doesn't have any clauses and
3332 // isn't a cleanup.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003333 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3334 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
Bill Wendlingfae14752011-08-12 20:24:12 +00003335
David Majnemer85a549d2015-08-11 02:48:30 +00003336 visitEHPadPredecessors(LPI);
Bill Wendlingfae14752011-08-12 20:24:12 +00003337
David Majnemer654e1302015-07-31 17:58:14 +00003338 if (!LandingPadResultTy)
3339 LandingPadResultTy = LPI.getType();
3340 else
3341 Assert(LandingPadResultTy == LPI.getType(),
3342 "The landingpad instruction should have a consistent result type "
3343 "inside a function.",
3344 &LPI);
3345
David Majnemer7fddecc2015-06-17 20:52:32 +00003346 Function *F = LPI.getParent()->getParent();
3347 Assert(F->hasPersonalityFn(),
3348 "LandingPadInst needs to be in a function with a personality.", &LPI);
3349
Bill Wendlingfae14752011-08-12 20:24:12 +00003350 // The landingpad instruction must be the first non-PHI instruction in the
3351 // block.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003352 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
3353 "LandingPadInst not the first non-PHI instruction in the block.",
3354 &LPI);
Bill Wendlingfae14752011-08-12 20:24:12 +00003355
Duncan Sands86de1a62011-09-27 16:43:19 +00003356 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00003357 Constant *Clause = LPI.getClause(i);
Duncan Sands68ba8132011-09-27 19:34:22 +00003358 if (LPI.isCatch(i)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003359 Assert(isa<PointerType>(Clause->getType()),
3360 "Catch operand does not have pointer type!", &LPI);
Duncan Sands68ba8132011-09-27 19:34:22 +00003361 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003362 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
3363 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3364 "Filter operand is not an array of constants!", &LPI);
Duncan Sands68ba8132011-09-27 19:34:22 +00003365 }
Duncan Sands86de1a62011-09-27 16:43:19 +00003366 }
3367
Bill Wendlingfae14752011-08-12 20:24:12 +00003368 visitInstruction(LPI);
3369}
3370
David Majnemerba6665d2016-08-01 18:06:34 +00003371void Verifier::visitResumeInst(ResumeInst &RI) {
3372 Assert(RI.getFunction()->hasPersonalityFn(),
3373 "ResumeInst needs to be in a function with a personality.", &RI);
3374
3375 if (!LandingPadResultTy)
3376 LandingPadResultTy = RI.getValue()->getType();
3377 else
3378 Assert(LandingPadResultTy == RI.getValue()->getType(),
3379 "The resume instruction should have a consistent result type "
3380 "inside a function.",
3381 &RI);
3382
3383 visitTerminatorInst(RI);
3384}
3385
David Majnemer654e1302015-07-31 17:58:14 +00003386void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
David Majnemer85a549d2015-08-11 02:48:30 +00003387 BasicBlock *BB = CPI.getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003388
David Majnemer654e1302015-07-31 17:58:14 +00003389 Function *F = BB->getParent();
3390 Assert(F->hasPersonalityFn(),
3391 "CatchPadInst needs to be in a function with a personality.", &CPI);
3392
David Majnemer8a1c45d2015-12-12 05:38:55 +00003393 Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
3394 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3395 CPI.getParentPad());
3396
David Majnemer654e1302015-07-31 17:58:14 +00003397 // The catchpad instruction must be the first non-PHI instruction in the
3398 // block.
3399 Assert(BB->getFirstNonPHI() == &CPI,
David Majnemer8a1c45d2015-12-12 05:38:55 +00003400 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
David Majnemer654e1302015-07-31 17:58:14 +00003401
David Majnemerfe2f7f32016-02-29 22:56:36 +00003402 visitEHPadPredecessors(CPI);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003403 visitFuncletPadInst(CPI);
David Majnemer654e1302015-07-31 17:58:14 +00003404}
3405
David Majnemer8a1c45d2015-12-12 05:38:55 +00003406void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
3407 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
3408 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3409 CatchReturn.getOperand(0));
David Majnemer654e1302015-07-31 17:58:14 +00003410
David Majnemer8a1c45d2015-12-12 05:38:55 +00003411 visitTerminatorInst(CatchReturn);
David Majnemer654e1302015-07-31 17:58:14 +00003412}
3413
3414void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3415 BasicBlock *BB = CPI.getParent();
3416
David Majnemer654e1302015-07-31 17:58:14 +00003417 Function *F = BB->getParent();
3418 Assert(F->hasPersonalityFn(),
3419 "CleanupPadInst needs to be in a function with a personality.", &CPI);
3420
3421 // The cleanuppad instruction must be the first non-PHI instruction in the
3422 // block.
3423 Assert(BB->getFirstNonPHI() == &CPI,
3424 "CleanupPadInst not the first non-PHI instruction in the block.",
3425 &CPI);
3426
David Majnemer8a1c45d2015-12-12 05:38:55 +00003427 auto *ParentPad = CPI.getParentPad();
Joseph Tremoulet06125e52016-01-02 15:24:24 +00003428 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003429 "CleanupPadInst has an invalid parent.", &CPI);
3430
David Majnemerfe2f7f32016-02-29 22:56:36 +00003431 visitEHPadPredecessors(CPI);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003432 visitFuncletPadInst(CPI);
3433}
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003434
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003435void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
3436 User *FirstUser = nullptr;
3437 Value *FirstUnwindPad = nullptr;
3438 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
David Majnemerf08579f2016-03-01 01:19:05 +00003439 SmallSet<FuncletPadInst *, 8> Seen;
David Majnemerfe2f7f32016-02-29 22:56:36 +00003440
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003441 while (!Worklist.empty()) {
3442 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
David Majnemerfe2f7f32016-02-29 22:56:36 +00003443 Assert(Seen.insert(CurrentPad).second,
3444 "FuncletPadInst must not be nested within itself", CurrentPad);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003445 Value *UnresolvedAncestorPad = nullptr;
3446 for (User *U : CurrentPad->users()) {
3447 BasicBlock *UnwindDest;
3448 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
3449 UnwindDest = CRI->getUnwindDest();
3450 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
3451 // We allow catchswitch unwind to caller to nest
3452 // within an outer pad that unwinds somewhere else,
3453 // because catchswitch doesn't have a nounwind variant.
3454 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
3455 if (CSI->unwindsToCaller())
3456 continue;
3457 UnwindDest = CSI->getUnwindDest();
3458 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
3459 UnwindDest = II->getUnwindDest();
3460 } else if (isa<CallInst>(U)) {
3461 // Calls which don't unwind may be found inside funclet
3462 // pads that unwind somewhere else. We don't *require*
3463 // such calls to be annotated nounwind.
3464 continue;
3465 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
3466 // The unwind dest for a cleanup can only be found by
3467 // recursive search. Add it to the worklist, and we'll
3468 // search for its first use that determines where it unwinds.
3469 Worklist.push_back(CPI);
3470 continue;
3471 } else {
3472 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
3473 continue;
3474 }
3475
3476 Value *UnwindPad;
3477 bool ExitsFPI;
3478 if (UnwindDest) {
3479 UnwindPad = UnwindDest->getFirstNonPHI();
David Majnemerfe2f7f32016-02-29 22:56:36 +00003480 if (!cast<Instruction>(UnwindPad)->isEHPad())
3481 continue;
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003482 Value *UnwindParent = getParentPad(UnwindPad);
3483 // Ignore unwind edges that don't exit CurrentPad.
3484 if (UnwindParent == CurrentPad)
3485 continue;
3486 // Determine whether the original funclet pad is exited,
3487 // and if we are scanning nested pads determine how many
3488 // of them are exited so we can stop searching their
3489 // children.
3490 Value *ExitedPad = CurrentPad;
3491 ExitsFPI = false;
3492 do {
3493 if (ExitedPad == &FPI) {
3494 ExitsFPI = true;
3495 // Now we can resolve any ancestors of CurrentPad up to
3496 // FPI, but not including FPI since we need to make sure
3497 // to check all direct users of FPI for consistency.
3498 UnresolvedAncestorPad = &FPI;
3499 break;
3500 }
3501 Value *ExitedParent = getParentPad(ExitedPad);
3502 if (ExitedParent == UnwindParent) {
3503 // ExitedPad is the ancestor-most pad which this unwind
3504 // edge exits, so we can resolve up to it, meaning that
3505 // ExitedParent is the first ancestor still unresolved.
3506 UnresolvedAncestorPad = ExitedParent;
3507 break;
3508 }
3509 ExitedPad = ExitedParent;
3510 } while (!isa<ConstantTokenNone>(ExitedPad));
3511 } else {
3512 // Unwinding to caller exits all pads.
3513 UnwindPad = ConstantTokenNone::get(FPI.getContext());
3514 ExitsFPI = true;
3515 UnresolvedAncestorPad = &FPI;
3516 }
3517
3518 if (ExitsFPI) {
3519 // This unwind edge exits FPI. Make sure it agrees with other
3520 // such edges.
3521 if (FirstUser) {
3522 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
3523 "pad must have the same unwind "
3524 "dest",
3525 &FPI, U, FirstUser);
3526 } else {
3527 FirstUser = U;
3528 FirstUnwindPad = UnwindPad;
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00003529 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
3530 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
3531 getParentPad(UnwindPad) == getParentPad(&FPI))
3532 SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U);
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003533 }
3534 }
3535 // Make sure we visit all uses of FPI, but for nested pads stop as
3536 // soon as we know where they unwind to.
3537 if (CurrentPad != &FPI)
3538 break;
3539 }
3540 if (UnresolvedAncestorPad) {
3541 if (CurrentPad == UnresolvedAncestorPad) {
3542 // When CurrentPad is FPI itself, we don't mark it as resolved even if
3543 // we've found an unwind edge that exits it, because we need to verify
3544 // all direct uses of FPI.
3545 assert(CurrentPad == &FPI);
3546 continue;
3547 }
3548 // Pop off the worklist any nested pads that we've found an unwind
3549 // destination for. The pads on the worklist are the uncles,
3550 // great-uncles, etc. of CurrentPad. We've found an unwind destination
3551 // for all ancestors of CurrentPad up to but not including
3552 // UnresolvedAncestorPad.
3553 Value *ResolvedPad = CurrentPad;
3554 while (!Worklist.empty()) {
3555 Value *UnclePad = Worklist.back();
3556 Value *AncestorPad = getParentPad(UnclePad);
3557 // Walk ResolvedPad up the ancestor list until we either find the
3558 // uncle's parent or the last resolved ancestor.
3559 while (ResolvedPad != AncestorPad) {
3560 Value *ResolvedParent = getParentPad(ResolvedPad);
3561 if (ResolvedParent == UnresolvedAncestorPad) {
3562 break;
3563 }
3564 ResolvedPad = ResolvedParent;
3565 }
3566 // If the resolved ancestor search didn't find the uncle's parent,
3567 // then the uncle is not yet resolved.
3568 if (ResolvedPad != AncestorPad)
3569 break;
3570 // This uncle is resolved, so pop it from the worklist.
3571 Worklist.pop_back();
3572 }
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003573 }
3574 }
3575
Joseph Tremoulet81e81962016-01-10 04:30:02 +00003576 if (FirstUnwindPad) {
3577 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
3578 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
3579 Value *SwitchUnwindPad;
3580 if (SwitchUnwindDest)
3581 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
3582 else
3583 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
3584 Assert(SwitchUnwindPad == FirstUnwindPad,
3585 "Unwind edges out of a catch must have the same unwind dest as "
3586 "the parent catchswitch",
3587 &FPI, FirstUser, CatchSwitch);
3588 }
3589 }
3590
3591 visitInstruction(FPI);
David Majnemer654e1302015-07-31 17:58:14 +00003592}
3593
David Majnemer8a1c45d2015-12-12 05:38:55 +00003594void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003595 BasicBlock *BB = CatchSwitch.getParent();
3596
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003597 Function *F = BB->getParent();
3598 Assert(F->hasPersonalityFn(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003599 "CatchSwitchInst needs to be in a function with a personality.",
3600 &CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003601
David Majnemer8a1c45d2015-12-12 05:38:55 +00003602 // The catchswitch instruction must be the first non-PHI instruction in the
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003603 // block.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003604 Assert(BB->getFirstNonPHI() == &CatchSwitch,
3605 "CatchSwitchInst not the first non-PHI instruction in the block.",
3606 &CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003607
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00003608 auto *ParentPad = CatchSwitch.getParentPad();
3609 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3610 "CatchSwitchInst has an invalid parent.", ParentPad);
3611
David Majnemer8a1c45d2015-12-12 05:38:55 +00003612 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003613 Instruction *I = UnwindDest->getFirstNonPHI();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003614 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3615 "CatchSwitchInst must unwind to an EH block which is not a "
3616 "landingpad.",
3617 &CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003618
Joseph Tremoulet8ea80862016-01-10 04:31:05 +00003619 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
3620 if (getParentPad(I) == ParentPad)
3621 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
3622 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003623
Joseph Tremoulet131a4622016-01-02 15:25:25 +00003624 Assert(CatchSwitch.getNumHandlers() != 0,
3625 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3626
Joseph Tremouletd425dd12016-01-02 15:50:34 +00003627 for (BasicBlock *Handler : CatchSwitch.handlers()) {
Joseph Tremoulet131a4622016-01-02 15:25:25 +00003628 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3629 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
Joseph Tremouletd425dd12016-01-02 15:50:34 +00003630 }
Joseph Tremoulet131a4622016-01-02 15:25:25 +00003631
David Majnemerfe2f7f32016-02-29 22:56:36 +00003632 visitEHPadPredecessors(CatchSwitch);
David Majnemer8a1c45d2015-12-12 05:38:55 +00003633 visitTerminatorInst(CatchSwitch);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003634}
3635
David Majnemer654e1302015-07-31 17:58:14 +00003636void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00003637 Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
3638 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
3639 CRI.getOperand(0));
3640
David Majnemer654e1302015-07-31 17:58:14 +00003641 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3642 Instruction *I = UnwindDest->getFirstNonPHI();
3643 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3644 "CleanupReturnInst must unwind to an EH block which is not a "
3645 "landingpad.",
3646 &CRI);
3647 }
3648
3649 visitTerminatorInst(CRI);
3650}
3651
Rafael Espindola654320a2012-02-26 02:23:37 +00003652void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3653 Instruction *Op = cast<Instruction>(I.getOperand(i));
Rafael Espindola9a167352012-08-17 18:21:28 +00003654 // If the we have an invalid invoke, don't try to compute the dominance.
3655 // We already reject it in the invoke specific checks and the dominance
3656 // computation doesn't handle multiple edges.
3657 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3658 if (II->getNormalDest() == II->getUnwindDest())
3659 return;
3660 }
Rafael Espindola654320a2012-02-26 02:23:37 +00003661
Michael Kruseff379b62016-03-26 23:32:57 +00003662 // Quick check whether the def has already been encountered in the same block.
3663 // PHI nodes are not checked to prevent accepting preceeding PHIs, because PHI
3664 // uses are defined to happen on the incoming edge, not at the instruction.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +00003665 //
3666 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
3667 // wrapping an SSA value, assert that we've already encountered it. See
3668 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
Michael Kruseff379b62016-03-26 23:32:57 +00003669 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
3670 return;
3671
Rafael Espindola103c2cf2012-06-01 21:56:26 +00003672 const Use &U = I.getOperandUse(i);
Michael Kruseff379b62016-03-26 23:32:57 +00003673 Assert(DT.dominates(Op, U),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003674 "Instruction does not dominate all uses!", Op, &I);
Rafael Espindola654320a2012-02-26 02:23:37 +00003675}
3676
Artur Pilipenkocca80022015-10-09 17:41:29 +00003677void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3678 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3679 "apply only to pointer types", &I);
3680 Assert(isa<LoadInst>(I),
3681 "dereferenceable, dereferenceable_or_null apply only to load"
3682 " instructions, use attributes for calls or invokes", &I);
3683 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3684 "take one operand!", &I);
3685 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3686 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3687 "dereferenceable_or_null metadata value must be an i64!", &I);
3688}
3689
Misha Brukmanc566ca362004-03-02 00:22:19 +00003690/// verifyInstruction - Verify that an instruction is well formed.
3691///
Chris Lattner069a7952002-06-25 15:56:27 +00003692void Verifier::visitInstruction(Instruction &I) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003693 BasicBlock *BB = I.getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003694 Assert(BB, "Instruction not embedded in basic block!", &I);
Chris Lattner0e851da2002-04-18 20:37:37 +00003695
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003696 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
Ahmed Charles821b6662014-03-09 04:57:09 +00003697 for (User *U : I.users()) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003698 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3699 "Only PHI nodes may reference their own value!", &I);
Ahmed Charles821b6662014-03-09 04:57:09 +00003700 }
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003701 }
Nick Lewycky3fc89802009-09-07 20:44:51 +00003702
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003703 // Check that void typed values don't have names
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003704 Assert(!I.getType()->isVoidTy() || !I.hasName(),
3705 "Instruction has a name, but provides a void value!", &I);
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003706
Chris Lattner5f126b72004-03-29 00:29:36 +00003707 // Check that the return value of the instruction is either void or a legal
3708 // value type.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003709 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3710 "Instruction returns a non-scalar type!", &I);
Chris Lattner5f126b72004-03-29 00:29:36 +00003711
Nick Lewycky93e06a52009-09-27 23:27:42 +00003712 // Check that the instruction doesn't produce metadata. Calls are already
3713 // checked against the callee type.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003714 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3715 "Invalid use of metadata!", &I);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00003716
Chris Lattner0e851da2002-04-18 20:37:37 +00003717 // Check that all uses of the instruction, if they are instructions
3718 // themselves, actually have parent basic blocks. If the use is not an
3719 // instruction, it is an error!
Chandler Carruthcdf47882014-03-09 03:16:01 +00003720 for (Use &U : I.uses()) {
3721 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003722 Assert(Used->getParent() != nullptr,
3723 "Instruction referencing"
3724 " instruction not embedded in a basic block!",
3725 &I, Used);
Nick Lewycky984161a2009-09-08 02:02:39 +00003726 else {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003727 CheckFailed("Use of instruction is not an instruction!", U);
Nick Lewycky984161a2009-09-08 02:02:39 +00003728 return;
3729 }
Chris Lattner0e851da2002-04-18 20:37:37 +00003730 }
3731
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003732 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003733 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
Chris Lattnerb7e1ef52006-07-11 20:29:49 +00003734
3735 // Check to make sure that only first-class-values are operands to
3736 // instructions.
Devang Patel1f00b532008-02-21 01:54:02 +00003737 if (!I.getOperand(i)->getType()->isFirstClassType()) {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00003738 Assert(false, "Instruction operands must be first-class values!", &I);
Devang Patel1f00b532008-02-21 01:54:02 +00003739 }
Nick Lewyckyadbc2842009-05-30 05:06:04 +00003740
Chris Lattner9ece94b2004-03-14 03:23:54 +00003741 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
Chris Lattnerb7e1ef52006-07-11 20:29:49 +00003742 // Check to make sure that the "address of" an intrinsic function is never
3743 // taken.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003744 Assert(
Justin Lebar9cbc3012016-07-28 23:58:15 +00003745 !F->isIntrinsic() ||
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003746 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3747 "Cannot take the address of an intrinsic!", &I);
3748 Assert(
3749 !F->isIntrinsic() || isa<CallInst>(I) ||
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00003750 F->getIntrinsicID() == Intrinsic::donothing ||
David Majnemerf93082e2016-08-04 20:30:07 +00003751 F->getIntrinsicID() == Intrinsic::coro_resume ||
3752 F->getIntrinsicID() == Intrinsic::coro_destroy ||
Juergen Ributzkaad2363f2014-10-17 17:39:00 +00003753 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
Igor Laevsky9570ff92015-02-19 11:28:47 +00003754 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3755 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
David Majnemerf93082e2016-08-04 20:30:07 +00003756 "Cannot invoke an intrinsic other than donothing, patchpoint, "
3757 "statepoint, coro_resume or coro_destroy",
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003758 &I);
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003759 Assert(F->getParent() == &M, "Referencing function in another module!",
3760 &I, &M, F, F->getParent());
Chris Lattner9ece94b2004-03-14 03:23:54 +00003761 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003762 Assert(OpBB->getParent() == BB->getParent(),
3763 "Referring to a basic block in another function!", &I);
Chris Lattner9ece94b2004-03-14 03:23:54 +00003764 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003765 Assert(OpArg->getParent() == BB->getParent(),
3766 "Referring to an argument in another function!", &I);
Chris Lattner4ff04522007-04-20 21:48:08 +00003767 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00003768 Assert(GV->getParent() == &M, "Referencing global in another module!", &I,
3769 &M, GV, GV->getParent());
Rafael Espindola654320a2012-02-26 02:23:37 +00003770 } else if (isa<Instruction>(I.getOperand(i))) {
3771 verifyDominatesUse(I, i);
Chris Lattner41eb5cd2006-01-26 00:08:45 +00003772 } else if (isa<InlineAsm>(I.getOperand(i))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003773 Assert((i + 1 == e && isa<CallInst>(I)) ||
3774 (i + 3 == e && isa<InvokeInst>(I)),
3775 "Cannot take the address of an inline asm!", &I);
Matt Arsenault24b49c42013-07-31 17:49:08 +00003776 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
Sanjoy Dase1129ee2016-08-02 02:55:57 +00003777 if (CE->getType()->isPtrOrPtrVectorTy() ||
3778 !DL.getNonIntegralAddressSpaces().empty()) {
Matt Arsenault24b49c42013-07-31 17:49:08 +00003779 // If we have a ConstantExpr pointer, we need to see if it came from an
Sanjoy Dase1129ee2016-08-02 02:55:57 +00003780 // illegal bitcast. If the datalayout string specifies non-integral
3781 // address spaces then we also need to check for illegal ptrtoint and
3782 // inttoptr expressions.
Duncan P. N. Exon Smith836f0dd2015-12-10 17:56:06 +00003783 visitConstantExprsRecursively(CE);
Matt Arsenault24b49c42013-07-31 17:49:08 +00003784 }
Chris Lattnerdf9779c2003-10-05 17:44:18 +00003785 }
3786 }
Rafael Espindolaef9f5502012-03-24 00:14:51 +00003787
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003788 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003789 Assert(I.getType()->isFPOrFPVectorTy(),
3790 "fpmath requires a floating point result!", &I);
3791 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003792 if (ConstantFP *CFP0 =
3793 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00003794 const APFloat &Accuracy = CFP0->getValueAPF();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003795 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
Matt Arsenault82f41512016-06-27 19:43:15 +00003796 "fpmath accuracy must have float type", &I);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003797 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3798 "fpmath accuracy not a positive number!", &I);
Duncan Sands05f4df82012-04-16 16:28:59 +00003799 } else {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003800 Assert(false, "invalid fpmath accuracy!", &I);
Duncan Sands05f4df82012-04-16 16:28:59 +00003801 }
Duncan Sandsaf06b262012-04-10 08:22:43 +00003802 }
3803
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00003804 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003805 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3806 "Ranges are only for loads, calls and invokes!", &I);
Philip Reamesbf9676f2014-10-20 23:52:07 +00003807 visitRangeMetadata(I, Range, I.getType());
3808 }
Rafael Espindolaef9f5502012-03-24 00:14:51 +00003809
Philip Reames0ca58b32014-10-21 20:56:29 +00003810 if (I.getMetadata(LLVMContext::MD_nonnull)) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003811 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3812 &I);
3813 Assert(isa<LoadInst>(I),
3814 "nonnull applies only to load instructions, use attributes"
3815 " for calls or invokes",
3816 &I);
Philip Reames0ca58b32014-10-21 20:56:29 +00003817 }
3818
Artur Pilipenkocca80022015-10-09 17:41:29 +00003819 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3820 visitDereferenceableMetadata(I, MD);
3821
3822 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3823 visitDereferenceableMetadata(I, MD);
3824
Mehdi Aminia84a8402016-12-16 06:29:14 +00003825 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa))
3826 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
Sanjoy Das2582e692016-11-08 20:46:01 +00003827
Artur Pilipenkocca80022015-10-09 17:41:29 +00003828 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3829 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3830 &I);
3831 Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3832 "use attributes for calls or invokes", &I);
3833 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3834 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3835 Assert(CI && CI->getType()->isIntegerTy(64),
3836 "align metadata value must be an i64!", &I);
3837 uint64_t Align = CI->getZExtValue();
3838 Assert(isPowerOf2_64(Align),
3839 "align metadata value must be a power of 2!", &I);
3840 Assert(Align <= Value::MaximumAlignment,
3841 "alignment is larger that implementation defined limit", &I);
3842 }
3843
Duncan P. N. Exon Smitha3bdc322015-03-20 19:26:58 +00003844 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
Adrian Prantl541a9c52016-05-06 19:26:47 +00003845 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
Duncan P. N. Exon Smithfc25da12015-03-24 17:32:19 +00003846 visitMDNode(*N);
Duncan P. N. Exon Smitha3bdc322015-03-20 19:26:58 +00003847 }
3848
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00003849 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
Adrian Prantl941fa752016-12-05 18:04:47 +00003850 verifyFragmentExpression(*DII);
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00003851
Chris Lattnerc9e79d02004-09-29 20:07:45 +00003852 InstsInThisBlock.insert(&I);
Chris Lattnerbb346d02003-05-08 03:47:33 +00003853}
3854
Philip Reames007561a2015-06-26 22:21:52 +00003855/// Allow intrinsics to be verified in different ways.
3856void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
Philip Reames9818dd72015-06-26 22:04:34 +00003857 Function *IF = CS.getCalledFunction();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003858 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3859 IF);
Nick Lewycky3fc89802009-09-07 20:44:51 +00003860
Chris Lattner144b6192012-05-27 19:37:05 +00003861 // Verify that the intrinsic prototype lines up with what the .td files
3862 // describe.
3863 FunctionType *IFTy = IF->getFunctionType();
Andrew Tricka2efd992013-10-31 17:18:11 +00003864 bool IsVarArg = IFTy->isVarArg();
Matt Arsenaultc4c92262013-07-20 17:46:00 +00003865
Chris Lattner144b6192012-05-27 19:37:05 +00003866 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3867 getIntrinsicInfoTableEntries(ID, Table);
3868 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
Nick Lewycky3fc89802009-09-07 20:44:51 +00003869
Chris Lattner144b6192012-05-27 19:37:05 +00003870 SmallVector<Type *, 4> ArgTys;
Artur Pilipenkobc552272016-06-22 14:56:33 +00003871 Assert(!Intrinsic::matchIntrinsicType(IFTy->getReturnType(),
3872 TableRef, ArgTys),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003873 "Intrinsic has incorrect return type!", IF);
Chris Lattner144b6192012-05-27 19:37:05 +00003874 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
Artur Pilipenkobc552272016-06-22 14:56:33 +00003875 Assert(!Intrinsic::matchIntrinsicType(IFTy->getParamType(i),
3876 TableRef, ArgTys),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003877 "Intrinsic has incorrect argument type!", IF);
Andrew Tricka2efd992013-10-31 17:18:11 +00003878
3879 // Verify if the intrinsic call matches the vararg property.
3880 if (IsVarArg)
Artur Pilipenkob68b8212016-06-24 14:47:27 +00003881 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003882 "Intrinsic was not defined with variable arguments!", IF);
Andrew Tricka2efd992013-10-31 17:18:11 +00003883 else
Artur Pilipenkob68b8212016-06-24 14:47:27 +00003884 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003885 "Callsite was not defined with variable arguments!", IF);
Andrew Tricka2efd992013-10-31 17:18:11 +00003886
3887 // All descriptors should be absorbed by now.
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003888 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
Chris Lattner144b6192012-05-27 19:37:05 +00003889
3890 // Now that we have the intrinsic ID and the actual argument types (and we
3891 // know they are legal for the intrinsic!) get the intrinsic name through the
3892 // usual means. This allows us to verify the mangling of argument types into
3893 // the name.
Justin Bogner28e1cf62014-03-10 21:22:44 +00003894 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003895 Assert(ExpectedName == IF->getName(),
3896 "Intrinsic name not mangled correctly for type arguments! "
3897 "Should be: " +
3898 ExpectedName,
3899 IF);
Matt Arsenaultc4c92262013-07-20 17:46:00 +00003900
Chris Lattner588096e2009-12-28 09:07:21 +00003901 // If the intrinsic takes MDNode arguments, verify that they are either global
3902 // or are local to *this* function.
Philip Reames007561a2015-06-26 22:21:52 +00003903 for (Value *V : CS.args())
3904 if (auto *MD = dyn_cast<MetadataAsValue>(V))
3905 visitMetadataAsValue(*MD, CS.getCaller());
Victor Hernandez0471abd2009-12-18 20:09:14 +00003906
Gordon Henriksena2f3e132007-09-17 20:30:04 +00003907 switch (ID) {
3908 default:
3909 break;
Gor Nishanov0f303ac2016-08-12 05:45:49 +00003910 case Intrinsic::coro_id: {
Gor Nishanovdce9b022016-08-29 14:34:12 +00003911 auto *InfoArg = CS.getArgOperand(3)->stripPointerCasts();
Gor Nishanov31d8c9a2016-08-06 02:16:35 +00003912 if (isa<ConstantPointerNull>(InfoArg))
3913 break;
3914 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
3915 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
3916 "info argument of llvm.coro.begin must refer to an initialized "
3917 "constant");
3918 Constant *Init = GV->getInitializer();
3919 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
3920 "info argument of llvm.coro.begin must refer to either a struct or "
3921 "an array");
3922 break;
3923 }
Chandler Carruth026cc372011-12-12 04:36:02 +00003924 case Intrinsic::ctlz: // llvm.ctlz
3925 case Intrinsic::cttz: // llvm.cttz
Philip Reames9818dd72015-06-26 22:04:34 +00003926 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003927 "is_zero_undef argument of bit counting intrinsics must be a "
3928 "constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00003929 CS);
Chandler Carruth026cc372011-12-12 04:36:02 +00003930 break;
Andrew Kaylora0a11642017-01-26 23:27:59 +00003931 case Intrinsic::experimental_constrained_fadd:
3932 case Intrinsic::experimental_constrained_fsub:
3933 case Intrinsic::experimental_constrained_fmul:
3934 case Intrinsic::experimental_constrained_fdiv:
3935 case Intrinsic::experimental_constrained_frem:
3936 visitConstrainedFPIntrinsic(
3937 cast<ConstrainedFPIntrinsic>(*CS.getInstruction()));
3938 break;
Duncan P. N. Exon Smith959299e2015-03-15 00:50:57 +00003939 case Intrinsic::dbg_declare: // llvm.dbg.declare
Philip Reames9818dd72015-06-26 22:04:34 +00003940 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3941 "invalid llvm.dbg.declare intrinsic call 1", CS);
3942 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00003943 break;
3944 case Intrinsic::dbg_value: // llvm.dbg.value
Philip Reames9818dd72015-06-26 22:04:34 +00003945 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
Duncan P. N. Exon Smith959299e2015-03-15 00:50:57 +00003946 break;
Chris Lattnerdd708342008-11-21 16:42:48 +00003947 case Intrinsic::memcpy:
3948 case Intrinsic::memmove:
Owen Anderson63fbf102015-03-02 09:35:06 +00003949 case Intrinsic::memset: {
Philip Reames9818dd72015-06-26 22:04:34 +00003950 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003951 Assert(AlignCI,
3952 "alignment argument of memory intrinsics must be a constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00003953 CS);
Owen Anderson63fbf102015-03-02 09:35:06 +00003954 const APInt &AlignVal = AlignCI->getValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003955 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
Philip Reames9818dd72015-06-26 22:04:34 +00003956 "alignment argument of memory intrinsics must be a power of 2", CS);
Pete Cooper67cf9a72015-11-19 05:56:52 +00003957 Assert(isa<ConstantInt>(CS.getArgOperand(4)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003958 "isvolatile argument of memory intrinsics must be a constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00003959 CS);
Chris Lattnerecded9a2008-08-23 05:31:10 +00003960 break;
Owen Anderson63fbf102015-03-02 09:35:06 +00003961 }
Igor Laevsky4f31e522016-12-29 14:31:07 +00003962 case Intrinsic::memcpy_element_atomic: {
3963 ConstantInt *ElementSizeCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3964 Assert(ElementSizeCI, "element size of the element-wise atomic memory "
3965 "intrinsic must be a constant int",
3966 CS);
3967 const APInt &ElementSizeVal = ElementSizeCI->getValue();
3968 Assert(ElementSizeVal.isPowerOf2(),
3969 "element size of the element-wise atomic memory intrinsic "
3970 "must be a power of 2",
3971 CS);
3972
3973 auto IsValidAlignment = [&](uint64_t Alignment) {
3974 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
3975 };
3976
3977 uint64_t DstAlignment = CS.getParamAlignment(1),
3978 SrcAlignment = CS.getParamAlignment(2);
3979
3980 Assert(IsValidAlignment(DstAlignment),
3981 "incorrect alignment of the destination argument",
3982 CS);
3983 Assert(IsValidAlignment(SrcAlignment),
3984 "incorrect alignment of the source argument",
3985 CS);
3986 break;
3987 }
Bill Wendling05604e02008-08-23 09:46:46 +00003988 case Intrinsic::gcroot:
3989 case Intrinsic::gcwrite:
Chris Lattner25852062008-08-24 20:46:13 +00003990 case Intrinsic::gcread:
3991 if (ID == Intrinsic::gcroot) {
Gordon Henriksenbf40eee2008-10-25 16:28:35 +00003992 AllocaInst *AI =
Philip Reames9818dd72015-06-26 22:04:34 +00003993 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3994 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3995 Assert(isa<Constant>(CS.getArgOperand(1)),
3996 "llvm.gcroot parameter #2 must be a constant.", CS);
David Blaikie96b48192015-05-11 23:09:25 +00003997 if (!AI->getAllocatedType()->isPointerTy()) {
Philip Reames9818dd72015-06-26 22:04:34 +00003998 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00003999 "llvm.gcroot parameter #1 must either be a pointer alloca, "
4000 "or argument #2 must be a non-null constant.",
Philip Reames9818dd72015-06-26 22:04:34 +00004001 CS);
Talin2e59f142010-09-30 20:23:47 +00004002 }
Chris Lattner25852062008-08-24 20:46:13 +00004003 }
Nick Lewycky3fc89802009-09-07 20:44:51 +00004004
Philip Reames9818dd72015-06-26 22:04:34 +00004005 Assert(CS.getParent()->getParent()->hasGC(),
4006 "Enclosing function does not use GC.", CS);
Chris Lattner25852062008-08-24 20:46:13 +00004007 break;
Duncan Sandsf72ff0c2007-09-29 16:25:54 +00004008 case Intrinsic::init_trampoline:
Philip Reames9818dd72015-06-26 22:04:34 +00004009 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004010 "llvm.init_trampoline parameter #2 must resolve to a function.",
Philip Reames9818dd72015-06-26 22:04:34 +00004011 CS);
Gordon Henriksen9157c492007-12-25 02:02:10 +00004012 break;
Chris Lattner229f7652008-10-16 06:00:36 +00004013 case Intrinsic::prefetch:
Philip Reames9818dd72015-06-26 22:04:34 +00004014 Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
4015 isa<ConstantInt>(CS.getArgOperand(2)) &&
4016 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
4017 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
4018 "invalid arguments to llvm.prefetch", CS);
Chris Lattner229f7652008-10-16 06:00:36 +00004019 break;
Bill Wendlingd8e312d2008-11-18 23:09:31 +00004020 case Intrinsic::stackprotector:
Philip Reames9818dd72015-06-26 22:04:34 +00004021 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
4022 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
Bill Wendlingd8e312d2008-11-18 23:09:31 +00004023 break;
Nick Lewycky9bc89042009-10-13 07:57:33 +00004024 case Intrinsic::lifetime_start:
4025 case Intrinsic::lifetime_end:
4026 case Intrinsic::invariant_start:
Philip Reames9818dd72015-06-26 22:04:34 +00004027 Assert(isa<ConstantInt>(CS.getArgOperand(0)),
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004028 "size argument of memory use markers must be a constant integer",
Philip Reames9818dd72015-06-26 22:04:34 +00004029 CS);
Nick Lewycky9bc89042009-10-13 07:57:33 +00004030 break;
4031 case Intrinsic::invariant_end:
Philip Reames9818dd72015-06-26 22:04:34 +00004032 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
4033 "llvm.invariant.end parameter #2 must be a constant integer", CS);
Nick Lewycky9bc89042009-10-13 07:57:33 +00004034 break;
Reid Klecknere9b89312015-01-13 00:48:10 +00004035
Reid Kleckner60381792015-07-07 22:25:32 +00004036 case Intrinsic::localescape: {
Philip Reames9818dd72015-06-26 22:04:34 +00004037 BasicBlock *BB = CS.getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004038 Assert(BB == &BB->getParent()->front(),
Reid Kleckner60381792015-07-07 22:25:32 +00004039 "llvm.localescape used outside of entry block", CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004040 Assert(!SawFrameEscape,
Reid Kleckner60381792015-07-07 22:25:32 +00004041 "multiple calls to llvm.localescape in one function", CS);
Philip Reames9818dd72015-06-26 22:04:34 +00004042 for (Value *Arg : CS.args()) {
Reid Kleckner3567d272015-04-02 21:13:31 +00004043 if (isa<ConstantPointerNull>(Arg))
4044 continue; // Null values are allowed as placeholders.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004045 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004046 Assert(AI && AI->isStaticAlloca(),
Reid Kleckner60381792015-07-07 22:25:32 +00004047 "llvm.localescape only accepts static allocas", CS);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004048 }
Philip Reames9818dd72015-06-26 22:04:34 +00004049 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004050 SawFrameEscape = true;
Reid Klecknere9b89312015-01-13 00:48:10 +00004051 break;
4052 }
Reid Kleckner60381792015-07-07 22:25:32 +00004053 case Intrinsic::localrecover: {
Philip Reames9818dd72015-06-26 22:04:34 +00004054 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
Reid Klecknere9b89312015-01-13 00:48:10 +00004055 Function *Fn = dyn_cast<Function>(FnArg);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004056 Assert(Fn && !Fn->isDeclaration(),
Reid Kleckner60381792015-07-07 22:25:32 +00004057 "llvm.localrecover first "
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004058 "argument must be function defined in this module",
Philip Reames9818dd72015-06-26 22:04:34 +00004059 CS);
4060 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
Reid Kleckner60381792015-07-07 22:25:32 +00004061 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
Philip Reames9818dd72015-06-26 22:04:34 +00004062 CS);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00004063 auto &Entry = FrameEscapeInfo[Fn];
4064 Entry.second = unsigned(
4065 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
Reid Klecknere9b89312015-01-13 00:48:10 +00004066 break;
4067 }
4068
Philip Reames1ffa9372015-01-30 23:28:05 +00004069 case Intrinsic::experimental_gc_statepoint:
Philip Reames9818dd72015-06-26 22:04:34 +00004070 Assert(!CS.isInlineAsm(),
4071 "gc.statepoint support for inline assembly unimplemented", CS);
4072 Assert(CS.getParent()->getParent()->hasGC(),
4073 "Enclosing function does not use GC.", CS);
Philip Reames0285c742015-02-03 23:18:47 +00004074
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004075 verifyStatepoint(CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004076 break;
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +00004077 case Intrinsic::experimental_gc_result: {
Philip Reames9818dd72015-06-26 22:04:34 +00004078 Assert(CS.getParent()->getParent()->hasGC(),
4079 "Enclosing function does not use GC.", CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004080 // Are we tied to a statepoint properly?
Philip Reames9818dd72015-06-26 22:04:34 +00004081 CallSite StatepointCS(CS.getArgOperand(0));
Philip Reames76ebd152015-01-07 22:48:01 +00004082 const Function *StatepointFn =
4083 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004084 Assert(StatepointFn && StatepointFn->isDeclaration() &&
4085 StatepointFn->getIntrinsicID() ==
4086 Intrinsic::experimental_gc_statepoint,
Philip Reames9818dd72015-06-26 22:04:34 +00004087 "gc.result operand #1 must be from a statepoint", CS,
4088 CS.getArgOperand(0));
Philip Reames38303a32014-12-03 19:53:15 +00004089
Philip Reamesb23713a2014-12-03 22:23:24 +00004090 // Assert that result type matches wrapped callee.
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004091 const Value *Target = StatepointCS.getArgument(2);
Craig Toppere3dcce92015-08-01 22:20:21 +00004092 auto *PT = cast<PointerType>(Target->getType());
4093 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
Philip Reames9818dd72015-06-26 22:04:34 +00004094 Assert(CS.getType() == TargetFuncType->getReturnType(),
4095 "gc.result result type does not match wrapped callee", CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004096 break;
4097 }
4098 case Intrinsic::experimental_gc_relocate: {
Philip Reames9818dd72015-06-26 22:04:34 +00004099 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
Igor Laevsky9570ff92015-02-19 11:28:47 +00004100
Philip Reames3e2cf532016-01-07 03:32:11 +00004101 Assert(isa<PointerType>(CS.getType()->getScalarType()),
4102 "gc.relocate must return a pointer or a vector of pointers", CS);
4103
Igor Laevsky9570ff92015-02-19 11:28:47 +00004104 // Check that this relocate is correctly tied to the statepoint
4105
4106 // This is case for relocate on the unwinding path of an invoke statepoint
Chen Lid71999e2015-12-26 07:54:32 +00004107 if (LandingPadInst *LandingPad =
4108 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) {
Igor Laevsky9570ff92015-02-19 11:28:47 +00004109
Sanjoy Das5665c992015-05-11 23:47:27 +00004110 const BasicBlock *InvokeBB =
Chen Lid71999e2015-12-26 07:54:32 +00004111 LandingPad->getParent()->getUniquePredecessor();
Igor Laevsky9570ff92015-02-19 11:28:47 +00004112
4113 // Landingpad relocates should have only one predecessor with invoke
4114 // statepoint terminator
Sanjoy Das5665c992015-05-11 23:47:27 +00004115 Assert(InvokeBB, "safepoints should have unique landingpads",
Chen Lid71999e2015-12-26 07:54:32 +00004116 LandingPad->getParent());
Sanjoy Das5665c992015-05-11 23:47:27 +00004117 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
4118 InvokeBB);
4119 Assert(isStatepoint(InvokeBB->getTerminator()),
4120 "gc relocate should be linked to a statepoint", InvokeBB);
Igor Laevsky9570ff92015-02-19 11:28:47 +00004121 }
4122 else {
4123 // In all other cases relocate should be tied to the statepoint directly.
4124 // This covers relocates on a normal return path of invoke statepoint and
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004125 // relocates of a call statepoint.
Philip Reames9818dd72015-06-26 22:04:34 +00004126 auto Token = CS.getArgOperand(0);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004127 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
Philip Reames9818dd72015-06-26 22:04:34 +00004128 "gc relocate is incorrectly tied to the statepoint", CS, Token);
Igor Laevsky9570ff92015-02-19 11:28:47 +00004129 }
4130
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004131 // Verify rest of the relocate arguments.
Igor Laevsky9570ff92015-02-19 11:28:47 +00004132
Manuel Jacob83eefa62016-01-05 04:03:00 +00004133 ImmutableCallSite StatepointCS(
4134 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint());
Philip Reames337c4bd2014-12-01 21:18:12 +00004135
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004136 // Both the base and derived must be piped through the safepoint.
Philip Reames9818dd72015-06-26 22:04:34 +00004137 Value* Base = CS.getArgOperand(1);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004138 Assert(isa<ConstantInt>(Base),
Philip Reames9818dd72015-06-26 22:04:34 +00004139 "gc.relocate operand #2 must be integer offset", CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004140
Philip Reames9818dd72015-06-26 22:04:34 +00004141 Value* Derived = CS.getArgOperand(2);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004142 Assert(isa<ConstantInt>(Derived),
Philip Reames9818dd72015-06-26 22:04:34 +00004143 "gc.relocate operand #3 must be integer offset", CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004144
4145 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
4146 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
4147 // Check the bounds
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004148 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
Philip Reames9818dd72015-06-26 22:04:34 +00004149 "gc.relocate: statepoint base index out of bounds", CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004150 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
Philip Reames9818dd72015-06-26 22:04:34 +00004151 "gc.relocate: statepoint derived index out of bounds", CS);
Philip Reames76ebd152015-01-07 22:48:01 +00004152
4153 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004154 // section of the statepoint's argument.
Owen Anderson3e7e67b2015-03-10 05:58:21 +00004155 Assert(StatepointCS.arg_size() > 0,
4156 "gc.statepoint: insufficient arguments");
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004157 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
Owen Andersona3c68fd2015-03-11 06:57:30 +00004158 "gc.statement: number of call arguments must be constant integer");
Owen Anderson3e7e67b2015-03-10 05:58:21 +00004159 const unsigned NumCallArgs =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004160 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
4161 Assert(StatepointCS.arg_size() > NumCallArgs + 5,
Owen Anderson3e7e67b2015-03-10 05:58:21 +00004162 "gc.statepoint: mismatch in number of call arguments");
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004163 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
Pat Gavlincc0431d2015-05-08 18:07:42 +00004164 "gc.statepoint: number of transition arguments must be "
4165 "a constant integer");
4166 const int NumTransitionArgs =
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +00004167 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
4168 ->getZExtValue();
4169 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
Pat Gavlincc0431d2015-05-08 18:07:42 +00004170 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
Owen Andersona3c68fd2015-03-11 06:57:30 +00004171 "gc.statepoint: number of deoptimization arguments must be "
4172 "a constant integer");
Philip Reames76ebd152015-01-07 22:48:01 +00004173 const int NumDeoptArgs =
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004174 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))
4175 ->getZExtValue();
Pat Gavlincc0431d2015-05-08 18:07:42 +00004176 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
Philip Reames76ebd152015-01-07 22:48:01 +00004177 const int GCParamArgsEnd = StatepointCS.arg_size();
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004178 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
4179 "gc.relocate: statepoint base index doesn't fall within the "
4180 "'gc parameters' section of the statepoint call",
Philip Reames9818dd72015-06-26 22:04:34 +00004181 CS);
Benjamin Kramerf027ad72015-03-07 21:15:40 +00004182 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
4183 "gc.relocate: statepoint derived index doesn't fall within the "
4184 "'gc parameters' section of the statepoint call",
Philip Reames9818dd72015-06-26 22:04:34 +00004185 CS);
Philip Reames38303a32014-12-03 19:53:15 +00004186
Philip Reames3e2cf532016-01-07 03:32:11 +00004187 // Relocated value must be either a pointer type or vector-of-pointer type,
4188 // but gc_relocate does not need to return the same pointer type as the
4189 // relocated pointer. It can be casted to the correct type later if it's
4190 // desired. However, they must have the same address space and 'vectorness'
Manuel Jacob83eefa62016-01-05 04:03:00 +00004191 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction());
Philip Reames3e2cf532016-01-07 03:32:11 +00004192 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(),
Philip Reames9818dd72015-06-26 22:04:34 +00004193 "gc.relocate: relocated value must be a gc pointer", CS);
Chen Li6d8635a2015-05-18 19:50:14 +00004194
Philip Reames3e2cf532016-01-07 03:32:11 +00004195 auto ResultType = CS.getType();
4196 auto DerivedType = Relocate.getDerivedPtr()->getType();
4197 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
Sanjay Patelbbdab7a2016-01-31 16:32:23 +00004198 "gc.relocate: vector relocates to vector and pointer to pointer",
4199 CS);
4200 Assert(
4201 ResultType->getPointerAddressSpace() ==
4202 DerivedType->getPointerAddressSpace(),
4203 "gc.relocate: relocating a pointer shouldn't change its address space",
4204 CS);
Philip Reames337c4bd2014-12-01 21:18:12 +00004205 break;
4206 }
Reid Kleckner72ba7042015-10-07 00:27:33 +00004207 case Intrinsic::eh_exceptioncode:
Joseph Tremoulet61efbc32015-09-03 09:15:32 +00004208 case Intrinsic::eh_exceptionpointer: {
4209 Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
4210 "eh.exceptionpointer argument must be a catchpad", CS);
4211 break;
4212 }
Philip Reamesf16d7812016-02-09 21:43:12 +00004213 case Intrinsic::masked_load: {
4214 Assert(CS.getType()->isVectorTy(), "masked_load: must return a vector", CS);
4215
4216 Value *Ptr = CS.getArgOperand(0);
4217 //Value *Alignment = CS.getArgOperand(1);
4218 Value *Mask = CS.getArgOperand(2);
4219 Value *PassThru = CS.getArgOperand(3);
4220 Assert(Mask->getType()->isVectorTy(),
4221 "masked_load: mask must be vector", CS);
4222
4223 // DataTy is the overloaded type
4224 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4225 Assert(DataTy == CS.getType(),
4226 "masked_load: return must match pointer type", CS);
4227 Assert(PassThru->getType() == DataTy,
4228 "masked_load: pass through and data type must match", CS);
4229 Assert(Mask->getType()->getVectorNumElements() ==
4230 DataTy->getVectorNumElements(),
4231 "masked_load: vector mask must be same length as data", CS);
4232 break;
4233 }
4234 case Intrinsic::masked_store: {
4235 Value *Val = CS.getArgOperand(0);
4236 Value *Ptr = CS.getArgOperand(1);
4237 //Value *Alignment = CS.getArgOperand(2);
4238 Value *Mask = CS.getArgOperand(3);
4239 Assert(Mask->getType()->isVectorTy(),
4240 "masked_store: mask must be vector", CS);
4241
4242 // DataTy is the overloaded type
4243 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4244 Assert(DataTy == Val->getType(),
4245 "masked_store: storee must match pointer type", CS);
4246 Assert(Mask->getType()->getVectorNumElements() ==
4247 DataTy->getVectorNumElements(),
4248 "masked_store: vector mask must be same length as data", CS);
4249 break;
4250 }
Sanjoy Dasb51325d2016-03-11 19:08:34 +00004251
Sanjoy Das021de052016-03-31 00:18:46 +00004252 case Intrinsic::experimental_guard: {
4253 Assert(CS.isCall(), "experimental_guard cannot be invoked", CS);
4254 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
4255 "experimental_guard must have exactly one "
4256 "\"deopt\" operand bundle");
4257 break;
4258 }
4259
Sanjoy Dasb51325d2016-03-11 19:08:34 +00004260 case Intrinsic::experimental_deoptimize: {
4261 Assert(CS.isCall(), "experimental_deoptimize cannot be invoked", CS);
4262 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1,
4263 "experimental_deoptimize must have exactly one "
4264 "\"deopt\" operand bundle");
4265 Assert(CS.getType() == CS.getInstruction()->getFunction()->getReturnType(),
4266 "experimental_deoptimize return type must match caller return type");
4267
4268 if (CS.isCall()) {
4269 auto *DeoptCI = CS.getInstruction();
4270 auto *RI = dyn_cast<ReturnInst>(DeoptCI->getNextNode());
4271 Assert(RI,
4272 "calls to experimental_deoptimize must be followed by a return");
4273
4274 if (!CS.getType()->isVoidTy() && RI)
4275 Assert(RI->getReturnValue() == DeoptCI,
4276 "calls to experimental_deoptimize must be followed by a return "
4277 "of the value computed by experimental_deoptimize");
4278 }
4279
4280 break;
4281 }
Philip Reames337c4bd2014-12-01 21:18:12 +00004282 };
Chris Lattner0e851da2002-04-18 20:37:37 +00004283}
4284
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004285/// \brief Carefully grab the subprogram from a local scope.
4286///
4287/// This carefully grabs the subprogram from a local scope, avoiding the
4288/// built-in assertions that would typically fire.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004289static DISubprogram *getSubprogram(Metadata *LocalScope) {
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004290 if (!LocalScope)
4291 return nullptr;
4292
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004293 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004294 return SP;
4295
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004296 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004297 return getSubprogram(LB->getRawScope());
4298
4299 // Just return null; broken scope chains are checked elsewhere.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004300 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004301 return nullptr;
4302}
4303
Andrew Kaylora0a11642017-01-26 23:27:59 +00004304void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
4305 Assert(isa<MetadataAsValue>(FPI.getOperand(2)),
4306 "invalid rounding mode argument", &FPI);
4307 Assert(FPI.getRoundingMode() != ConstrainedFPIntrinsic::rmInvalid,
4308 "invalid rounding mode argument", &FPI);
4309 Assert(FPI.getExceptionBehavior() != ConstrainedFPIntrinsic::ebInvalid,
4310 "invalid exception behavior argument", &FPI);
4311}
4312
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004313template <class DbgIntrinsicTy>
4314void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
4315 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
Adrian Prantl541a9c52016-05-06 19:26:47 +00004316 AssertDI(isa<ValueAsMetadata>(MD) ||
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004317 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
4318 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
Adrian Prantl541a9c52016-05-06 19:26:47 +00004319 AssertDI(isa<DILocalVariable>(DII.getRawVariable()),
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004320 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
4321 DII.getRawVariable());
Adrian Prantl541a9c52016-05-06 19:26:47 +00004322 AssertDI(isa<DIExpression>(DII.getRawExpression()),
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004323 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
4324 DII.getRawExpression());
Duncan P. N. Exon Smith81f522a2015-04-03 16:54:30 +00004325
4326 // Ignore broken !dbg attachments; they're checked elsewhere.
4327 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004328 if (!isa<DILocation>(N))
Duncan P. N. Exon Smith81f522a2015-04-03 16:54:30 +00004329 return;
4330
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004331 BasicBlock *BB = DII.getParent();
4332 Function *F = BB ? BB->getParent() : nullptr;
4333
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00004334 // The scopes for variables and !dbg attachments must agree.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004335 DILocalVariable *Var = DII.getVariable();
4336 DILocation *Loc = DII.getDebugLoc();
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004337 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
4338 &DII, BB, F);
4339
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004340 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
4341 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
Duncan P. N. Exon Smithf17f34e2015-04-15 22:15:46 +00004342 if (!VarSP || !LocSP)
4343 return; // Broken scope chains are checked elsewhere.
4344
Adrian Prantla2ef0472016-09-14 17:30:37 +00004345 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
4346 " variable and !dbg attachment",
4347 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
4348 Loc->getScope()->getSubprogram());
Adrian Prantl612ac862017-02-28 23:48:42 +00004349
4350 verifyFnArgs(DII);
Duncan P. N. Exon Smith166121a2015-03-15 01:21:30 +00004351}
4352
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00004353static uint64_t getVariableSize(const DILocalVariable &V) {
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004354 // Be careful of broken types (checked elsewhere).
4355 const Metadata *RawType = V.getRawType();
4356 while (RawType) {
4357 // Try to get the size directly.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004358 if (auto *T = dyn_cast<DIType>(RawType))
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004359 if (uint64_t Size = T->getSizeInBits())
4360 return Size;
4361
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004362 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004363 // Look at the base type.
4364 RawType = DT->getRawBaseType();
4365 continue;
4366 }
4367
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004368 // Missing type or size.
4369 break;
4370 }
4371
4372 // Fail gracefully.
4373 return 0;
4374}
4375
Adrian Prantl941fa752016-12-05 18:04:47 +00004376void Verifier::verifyFragmentExpression(const DbgInfoIntrinsic &I) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004377 DILocalVariable *V;
4378 DIExpression *E;
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004379 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004380 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
4381 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004382 } else {
4383 auto *DDI = cast<DbgDeclareInst>(&I);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00004384 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
4385 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004386 }
4387
4388 // We don't know whether this intrinsic verified correctly.
4389 if (!V || !E || !E->isValid())
4390 return;
4391
Keno Fischer253a7bd2016-01-15 02:12:38 +00004392 // Nothing to do if this isn't a bit piece expression.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004393 auto Fragment = E->getFragmentInfo();
4394 if (!Fragment)
Keno Fischer253a7bd2016-01-15 02:12:38 +00004395 return;
4396
Adrian Prantlba6ec4b2015-04-29 16:52:17 +00004397 // The frontend helps out GDB by emitting the members of local anonymous
4398 // unions as artificial local variables with shared storage. When SROA splits
4399 // the storage for artificial local variables that are smaller than the entire
4400 // union, the overhang piece will be outside of the allotted space for the
4401 // variable and this check fails.
4402 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
4403 if (V->isArtificial())
4404 return;
4405
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004406 // If there's no size, the type is broken, but that should be checked
4407 // elsewhere.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00004408 uint64_t VarSize = getVariableSize(*V);
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004409 if (!VarSize)
4410 return;
4411
Adrian Prantl49797ca2016-12-22 05:27:12 +00004412 unsigned FragSize = Fragment->SizeInBits;
4413 unsigned FragOffset = Fragment->OffsetInBits;
Adrian Prantl941fa752016-12-05 18:04:47 +00004414 AssertDI(FragSize + FragOffset <= VarSize,
4415 "fragment is larger than or outside of variable", &I, V, E);
4416 AssertDI(FragSize != VarSize, "fragment covers entire variable", &I, V, E);
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00004417}
4418
Adrian Prantl612ac862017-02-28 23:48:42 +00004419void Verifier::verifyFnArgs(const DbgInfoIntrinsic &I) {
Adrian Prantl63d96952017-03-07 17:28:54 +00004420 // This function does not take the scope of noninlined function arguments into
4421 // account. Don't run it if current function is nodebug, because it may
4422 // contain inlined debug intrinsics.
4423 if (!HasDebugInfo)
4424 return;
4425
Adrian Prantl612ac862017-02-28 23:48:42 +00004426 DILocalVariable *Var;
4427 if (auto *DV = dyn_cast<DbgValueInst>(&I)) {
4428 // For performance reasons only check non-inlined ones.
4429 if (DV->getDebugLoc()->getInlinedAt())
4430 return;
4431 Var = DV->getVariable();
4432 } else {
4433 auto *DD = cast<DbgDeclareInst>(&I);
4434 if (DD->getDebugLoc()->getInlinedAt())
4435 return;
4436 Var = DD->getVariable();
4437 }
4438 AssertDI(Var, "dbg intrinsic without variable");
4439
4440 unsigned ArgNo = Var->getArg();
4441 if (!ArgNo)
4442 return;
4443
4444 // Verify there are no duplicate function argument debug info entries.
4445 // These will cause hard-to-debug assertions in the DWARF backend.
4446 if (DebugFnArgs.size() < ArgNo)
4447 DebugFnArgs.resize(ArgNo, nullptr);
4448
4449 auto *Prev = DebugFnArgs[ArgNo - 1];
4450 DebugFnArgs[ArgNo - 1] = Var;
4451 AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I,
4452 Prev, Var);
4453}
4454
Adrian Prantlfaebbb02016-03-28 21:06:26 +00004455void Verifier::verifyCompileUnits() {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004456 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
Adrian Prantlfaebbb02016-03-28 21:06:26 +00004457 SmallPtrSet<const Metadata *, 2> Listed;
4458 if (CUs)
4459 Listed.insert(CUs->op_begin(), CUs->op_end());
Davide Italianoa9de0102017-02-20 22:51:42 +00004460 for (auto *CU : CUVisited)
4461 AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
Adrian Prantlfaebbb02016-03-28 21:06:26 +00004462 CUVisited.clear();
4463}
4464
Sanjoy Dase0aa4142016-05-12 01:17:38 +00004465void Verifier::verifyDeoptimizeCallingConvs() {
4466 if (DeoptimizeDeclarations.empty())
4467 return;
4468
4469 const Function *First = DeoptimizeDeclarations[0];
Sanjoy Das8d3b1792016-05-12 01:38:08 +00004470 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) {
Sanjoy Dase0aa4142016-05-12 01:17:38 +00004471 Assert(First->getCallingConv() == F->getCallingConv(),
4472 "All llvm.experimental.deoptimize declarations must have the same "
4473 "calling convention",
4474 First, F);
Sanjoy Das8d3b1792016-05-12 01:38:08 +00004475 }
Sanjoy Dase0aa4142016-05-12 01:17:38 +00004476}
4477
Chris Lattner0e851da2002-04-18 20:37:37 +00004478//===----------------------------------------------------------------------===//
4479// Implement the public interfaces to this file...
4480//===----------------------------------------------------------------------===//
4481
Chandler Carruth043949d2014-01-19 02:22:18 +00004482bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
Chandler Carruthbf2b6522014-01-17 11:09:34 +00004483 Function &F = const_cast<Function &>(f);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004484
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +00004485 // Don't use a raw_null_ostream. Printing IR is expensive.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004486 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
Chandler Carruth043949d2014-01-19 02:22:18 +00004487
4488 // Note that this function's return value is inverted from what you would
4489 // expect of a function called "verify".
4490 return !V.verify(F);
Chris Lattnerd02f08d2002-02-20 17:55:43 +00004491}
4492
Adrian Prantlfe7a3822016-05-09 19:57:15 +00004493bool llvm::verifyModule(const Module &M, raw_ostream *OS,
4494 bool *BrokenDebugInfo) {
Duncan P. N. Exon Smithe8fc69d2016-04-20 16:17:37 +00004495 // Don't use a raw_null_ostream. Printing IR is expensive.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004496 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
Nick Lewycky3fc89802009-09-07 20:44:51 +00004497
Chandler Carruth043949d2014-01-19 02:22:18 +00004498 bool Broken = false;
Sanjay Patel1f26bcf2016-02-25 16:44:27 +00004499 for (const Function &F : M)
Peter Collingbournebb738172016-06-06 23:21:27 +00004500 Broken |= !V.verify(F);
Chandler Carruth043949d2014-01-19 02:22:18 +00004501
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004502 Broken |= !V.verify();
Adrian Prantlfe7a3822016-05-09 19:57:15 +00004503 if (BrokenDebugInfo)
4504 *BrokenDebugInfo = V.hasBrokenDebugInfo();
Chandler Carruth043949d2014-01-19 02:22:18 +00004505 // Note that this function's return value is inverted from what you would
4506 // expect of a function called "verify".
Adrian Prantlfe7a3822016-05-09 19:57:15 +00004507 return Broken;
Chris Lattner2f7c9632001-06-06 20:29:01 +00004508}
Chandler Carruth043949d2014-01-19 02:22:18 +00004509
4510namespace {
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00004511
Chandler Carruth4d356312014-01-20 11:34:08 +00004512struct VerifierLegacyPass : public FunctionPass {
Chandler Carruth043949d2014-01-19 02:22:18 +00004513 static char ID;
4514
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004515 std::unique_ptr<Verifier> V;
Adrian Prantl94a903e2016-05-25 21:33:20 +00004516 bool FatalErrors = true;
Chandler Carruth043949d2014-01-19 02:22:18 +00004517
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004518 VerifierLegacyPass() : FunctionPass(ID) {
Chandler Carruth4d356312014-01-20 11:34:08 +00004519 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth043949d2014-01-19 02:22:18 +00004520 }
Chandler Carruth4d356312014-01-20 11:34:08 +00004521 explicit VerifierLegacyPass(bool FatalErrors)
Adrian Prantl541a9c52016-05-06 19:26:47 +00004522 : FunctionPass(ID),
Adrian Prantl541a9c52016-05-06 19:26:47 +00004523 FatalErrors(FatalErrors) {
Chandler Carruth4d356312014-01-20 11:34:08 +00004524 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruth043949d2014-01-19 02:22:18 +00004525 }
4526
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004527 bool doInitialization(Module &M) override {
4528 V = llvm::make_unique<Verifier>(
4529 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
4530 return false;
4531 }
4532
Craig Topperf398d7c2014-03-05 06:35:38 +00004533 bool runOnFunction(Function &F) override {
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004534 if (!V->verify(F) && FatalErrors)
Chandler Carruth043949d2014-01-19 02:22:18 +00004535 report_fatal_error("Broken function found, compilation aborted!");
4536
4537 return false;
4538 }
4539
Craig Topperf398d7c2014-03-05 06:35:38 +00004540 bool doFinalization(Module &M) override {
Peter Collingbournebb738172016-06-06 23:21:27 +00004541 bool HasErrors = false;
4542 for (Function &F : M)
4543 if (F.isDeclaration())
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004544 HasErrors |= !V->verify(F);
Peter Collingbournebb738172016-06-06 23:21:27 +00004545
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004546 HasErrors |= !V->verify();
Adrian Prantl94a903e2016-05-25 21:33:20 +00004547 if (FatalErrors) {
4548 if (HasErrors)
4549 report_fatal_error("Broken module found, compilation aborted!");
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004550 assert(!V->hasBrokenDebugInfo() && "Module contains invalid debug info");
Adrian Prantl94a903e2016-05-25 21:33:20 +00004551 }
Chandler Carruth043949d2014-01-19 02:22:18 +00004552
Adrian Prantl94a903e2016-05-25 21:33:20 +00004553 // Strip broken debug info.
Sanjoy Das4b54b7f2016-08-02 01:34:50 +00004554 if (V->hasBrokenDebugInfo()) {
Adrian Prantl94a903e2016-05-25 21:33:20 +00004555 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M);
4556 M.getContext().diagnose(DiagInvalid);
4557 if (!StripDebugInfo(M))
4558 report_fatal_error("Failed to strip malformed debug info");
4559 }
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +00004560 return false;
4561 }
4562
4563 void getAnalysisUsage(AnalysisUsage &AU) const override {
4564 AU.setPreservesAll();
4565 }
4566};
Eugene Zelenko3e3a0572016-08-13 00:50:41 +00004567
4568} // end anonymous namespace
Chandler Carruth043949d2014-01-19 02:22:18 +00004569
Mehdi Aminia84a8402016-12-16 06:29:14 +00004570/// Helper to issue failure from the TBAA verification
4571template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
4572 if (Diagnostic)
4573 return Diagnostic->CheckFailed(Args...);
4574}
4575
4576#define AssertTBAA(C, ...) \
4577 do { \
4578 if (!(C)) { \
4579 CheckFailed(__VA_ARGS__); \
4580 return false; \
4581 } \
4582 } while (false)
4583
4584/// Verify that \p BaseNode can be used as the "base type" in the struct-path
4585/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
4586/// struct-type node describing an aggregate data structure (like a struct).
4587TBAAVerifier::TBAABaseNodeSummary
Sanjoy Das600d2a52016-12-29 15:47:01 +00004588TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode) {
Mehdi Aminia84a8402016-12-16 06:29:14 +00004589 if (BaseNode->getNumOperands() < 2) {
4590 CheckFailed("Base nodes must have at least two operands", &I, BaseNode);
4591 return {true, ~0u};
4592 }
4593
4594 auto Itr = TBAABaseNodes.find(BaseNode);
4595 if (Itr != TBAABaseNodes.end())
4596 return Itr->second;
4597
4598 auto Result = verifyTBAABaseNodeImpl(I, BaseNode);
4599 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
4600 (void)InsertResult;
4601 assert(InsertResult.second && "We just checked!");
4602 return Result;
4603}
4604
4605TBAAVerifier::TBAABaseNodeSummary
Sanjoy Das600d2a52016-12-29 15:47:01 +00004606TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode) {
Mehdi Aminia84a8402016-12-16 06:29:14 +00004607 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
4608
4609 if (BaseNode->getNumOperands() == 2) {
Mehdi Aminia84a8402016-12-16 06:29:14 +00004610 // Scalar nodes can only be accessed at offset 0.
Sanjoy Das00d76a52016-12-29 15:47:05 +00004611 return isValidScalarTBAANode(BaseNode)
4612 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
4613 : InvalidNode;
Mehdi Aminia84a8402016-12-16 06:29:14 +00004614 }
4615
4616 if (BaseNode->getNumOperands() % 2 != 1) {
4617 CheckFailed("Struct tag nodes must have an odd number of operands!",
4618 BaseNode);
4619 return InvalidNode;
4620 }
4621
Sanjoy Das00d76a52016-12-29 15:47:05 +00004622 if (!isa<MDString>(BaseNode->getOperand(0))) {
4623 CheckFailed("Struct tag nodes have a string as their first operand",
4624 BaseNode);
4625 return InvalidNode;
4626 }
4627
Mehdi Aminia84a8402016-12-16 06:29:14 +00004628 bool Failed = false;
4629
4630 Optional<APInt> PrevOffset;
4631 unsigned BitWidth = ~0u;
4632
4633 // We've already checked that BaseNode is not a degenerate root node with one
4634 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
4635 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) {
4636 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
4637 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
4638 if (!isa<MDNode>(FieldTy)) {
4639 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode);
4640 Failed = true;
4641 continue;
4642 }
4643
4644 auto *OffsetEntryCI =
4645 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
4646 if (!OffsetEntryCI) {
4647 CheckFailed("Offset entries must be constants!", &I, BaseNode);
4648 Failed = true;
4649 continue;
4650 }
4651
4652 if (BitWidth == ~0u)
4653 BitWidth = OffsetEntryCI->getBitWidth();
4654
4655 if (OffsetEntryCI->getBitWidth() != BitWidth) {
4656 CheckFailed(
4657 "Bitwidth between the offsets and struct type entries must match", &I,
4658 BaseNode);
4659 Failed = true;
4660 continue;
4661 }
4662
4663 // NB! As far as I can tell, we generate a non-strictly increasing offset
4664 // sequence only from structs that have zero size bit fields. When
4665 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
4666 // pick the field lexically the latest in struct type metadata node. This
4667 // mirrors the actual behavior of the alias analysis implementation.
4668 bool IsAscending =
4669 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
4670
4671 if (!IsAscending) {
4672 CheckFailed("Offsets must be increasing!", &I, BaseNode);
4673 Failed = true;
4674 }
4675
4676 PrevOffset = OffsetEntryCI->getValue();
4677 }
4678
4679 return Failed ? InvalidNode
4680 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
4681}
4682
4683static bool IsRootTBAANode(const MDNode *MD) {
4684 return MD->getNumOperands() < 2;
4685}
4686
4687static bool IsScalarTBAANodeImpl(const MDNode *MD,
4688 SmallPtrSetImpl<const MDNode *> &Visited) {
Sanjoy Das00d76a52016-12-29 15:47:05 +00004689 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
Mehdi Aminia84a8402016-12-16 06:29:14 +00004690 return false;
4691
Sanjoy Das00d76a52016-12-29 15:47:05 +00004692 if (!isa<MDString>(MD->getOperand(0)))
Mehdi Aminia84a8402016-12-16 06:29:14 +00004693 return false;
4694
Sanjoy Das00d76a52016-12-29 15:47:05 +00004695 if (MD->getNumOperands() == 3) {
4696 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
4697 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
4698 return false;
4699 }
4700
4701 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
4702 return Parent && Visited.insert(Parent).second &&
Mehdi Aminia84a8402016-12-16 06:29:14 +00004703 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
4704}
4705
Sanjoy Das55f12d92016-12-29 15:46:57 +00004706bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
4707 auto ResultIt = TBAAScalarNodes.find(MD);
4708 if (ResultIt != TBAAScalarNodes.end())
4709 return ResultIt->second;
4710
Mehdi Aminia84a8402016-12-16 06:29:14 +00004711 SmallPtrSet<const MDNode *, 4> Visited;
Sanjoy Das55f12d92016-12-29 15:46:57 +00004712 bool Result = IsScalarTBAANodeImpl(MD, Visited);
4713 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
4714 (void)InsertResult;
4715 assert(InsertResult.second && "Just checked!");
4716
4717 return Result;
Mehdi Aminia84a8402016-12-16 06:29:14 +00004718}
4719
4720/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
4721/// Offset in place to be the offset within the field node returned.
4722///
4723/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
4724MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I,
Sanjoy Das600d2a52016-12-29 15:47:01 +00004725 const MDNode *BaseNode,
Mehdi Aminia84a8402016-12-16 06:29:14 +00004726 APInt &Offset) {
4727 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
4728
4729 // Scalar nodes have only one possible "field" -- their parent in the access
4730 // hierarchy. Offset must be zero at this point, but our caller is supposed
4731 // to Assert that.
4732 if (BaseNode->getNumOperands() == 2)
4733 return cast<MDNode>(BaseNode->getOperand(1));
4734
4735 for (unsigned Idx = 1; Idx < BaseNode->getNumOperands(); Idx += 2) {
4736 auto *OffsetEntryCI =
4737 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
4738 if (OffsetEntryCI->getValue().ugt(Offset)) {
4739 if (Idx == 1) {
4740 CheckFailed("Could not find TBAA parent in struct type node", &I,
4741 BaseNode, &Offset);
4742 return nullptr;
4743 }
4744
4745 auto *PrevOffsetEntryCI =
4746 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx - 1));
4747 Offset -= PrevOffsetEntryCI->getValue();
4748 return cast<MDNode>(BaseNode->getOperand(Idx - 2));
4749 }
4750 }
4751
4752 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
4753 BaseNode->getOperand(BaseNode->getNumOperands() - 1));
4754
4755 Offset -= LastOffsetEntryCI->getValue();
4756 return cast<MDNode>(BaseNode->getOperand(BaseNode->getNumOperands() - 2));
4757}
4758
Sanjoy Das600d2a52016-12-29 15:47:01 +00004759bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) {
Mehdi Aminia84a8402016-12-16 06:29:14 +00004760 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
Sanjoy Das600d2a52016-12-29 15:47:01 +00004761 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
4762 isa<AtomicCmpXchgInst>(I),
Mehdi Aminia84a8402016-12-16 06:29:14 +00004763 "TBAA is only for loads, stores and calls!", &I);
4764
4765 bool IsStructPathTBAA =
4766 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
4767
4768 AssertTBAA(
4769 IsStructPathTBAA,
4770 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
4771
4772 AssertTBAA(MD->getNumOperands() < 5,
4773 "Struct tag metadata must have either 3 or 4 operands", &I, MD);
4774
4775 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
4776 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
4777
4778 if (MD->getNumOperands() == 4) {
4779 auto *IsImmutableCI =
4780 mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(3));
4781 AssertTBAA(IsImmutableCI,
4782 "Immutability tag on struct tag metadata must be a constant", &I,
4783 MD);
4784 AssertTBAA(
4785 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
4786 "Immutability part of the struct tag metadata must be either 0 or 1",
4787 &I, MD);
4788 }
4789
4790 AssertTBAA(BaseNode && AccessType,
4791 "Malformed struct tag metadata: base and access-type "
4792 "should be non-null and point to Metadata nodes",
4793 &I, MD, BaseNode, AccessType);
4794
Sanjoy Das55f12d92016-12-29 15:46:57 +00004795 AssertTBAA(isValidScalarTBAANode(AccessType),
Sanjoy Das00d76a52016-12-29 15:47:05 +00004796 "Access type node must be a valid scalar type", &I, MD,
4797 AccessType);
Mehdi Aminia84a8402016-12-16 06:29:14 +00004798
4799 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2));
4800 AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD);
4801
4802 APInt Offset = OffsetCI->getValue();
4803 bool SeenAccessTypeInPath = false;
4804
4805 SmallPtrSet<MDNode *, 4> StructPath;
4806
4807 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
4808 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset)) {
4809 if (!StructPath.insert(BaseNode).second) {
4810 CheckFailed("Cycle detected in struct path", &I, MD);
4811 return false;
4812 }
4813
4814 bool Invalid;
4815 unsigned BaseNodeBitWidth;
4816 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode);
4817
4818 // If the base node is invalid in itself, then we've already printed all the
4819 // errors we wanted to print.
4820 if (Invalid)
4821 return false;
4822
4823 SeenAccessTypeInPath |= BaseNode == AccessType;
4824
Sanjoy Das55f12d92016-12-29 15:46:57 +00004825 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
Mehdi Aminia84a8402016-12-16 06:29:14 +00004826 AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access",
4827 &I, MD, &Offset);
4828
4829 AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
4830 (BaseNodeBitWidth == 0 && Offset == 0),
4831 "Access bit-width not the same as description bit-width", &I, MD,
4832 BaseNodeBitWidth, Offset.getBitWidth());
4833 }
4834
4835 AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!",
4836 &I, MD);
4837 return true;
4838}
4839
Chandler Carruth4d356312014-01-20 11:34:08 +00004840char VerifierLegacyPass::ID = 0;
4841INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
Chandler Carruth043949d2014-01-19 02:22:18 +00004842
4843FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
Chandler Carruth4d356312014-01-20 11:34:08 +00004844 return new VerifierLegacyPass(FatalErrors);
Chandler Carruth043949d2014-01-19 02:22:18 +00004845}
4846
Chandler Carruthdab4eae2016-11-23 17:53:26 +00004847AnalysisKey VerifierAnalysis::Key;
Chandler Carruth164a2aa62016-06-17 00:11:01 +00004848VerifierAnalysis::Result VerifierAnalysis::run(Module &M,
4849 ModuleAnalysisManager &) {
Adrian Prantle3656182016-05-09 19:57:29 +00004850 Result Res;
4851 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken);
4852 return Res;
4853}
Chandler Carruth4d356312014-01-20 11:34:08 +00004854
Chandler Carruth164a2aa62016-06-17 00:11:01 +00004855VerifierAnalysis::Result VerifierAnalysis::run(Function &F,
4856 FunctionAnalysisManager &) {
Adrian Prantle3656182016-05-09 19:57:29 +00004857 return { llvm::verifyFunction(F, &dbgs()), false };
4858}
4859
4860PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) {
4861 auto Res = AM.getResult<VerifierAnalysis>(M);
4862 if (FatalErrors) {
4863 if (Res.IRBroken)
4864 report_fatal_error("Broken module found, compilation aborted!");
4865 assert(!Res.DebugInfoBroken && "Module contains invalid debug info");
4866 }
4867
4868 // Strip broken debug info.
4869 if (Res.DebugInfoBroken) {
4870 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M);
4871 M.getContext().diagnose(DiagInvalid);
4872 if (!StripDebugInfo(M))
4873 report_fatal_error("Failed to strip malformed debug info");
4874 }
Chandler Carruth4d356312014-01-20 11:34:08 +00004875 return PreservedAnalyses::all();
4876}
4877
Adrian Prantle3656182016-05-09 19:57:29 +00004878PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
4879 auto res = AM.getResult<VerifierAnalysis>(F);
4880 if (res.IRBroken && FatalErrors)
Chandler Carruth4d356312014-01-20 11:34:08 +00004881 report_fatal_error("Broken function found, compilation aborted!");
4882
4883 return PreservedAnalyses::all();
4884}