Bug Summary

File:lib/Transforms/IPO/IPConstantPropagation.cpp
Warning:line 90, column 16
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name IPConstantPropagation.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Transforms/IPO -I /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/IPO -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/lib/Transforms/IPO -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/IPO/IPConstantPropagation.cpp

/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/IPO/IPConstantPropagation.cpp

1//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements an _extremely_ simple interprocedural constant
10// propagation pass. It could certainly be improved in many different ways,
11// like using a worklist. This pass makes arguments dead, but does not remove
12// them. The existing dead argument elimination pass should be run after this
13// to clean up the mess.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/CallSite.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Transforms/IPO.h"
26using namespace llvm;
27
28#define DEBUG_TYPE"ipconstprop" "ipconstprop"
29
30STATISTIC(NumArgumentsProped, "Number of args turned into constants")static llvm::Statistic NumArgumentsProped = {"ipconstprop", "NumArgumentsProped"
, "Number of args turned into constants"}
;
31STATISTIC(NumReturnValProped, "Number of return values turned into constants")static llvm::Statistic NumReturnValProped = {"ipconstprop", "NumReturnValProped"
, "Number of return values turned into constants"}
;
32
33namespace {
34 /// IPCP - The interprocedural constant propagation pass
35 ///
36 struct IPCP : public ModulePass {
37 static char ID; // Pass identification, replacement for typeid
38 IPCP() : ModulePass(ID) {
39 initializeIPCPPass(*PassRegistry::getPassRegistry());
40 }
41
42 bool runOnModule(Module &M) override;
43 };
44}
45
46/// PropagateConstantsIntoArguments - Look at all uses of the specified
47/// function. If all uses are direct call sites, and all pass a particular
48/// constant in for an argument, propagate that constant in as the argument.
49///
50static bool PropagateConstantsIntoArguments(Function &F) {
51 if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
8
Assuming the condition is false
9
Calling 'Value::use_empty'
12
Returning from 'Value::use_empty'
13
Taking false branch
52
53 // For each argument, keep track of its constant value and whether it is a
54 // constant or not. The bool is driven to true when found to be non-constant.
55 SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
56 ArgumentConstants.resize(F.arg_size());
57
58 unsigned NumNonconstant = 0;
59 for (Use &U : F.uses()) {
60 User *UR = U.getUser();
61 // Ignore blockaddress uses.
62 if (isa<BlockAddress>(UR)) continue;
14
Assuming 'UR' is not a 'BlockAddress'
15
Taking false branch
63
64 // If no abstract call site was created we did not understand the use, bail.
65 AbstractCallSite ACS(&U);
66 if (!ACS)
16
Assuming the condition is false
17
Taking false branch
67 return false;
68
69 // Mismatched argument count is undefined behavior. Simply bail out to avoid
70 // handling of such situations below (avoiding asserts/crashes).
71 unsigned NumActualArgs = ACS.getNumArgOperands();
72 if (F.isVarArg() ? ArgumentConstants.size() > NumActualArgs
18
Assuming the condition is false
19
'?' condition is false
21
Taking false branch
73 : ArgumentConstants.size() != NumActualArgs)
20
Assuming the condition is false
74 return false;
75
76 // Check out all of the potentially constant arguments. Note that we don't
77 // inspect varargs here.
78 Function::arg_iterator Arg = F.arg_begin();
79 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++Arg) {
22
Assuming 'i' is not equal to 'e'
23
Loop condition is true. Entering loop body
29
Null pointer value stored to 'Arg'
30
Assuming 'i' is not equal to 'e'
31
Loop condition is true. Entering loop body
80
81 // If this argument is known non-constant, ignore it.
82 if (ArgumentConstants[i].second)
24
Assuming field 'second' is false
25
Taking false branch
32
Assuming field 'second' is false
33
Taking false branch
83 continue;
84
85 Value *V = ACS.getCallArgOperand(i);
86 Constant *C = dyn_cast_or_null<Constant>(V);
26
Assuming null pointer is passed into cast
34
Assuming 'V' is a 'Constant'
87
88 // Mismatched argument type is undefined behavior. Simply bail out to avoid
89 // handling of such situations below (avoiding asserts/crashes).
90 if (C
26.1
'C' is null
34.1
'C' is non-null
26.1
'C' is null
34.1
'C' is non-null
&& Arg->getType() != C->getType())
35
Called C++ object pointer is null
91 return false;
92
93 // We can only propagate thread independent values through callbacks.
94 // This is different to direct/indirect call sites because for them we
95 // know the thread executing the caller and callee is the same. For
96 // callbacks this is not guaranteed, thus a thread dependent value could
97 // be different for the caller and callee, making it invalid to propagate.
98 if (C
26.2
'C' is null
26.2
'C' is null
&& ACS.isCallbackCall() && C->isThreadDependent()) {
99 // Argument became non-constant. If all arguments are non-constant now,
100 // give up on this function.
101 if (++NumNonconstant == ArgumentConstants.size())
102 return false;
103
104 ArgumentConstants[i].second = true;
105 continue;
106 }
107
108 if (C
26.3
'C' is null
26.3
'C' is null
&& ArgumentConstants[i].first == nullptr) {
109 ArgumentConstants[i].first = C; // First constant seen.
110 } else if (C
26.4
'C' is null
26.4
'C' is null
&& ArgumentConstants[i].first == C) {
111 // Still the constant value we think it is.
112 } else if (V == &*Arg) {
27
Assuming the condition is true
28
Taking true branch
113 // Ignore recursive calls passing argument down.
114 } else {
115 // Argument became non-constant. If all arguments are non-constant now,
116 // give up on this function.
117 if (++NumNonconstant == ArgumentConstants.size())
118 return false;
119 ArgumentConstants[i].second = true;
120 }
121 }
122 }
123
124 // If we got to this point, there is a constant argument!
125 assert(NumNonconstant != ArgumentConstants.size())((NumNonconstant != ArgumentConstants.size()) ? static_cast<
void> (0) : __assert_fail ("NumNonconstant != ArgumentConstants.size()"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/IPO/IPConstantPropagation.cpp"
, 125, __PRETTY_FUNCTION__))
;
126 bool MadeChange = false;
127 Function::arg_iterator AI = F.arg_begin();
128 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
129 // Do we have a constant argument?
130 if (ArgumentConstants[i].second || AI->use_empty() ||
131 AI->hasInAllocaAttr() || (AI->hasByValAttr() && !F.onlyReadsMemory()))
132 continue;
133
134 Value *V = ArgumentConstants[i].first;
135 if (!V) V = UndefValue::get(AI->getType());
136 AI->replaceAllUsesWith(V);
137 ++NumArgumentsProped;
138 MadeChange = true;
139 }
140 return MadeChange;
141}
142
143
144// Check to see if this function returns one or more constants. If so, replace
145// all callers that use those return values with the constant value. This will
146// leave in the actual return values and instructions, but deadargelim will
147// clean that up.
148//
149// Additionally if a function always returns one of its arguments directly,
150// callers will be updated to use the value they pass in directly instead of
151// using the return value.
152static bool PropagateConstantReturn(Function &F) {
153 if (F.getReturnType()->isVoidTy())
154 return false; // No return value.
155
156 // We can infer and propagate the return value only when we know that the
157 // definition we'll get at link time is *exactly* the definition we see now.
158 // For more details, see GlobalValue::mayBeDerefined.
159 if (!F.isDefinitionExact())
160 return false;
161
162 // Don't touch naked functions. The may contain asm returning
163 // value we don't see, so we may end up interprocedurally propagating
164 // the return value incorrectly.
165 if (F.hasFnAttribute(Attribute::Naked))
166 return false;
167
168 // Check to see if this function returns a constant.
169 SmallVector<Value *,4> RetVals;
170 StructType *STy = dyn_cast<StructType>(F.getReturnType());
171 if (STy)
172 for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
173 RetVals.push_back(UndefValue::get(STy->getElementType(i)));
174 else
175 RetVals.push_back(UndefValue::get(F.getReturnType()));
176
177 unsigned NumNonConstant = 0;
178 for (BasicBlock &BB : F)
179 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
180 for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
181 // Already found conflicting return values?
182 Value *RV = RetVals[i];
183 if (!RV)
184 continue;
185
186 // Find the returned value
187 Value *V;
188 if (!STy)
189 V = RI->getOperand(0);
190 else
191 V = FindInsertedValue(RI->getOperand(0), i);
192
193 if (V) {
194 // Ignore undefs, we can change them into anything
195 if (isa<UndefValue>(V))
196 continue;
197
198 // Try to see if all the rets return the same constant or argument.
199 if (isa<Constant>(V) || isa<Argument>(V)) {
200 if (isa<UndefValue>(RV)) {
201 // No value found yet? Try the current one.
202 RetVals[i] = V;
203 continue;
204 }
205 // Returning the same value? Good.
206 if (RV == V)
207 continue;
208 }
209 }
210 // Different or no known return value? Don't propagate this return
211 // value.
212 RetVals[i] = nullptr;
213 // All values non-constant? Stop looking.
214 if (++NumNonConstant == RetVals.size())
215 return false;
216 }
217 }
218
219 // If we got here, the function returns at least one constant value. Loop
220 // over all users, replacing any uses of the return value with the returned
221 // constant.
222 bool MadeChange = false;
223 for (Use &U : F.uses()) {
224 CallSite CS(U.getUser());
225 Instruction* Call = CS.getInstruction();
226
227 // Not a call instruction or a call instruction that's not calling F
228 // directly?
229 if (!Call || !CS.isCallee(&U))
230 continue;
231
232 // Call result not used?
233 if (Call->use_empty())
234 continue;
235
236 MadeChange = true;
237
238 if (!STy) {
239 Value* New = RetVals[0];
240 if (Argument *A = dyn_cast<Argument>(New))
241 // Was an argument returned? Then find the corresponding argument in
242 // the call instruction and use that.
243 New = CS.getArgument(A->getArgNo());
244 Call->replaceAllUsesWith(New);
245 continue;
246 }
247
248 for (auto I = Call->user_begin(), E = Call->user_end(); I != E;) {
249 Instruction *Ins = cast<Instruction>(*I);
250
251 // Increment now, so we can remove the use
252 ++I;
253
254 // Find the index of the retval to replace with
255 int index = -1;
256 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
257 if (EV->hasIndices())
258 index = *EV->idx_begin();
259
260 // If this use uses a specific return value, and we have a replacement,
261 // replace it.
262 if (index != -1) {
263 Value *New = RetVals[index];
264 if (New) {
265 if (Argument *A = dyn_cast<Argument>(New))
266 // Was an argument returned? Then find the corresponding argument in
267 // the call instruction and use that.
268 New = CS.getArgument(A->getArgNo());
269 Ins->replaceAllUsesWith(New);
270 Ins->eraseFromParent();
271 }
272 }
273 }
274 }
275
276 if (MadeChange) ++NumReturnValProped;
277 return MadeChange;
278}
279
280char IPCP::ID = 0;
281INITIALIZE_PASS(IPCP, "ipconstprop",static void *initializeIPCPPassOnce(PassRegistry &Registry
) { PassInfo *PI = new PassInfo( "Interprocedural constant propagation"
, "ipconstprop", &IPCP::ID, PassInfo::NormalCtor_t(callDefaultCtor
<IPCP>), false, false); Registry.registerPass(*PI, true
); return PI; } static llvm::once_flag InitializeIPCPPassFlag
; void llvm::initializeIPCPPass(PassRegistry &Registry) {
llvm::call_once(InitializeIPCPPassFlag, initializeIPCPPassOnce
, std::ref(Registry)); }
282 "Interprocedural constant propagation", false, false)static void *initializeIPCPPassOnce(PassRegistry &Registry
) { PassInfo *PI = new PassInfo( "Interprocedural constant propagation"
, "ipconstprop", &IPCP::ID, PassInfo::NormalCtor_t(callDefaultCtor
<IPCP>), false, false); Registry.registerPass(*PI, true
); return PI; } static llvm::once_flag InitializeIPCPPassFlag
; void llvm::initializeIPCPPass(PassRegistry &Registry) {
llvm::call_once(InitializeIPCPPassFlag, initializeIPCPPassOnce
, std::ref(Registry)); }
283
284ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
285
286bool IPCP::runOnModule(Module &M) {
287 if (skipModule(M))
1
Assuming the condition is false
2
Taking false branch
288 return false;
289
290 bool Changed = false;
291 bool LocalChange = true;
292
293 // FIXME: instead of using smart algorithms, we just iterate until we stop
294 // making changes.
295 while (LocalChange) {
3
Loop condition is true. Entering loop body
296 LocalChange = false;
297 for (Function &F : M)
298 if (!F.isDeclaration()) {
4
Assuming the condition is true
5
Taking true branch
299 // Delete any klingons.
300 F.removeDeadConstantUsers();
301 if (F.hasLocalLinkage())
6
Taking true branch
302 LocalChange |= PropagateConstantsIntoArguments(F);
7
Calling 'PropagateConstantsIntoArguments'
303 Changed |= PropagateConstantReturn(F);
304 }
305 Changed |= LocalChange;
306 }
307 return Changed;
308}

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h

1//===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file declares the Value class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_IR_VALUE_H
14#define LLVM_IR_VALUE_H
15
16#include "llvm-c/Types.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/iterator_range.h"
19#include "llvm/IR/Use.h"
20#include "llvm/Support/CBindingWrapping.h"
21#include "llvm/Support/Casting.h"
22#include <cassert>
23#include <iterator>
24#include <memory>
25
26namespace llvm {
27
28class APInt;
29class Argument;
30class BasicBlock;
31class Constant;
32class ConstantData;
33class ConstantAggregate;
34class DataLayout;
35class Function;
36class GlobalAlias;
37class GlobalIFunc;
38class GlobalIndirectSymbol;
39class GlobalObject;
40class GlobalValue;
41class GlobalVariable;
42class InlineAsm;
43class Instruction;
44class LLVMContext;
45class Module;
46class ModuleSlotTracker;
47class raw_ostream;
48template<typename ValueTy> class StringMapEntry;
49class StringRef;
50class Twine;
51class Type;
52class User;
53
54using ValueName = StringMapEntry<Value *>;
55
56//===----------------------------------------------------------------------===//
57// Value Class
58//===----------------------------------------------------------------------===//
59
60/// LLVM Value Representation
61///
62/// This is a very important LLVM class. It is the base class of all values
63/// computed by a program that may be used as operands to other values. Value is
64/// the super class of other important classes such as Instruction and Function.
65/// All Values have a Type. Type is not a subclass of Value. Some values can
66/// have a name and they belong to some Module. Setting the name on the Value
67/// automatically updates the module's symbol table.
68///
69/// Every value has a "use list" that keeps track of which other Values are
70/// using this Value. A Value can also have an arbitrary number of ValueHandle
71/// objects that watch it and listen to RAUW and Destroy events. See
72/// llvm/IR/ValueHandle.h for details.
73class Value {
74 // The least-significant bit of the first word of Value *must* be zero:
75 // http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm
76 Type *VTy;
77 Use *UseList;
78
79 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
80 friend class ValueHandleBase;
81
82 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
83 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
84
85protected:
86 /// Hold subclass data that can be dropped.
87 ///
88 /// This member is similar to SubclassData, however it is for holding
89 /// information which may be used to aid optimization, but which may be
90 /// cleared to zero without affecting conservative interpretation.
91 unsigned char SubclassOptionalData : 7;
92
93private:
94 /// Hold arbitrary subclass data.
95 ///
96 /// This member is defined by this class, but is not used for anything.
97 /// Subclasses can use it to hold whatever state they find useful. This
98 /// field is initialized to zero by the ctor.
99 unsigned short SubclassData;
100
101protected:
102 /// The number of operands in the subclass.
103 ///
104 /// This member is defined by this class, but not used for anything.
105 /// Subclasses can use it to store their number of operands, if they have
106 /// any.
107 ///
108 /// This is stored here to save space in User on 64-bit hosts. Since most
109 /// instances of Value have operands, 32-bit hosts aren't significantly
110 /// affected.
111 ///
112 /// Note, this should *NOT* be used directly by any class other than User.
113 /// User uses this value to find the Use list.
114 enum : unsigned { NumUserOperandsBits = 28 };
115 unsigned NumUserOperands : NumUserOperandsBits;
116
117 // Use the same type as the bitfield above so that MSVC will pack them.
118 unsigned IsUsedByMD : 1;
119 unsigned HasName : 1;
120 unsigned HasHungOffUses : 1;
121 unsigned HasDescriptor : 1;
122
123private:
124 template <typename UseT> // UseT == 'Use' or 'const Use'
125 class use_iterator_impl
126 : public std::iterator<std::forward_iterator_tag, UseT *> {
127 friend class Value;
128
129 UseT *U;
130
131 explicit use_iterator_impl(UseT *u) : U(u) {}
132
133 public:
134 use_iterator_impl() : U() {}
135
136 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
137 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
138
139 use_iterator_impl &operator++() { // Preincrement
140 assert(U && "Cannot increment end iterator!")((U && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 140, __PRETTY_FUNCTION__))
;
141 U = U->getNext();
142 return *this;
143 }
144
145 use_iterator_impl operator++(int) { // Postincrement
146 auto tmp = *this;
147 ++*this;
148 return tmp;
149 }
150
151 UseT &operator*() const {
152 assert(U && "Cannot dereference end iterator!")((U && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 152, __PRETTY_FUNCTION__))
;
153 return *U;
154 }
155
156 UseT *operator->() const { return &operator*(); }
157
158 operator use_iterator_impl<const UseT>() const {
159 return use_iterator_impl<const UseT>(U);
160 }
161 };
162
163 template <typename UserTy> // UserTy == 'User' or 'const User'
164 class user_iterator_impl
165 : public std::iterator<std::forward_iterator_tag, UserTy *> {
166 use_iterator_impl<Use> UI;
167 explicit user_iterator_impl(Use *U) : UI(U) {}
168 friend class Value;
169
170 public:
171 user_iterator_impl() = default;
172
173 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
174 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
175
176 /// Returns true if this iterator is equal to user_end() on the value.
177 bool atEnd() const { return *this == user_iterator_impl(); }
178
179 user_iterator_impl &operator++() { // Preincrement
180 ++UI;
181 return *this;
182 }
183
184 user_iterator_impl operator++(int) { // Postincrement
185 auto tmp = *this;
186 ++*this;
187 return tmp;
188 }
189
190 // Retrieve a pointer to the current User.
191 UserTy *operator*() const {
192 return UI->getUser();
193 }
194
195 UserTy *operator->() const { return operator*(); }
196
197 operator user_iterator_impl<const UserTy>() const {
198 return user_iterator_impl<const UserTy>(*UI);
199 }
200
201 Use &getUse() const { return *UI; }
202 };
203
204protected:
205 Value(Type *Ty, unsigned scid);
206
207 /// Value's destructor should be virtual by design, but that would require
208 /// that Value and all of its subclasses have a vtable that effectively
209 /// duplicates the information in the value ID. As a size optimization, the
210 /// destructor has been protected, and the caller should manually call
211 /// deleteValue.
212 ~Value(); // Use deleteValue() to delete a generic Value.
213
214public:
215 Value(const Value &) = delete;
216 Value &operator=(const Value &) = delete;
217
218 /// Delete a pointer to a generic Value.
219 void deleteValue();
220
221 /// Support for debugging, callable in GDB: V->dump()
222 void dump() const;
223
224 /// Implement operator<< on Value.
225 /// @{
226 void print(raw_ostream &O, bool IsForDebug = false) const;
227 void print(raw_ostream &O, ModuleSlotTracker &MST,
228 bool IsForDebug = false) const;
229 /// @}
230
231 /// Print the name of this Value out to the specified raw_ostream.
232 ///
233 /// This is useful when you just want to print 'int %reg126', not the
234 /// instruction that generated it. If you specify a Module for context, then
235 /// even constanst get pretty-printed; for example, the type of a null
236 /// pointer is printed symbolically.
237 /// @{
238 void printAsOperand(raw_ostream &O, bool PrintType = true,
239 const Module *M = nullptr) const;
240 void printAsOperand(raw_ostream &O, bool PrintType,
241 ModuleSlotTracker &MST) const;
242 /// @}
243
244 /// All values are typed, get the type of this value.
245 Type *getType() const { return VTy; }
246
247 /// All values hold a context through their type.
248 LLVMContext &getContext() const;
249
250 // All values can potentially be named.
251 bool hasName() const { return HasName; }
252 ValueName *getValueName() const;
253 void setValueName(ValueName *VN);
254
255private:
256 void destroyValueName();
257 enum class ReplaceMetadataUses { No, Yes };
258 void doRAUW(Value *New, ReplaceMetadataUses);
259 void setNameImpl(const Twine &Name);
260
261public:
262 /// Return a constant reference to the value's name.
263 ///
264 /// This guaranteed to return the same reference as long as the value is not
265 /// modified. If the value has a name, this does a hashtable lookup, so it's
266 /// not free.
267 StringRef getName() const;
268
269 /// Change the name of the value.
270 ///
271 /// Choose a new unique name if the provided name is taken.
272 ///
273 /// \param Name The new name; or "" if the value's name should be removed.
274 void setName(const Twine &Name);
275
276 /// Transfer the name from V to this value.
277 ///
278 /// After taking V's name, sets V's name to empty.
279 ///
280 /// \note It is an error to call V->takeName(V).
281 void takeName(Value *V);
282
283 /// Change all uses of this to point to a new Value.
284 ///
285 /// Go through the uses list for this definition and make each use point to
286 /// "V" instead of "this". After this completes, 'this's use list is
287 /// guaranteed to be empty.
288 void replaceAllUsesWith(Value *V);
289
290 /// Change non-metadata uses of this to point to a new Value.
291 ///
292 /// Go through the uses list for this definition and make each use point to
293 /// "V" instead of "this". This function skips metadata entries in the list.
294 void replaceNonMetadataUsesWith(Value *V);
295
296 /// Go through the uses list for this definition and make each use point
297 /// to "V" if the callback ShouldReplace returns true for the given Use.
298 /// Unlike replaceAllUsesWith() this function does not support basic block
299 /// values or constant users.
300 void replaceUsesWithIf(Value *New,
301 llvm::function_ref<bool(Use &U)> ShouldReplace) {
302 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!")((New && "Value::replaceUsesWithIf(<null>) is invalid!"
) ? static_cast<void> (0) : __assert_fail ("New && \"Value::replaceUsesWithIf(<null>) is invalid!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 302, __PRETTY_FUNCTION__))
;
303 assert(New->getType() == getType() &&((New->getType() == getType() && "replaceUses of value with new value of different type!"
) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 304, __PRETTY_FUNCTION__))
304 "replaceUses of value with new value of different type!")((New->getType() == getType() && "replaceUses of value with new value of different type!"
) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 304, __PRETTY_FUNCTION__))
;
305
306 for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
307 Use &U = *UI;
308 ++UI;
309 if (!ShouldReplace(U))
310 continue;
311 U.set(New);
312 }
313 }
314
315 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
316 /// make each use point to "V" instead of "this" when the use is outside the
317 /// block. 'This's use list is expected to have at least one element.
318 /// Unlike replaceAllUsesWith() this function does not support basic block
319 /// values or constant users.
320 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
321
322 //----------------------------------------------------------------------
323 // Methods for handling the chain of uses of this Value.
324 //
325 // Materializing a function can introduce new uses, so these methods come in
326 // two variants:
327 // The methods that start with materialized_ check the uses that are
328 // currently known given which functions are materialized. Be very careful
329 // when using them since you might not get all uses.
330 // The methods that don't start with materialized_ assert that modules is
331 // fully materialized.
332 void assertModuleIsMaterializedImpl() const;
333 // This indirection exists so we can keep assertModuleIsMaterializedImpl()
334 // around in release builds of Value.cpp to be linked with other code built
335 // in debug mode. But this avoids calling it in any of the release built code.
336 void assertModuleIsMaterialized() const {
337#ifndef NDEBUG
338 assertModuleIsMaterializedImpl();
339#endif
340 }
341
342 bool use_empty() const {
343 assertModuleIsMaterialized();
344 return UseList == nullptr;
10
Assuming the condition is false
11
Returning zero, which participates in a condition later
345 }
346
347 bool materialized_use_empty() const {
348 return UseList == nullptr;
349 }
350
351 using use_iterator = use_iterator_impl<Use>;
352 using const_use_iterator = use_iterator_impl<const Use>;
353
354 use_iterator materialized_use_begin() { return use_iterator(UseList); }
355 const_use_iterator materialized_use_begin() const {
356 return const_use_iterator(UseList);
357 }
358 use_iterator use_begin() {
359 assertModuleIsMaterialized();
360 return materialized_use_begin();
361 }
362 const_use_iterator use_begin() const {
363 assertModuleIsMaterialized();
364 return materialized_use_begin();
365 }
366 use_iterator use_end() { return use_iterator(); }
367 const_use_iterator use_end() const { return const_use_iterator(); }
368 iterator_range<use_iterator> materialized_uses() {
369 return make_range(materialized_use_begin(), use_end());
370 }
371 iterator_range<const_use_iterator> materialized_uses() const {
372 return make_range(materialized_use_begin(), use_end());
373 }
374 iterator_range<use_iterator> uses() {
375 assertModuleIsMaterialized();
376 return materialized_uses();
377 }
378 iterator_range<const_use_iterator> uses() const {
379 assertModuleIsMaterialized();
380 return materialized_uses();
381 }
382
383 bool user_empty() const {
384 assertModuleIsMaterialized();
385 return UseList == nullptr;
386 }
387
388 using user_iterator = user_iterator_impl<User>;
389 using const_user_iterator = user_iterator_impl<const User>;
390
391 user_iterator materialized_user_begin() { return user_iterator(UseList); }
392 const_user_iterator materialized_user_begin() const {
393 return const_user_iterator(UseList);
394 }
395 user_iterator user_begin() {
396 assertModuleIsMaterialized();
397 return materialized_user_begin();
398 }
399 const_user_iterator user_begin() const {
400 assertModuleIsMaterialized();
401 return materialized_user_begin();
402 }
403 user_iterator user_end() { return user_iterator(); }
404 const_user_iterator user_end() const { return const_user_iterator(); }
405 User *user_back() {
406 assertModuleIsMaterialized();
407 return *materialized_user_begin();
408 }
409 const User *user_back() const {
410 assertModuleIsMaterialized();
411 return *materialized_user_begin();
412 }
413 iterator_range<user_iterator> materialized_users() {
414 return make_range(materialized_user_begin(), user_end());
415 }
416 iterator_range<const_user_iterator> materialized_users() const {
417 return make_range(materialized_user_begin(), user_end());
418 }
419 iterator_range<user_iterator> users() {
420 assertModuleIsMaterialized();
421 return materialized_users();
422 }
423 iterator_range<const_user_iterator> users() const {
424 assertModuleIsMaterialized();
425 return materialized_users();
426 }
427
428 /// Return true if there is exactly one user of this value.
429 ///
430 /// This is specialized because it is a common request and does not require
431 /// traversing the whole use list.
432 bool hasOneUse() const {
433 const_use_iterator I = use_begin(), E = use_end();
434 if (I == E) return false;
435 return ++I == E;
436 }
437
438 /// Return true if this Value has exactly N users.
439 bool hasNUses(unsigned N) const;
440
441 /// Return true if this value has N users or more.
442 ///
443 /// This is logically equivalent to getNumUses() >= N.
444 bool hasNUsesOrMore(unsigned N) const;
445
446 /// Check if this value is used in the specified basic block.
447 bool isUsedInBasicBlock(const BasicBlock *BB) const;
448
449 /// This method computes the number of uses of this Value.
450 ///
451 /// This is a linear time operation. Use hasOneUse, hasNUses, or
452 /// hasNUsesOrMore to check for specific values.
453 unsigned getNumUses() const;
454
455 /// This method should only be used by the Use class.
456 void addUse(Use &U) { U.addToList(&UseList); }
457
458 /// Concrete subclass of this.
459 ///
460 /// An enumeration for keeping track of the concrete subclass of Value that
461 /// is actually instantiated. Values of this enumeration are kept in the
462 /// Value classes SubclassID field. They are used for concrete type
463 /// identification.
464 enum ValueTy {
465#define HANDLE_VALUE(Name) Name##Val,
466#include "llvm/IR/Value.def"
467
468 // Markers:
469#define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
470#include "llvm/IR/Value.def"
471 };
472
473 /// Return an ID for the concrete type of this object.
474 ///
475 /// This is used to implement the classof checks. This should not be used
476 /// for any other purpose, as the values may change as LLVM evolves. Also,
477 /// note that for instructions, the Instruction's opcode is added to
478 /// InstructionVal. So this means three things:
479 /// # there is no value with code InstructionVal (no opcode==0).
480 /// # there are more possible values for the value type than in ValueTy enum.
481 /// # the InstructionVal enumerator must be the highest valued enumerator in
482 /// the ValueTy enum.
483 unsigned getValueID() const {
484 return SubclassID;
485 }
486
487 /// Return the raw optional flags value contained in this value.
488 ///
489 /// This should only be used when testing two Values for equivalence.
490 unsigned getRawSubclassOptionalData() const {
491 return SubclassOptionalData;
492 }
493
494 /// Clear the optional flags contained in this value.
495 void clearSubclassOptionalData() {
496 SubclassOptionalData = 0;
497 }
498
499 /// Check the optional flags for equality.
500 bool hasSameSubclassOptionalData(const Value *V) const {
501 return SubclassOptionalData == V->SubclassOptionalData;
502 }
503
504 /// Return true if there is a value handle associated with this value.
505 bool hasValueHandle() const { return HasValueHandle; }
506
507 /// Return true if there is metadata referencing this value.
508 bool isUsedByMetadata() const { return IsUsedByMD; }
509
510 /// Return true if this value is a swifterror value.
511 ///
512 /// swifterror values can be either a function argument or an alloca with a
513 /// swifterror attribute.
514 bool isSwiftError() const;
515
516 /// Strip off pointer casts, all-zero GEPs and address space casts.
517 ///
518 /// Returns the original uncasted value. If this is called on a non-pointer
519 /// value, it returns 'this'.
520 const Value *stripPointerCasts() const;
521 Value *stripPointerCasts() {
522 return const_cast<Value *>(
523 static_cast<const Value *>(this)->stripPointerCasts());
524 }
525
526 /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
527 ///
528 /// Returns the original uncasted value. If this is called on a non-pointer
529 /// value, it returns 'this'.
530 const Value *stripPointerCastsAndAliases() const;
531 Value *stripPointerCastsAndAliases() {
532 return const_cast<Value *>(
533 static_cast<const Value *>(this)->stripPointerCastsAndAliases());
534 }
535
536 /// Strip off pointer casts, all-zero GEPs and address space casts
537 /// but ensures the representation of the result stays the same.
538 ///
539 /// Returns the original uncasted value with the same representation. If this
540 /// is called on a non-pointer value, it returns 'this'.
541 const Value *stripPointerCastsSameRepresentation() const;
542 Value *stripPointerCastsSameRepresentation() {
543 return const_cast<Value *>(static_cast<const Value *>(this)
544 ->stripPointerCastsSameRepresentation());
545 }
546
547 /// Strip off pointer casts, all-zero GEPs and invariant group info.
548 ///
549 /// Returns the original uncasted value. If this is called on a non-pointer
550 /// value, it returns 'this'. This function should be used only in
551 /// Alias analysis.
552 const Value *stripPointerCastsAndInvariantGroups() const;
553 Value *stripPointerCastsAndInvariantGroups() {
554 return const_cast<Value *>(static_cast<const Value *>(this)
555 ->stripPointerCastsAndInvariantGroups());
556 }
557
558 /// Strip off pointer casts and all-constant inbounds GEPs.
559 ///
560 /// Returns the original pointer value. If this is called on a non-pointer
561 /// value, it returns 'this'.
562 const Value *stripInBoundsConstantOffsets() const;
563 Value *stripInBoundsConstantOffsets() {
564 return const_cast<Value *>(
565 static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
566 }
567
568 /// Accumulate the constant offset this value has compared to a base pointer.
569 /// Only 'getelementptr' instructions (GEPs) with constant indices are
570 /// accumulated but other instructions, e.g., casts, are stripped away as
571 /// well. The accumulated constant offset is added to \p Offset and the base
572 /// pointer is returned.
573 ///
574 /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
575 /// the address space of 'this' pointer value, e.g., use
576 /// DataLayout::getIndexTypeSizeInBits(Ty).
577 ///
578 /// If \p AllowNonInbounds is true, constant offsets in GEPs are stripped and
579 /// accumulated even if the GEP is not "inbounds".
580 ///
581 /// If this is called on a non-pointer value, it returns 'this' and the
582 /// \p Offset is not modified.
583 ///
584 /// Note that this function will never return a nullptr. It will also never
585 /// manipulate the \p Offset in a way that would not match the difference
586 /// between the underlying value and the returned one. Thus, if no constant
587 /// offset was found, the returned value is the underlying one and \p Offset
588 /// is unchanged.
589 const Value *stripAndAccumulateConstantOffsets(const DataLayout &DL,
590 APInt &Offset,
591 bool AllowNonInbounds) const;
592 Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
593 bool AllowNonInbounds) {
594 return const_cast<Value *>(
595 static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
596 DL, Offset, AllowNonInbounds));
597 }
598
599 /// This is a wrapper around stripAndAccumulateConstantOffsets with the
600 /// in-bounds requirement set to false.
601 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
602 APInt &Offset) const {
603 return stripAndAccumulateConstantOffsets(DL, Offset,
604 /* AllowNonInbounds */ false);
605 }
606 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
607 APInt &Offset) {
608 return stripAndAccumulateConstantOffsets(DL, Offset,
609 /* AllowNonInbounds */ false);
610 }
611
612 /// Strip off pointer casts and inbounds GEPs.
613 ///
614 /// Returns the original pointer value. If this is called on a non-pointer
615 /// value, it returns 'this'.
616 const Value *stripInBoundsOffsets() const;
617 Value *stripInBoundsOffsets() {
618 return const_cast<Value *>(
619 static_cast<const Value *>(this)->stripInBoundsOffsets());
620 }
621
622 /// Returns the number of bytes known to be dereferenceable for the
623 /// pointer value.
624 ///
625 /// If CanBeNull is set by this function the pointer can either be null or be
626 /// dereferenceable up to the returned number of bytes.
627 uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
628 bool &CanBeNull) const;
629
630 /// Returns an alignment of the pointer value.
631 ///
632 /// Returns an alignment which is either specified explicitly, e.g. via
633 /// align attribute of a function argument, or guaranteed by DataLayout.
634 unsigned getPointerAlignment(const DataLayout &DL) const;
635
636 /// Translate PHI node to its predecessor from the given basic block.
637 ///
638 /// If this value is a PHI node with CurBB as its parent, return the value in
639 /// the PHI node corresponding to PredBB. If not, return ourself. This is
640 /// useful if you want to know the value something has in a predecessor
641 /// block.
642 const Value *DoPHITranslation(const BasicBlock *CurBB,
643 const BasicBlock *PredBB) const;
644 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
645 return const_cast<Value *>(
646 static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
647 }
648
649 /// The maximum alignment for instructions.
650 ///
651 /// This is the greatest alignment value supported by load, store, and alloca
652 /// instructions, and global values.
653 static const unsigned MaxAlignmentExponent = 29;
654 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
655
656 /// Mutate the type of this Value to be of the specified type.
657 ///
658 /// Note that this is an extremely dangerous operation which can create
659 /// completely invalid IR very easily. It is strongly recommended that you
660 /// recreate IR objects with the right types instead of mutating them in
661 /// place.
662 void mutateType(Type *Ty) {
663 VTy = Ty;
664 }
665
666 /// Sort the use-list.
667 ///
668 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
669 /// expected to compare two \a Use references.
670 template <class Compare> void sortUseList(Compare Cmp);
671
672 /// Reverse the use-list.
673 void reverseUseList();
674
675private:
676 /// Merge two lists together.
677 ///
678 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
679 /// "equal" items from L before items from R.
680 ///
681 /// \return the first element in the list.
682 ///
683 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
684 template <class Compare>
685 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
686 Use *Merged;
687 Use **Next = &Merged;
688
689 while (true) {
690 if (!L) {
691 *Next = R;
692 break;
693 }
694 if (!R) {
695 *Next = L;
696 break;
697 }
698 if (Cmp(*R, *L)) {
699 *Next = R;
700 Next = &R->Next;
701 R = R->Next;
702 } else {
703 *Next = L;
704 Next = &L->Next;
705 L = L->Next;
706 }
707 }
708
709 return Merged;
710 }
711
712protected:
713 unsigned short getSubclassDataFromValue() const { return SubclassData; }
714 void setValueSubclassData(unsigned short D) { SubclassData = D; }
715};
716
717struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
718
719/// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
720/// Those don't work because Value and Instruction's destructors are protected,
721/// aren't virtual, and won't destroy the complete object.
722using unique_value = std::unique_ptr<Value, ValueDeleter>;
723
724inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
725 V.print(OS);
726 return OS;
727}
728
729void Use::set(Value *V) {
730 if (Val) removeFromList();
731 Val = V;
732 if (V) V->addUse(*this);
733}
734
735Value *Use::operator=(Value *RHS) {
736 set(RHS);
737 return RHS;
738}
739
740const Use &Use::operator=(const Use &RHS) {
741 set(RHS.Val);
742 return *this;
743}
744
745template <class Compare> void Value::sortUseList(Compare Cmp) {
746 if (!UseList || !UseList->Next)
747 // No need to sort 0 or 1 uses.
748 return;
749
750 // Note: this function completely ignores Prev pointers until the end when
751 // they're fixed en masse.
752
753 // Create a binomial vector of sorted lists, visiting uses one at a time and
754 // merging lists as necessary.
755 const unsigned MaxSlots = 32;
756 Use *Slots[MaxSlots];
757
758 // Collect the first use, turning it into a single-item list.
759 Use *Next = UseList->Next;
760 UseList->Next = nullptr;
761 unsigned NumSlots = 1;
762 Slots[0] = UseList;
763
764 // Collect all but the last use.
765 while (Next->Next) {
766 Use *Current = Next;
767 Next = Current->Next;
768
769 // Turn Current into a single-item list.
770 Current->Next = nullptr;
771
772 // Save Current in the first available slot, merging on collisions.
773 unsigned I;
774 for (I = 0; I < NumSlots; ++I) {
775 if (!Slots[I])
776 break;
777
778 // Merge two lists, doubling the size of Current and emptying slot I.
779 //
780 // Since the uses in Slots[I] originally preceded those in Current, send
781 // Slots[I] in as the left parameter to maintain a stable sort.
782 Current = mergeUseLists(Slots[I], Current, Cmp);
783 Slots[I] = nullptr;
784 }
785 // Check if this is a new slot.
786 if (I == NumSlots) {
787 ++NumSlots;
788 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32")((NumSlots <= MaxSlots && "Use list bigger than 2^32"
) ? static_cast<void> (0) : __assert_fail ("NumSlots <= MaxSlots && \"Use list bigger than 2^32\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 788, __PRETTY_FUNCTION__))
;
789 }
790
791 // Found an open slot.
792 Slots[I] = Current;
793 }
794
795 // Merge all the lists together.
796 assert(Next && "Expected one more Use")((Next && "Expected one more Use") ? static_cast<void
> (0) : __assert_fail ("Next && \"Expected one more Use\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 796, __PRETTY_FUNCTION__))
;
797 assert(!Next->Next && "Expected only one Use")((!Next->Next && "Expected only one Use") ? static_cast
<void> (0) : __assert_fail ("!Next->Next && \"Expected only one Use\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Value.h"
, 797, __PRETTY_FUNCTION__))
;
798 UseList = Next;
799 for (unsigned I = 0; I < NumSlots; ++I)
800 if (Slots[I])
801 // Since the uses in Slots[I] originally preceded those in UseList, send
802 // Slots[I] in as the left parameter to maintain a stable sort.
803 UseList = mergeUseLists(Slots[I], UseList, Cmp);
804
805 // Fix the Prev pointers.
806 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
807 I->setPrev(Prev);
808 Prev = &I->Next;
809 }
810}
811
812// isa - Provide some specializations of isa so that we don't have to include
813// the subtype header files to test to see if the value is a subclass...
814//
815template <> struct isa_impl<Constant, Value> {
816 static inline bool doit(const Value &Val) {
817 static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
818 return Val.getValueID() <= Value::ConstantLastVal;
819 }
820};
821
822template <> struct isa_impl<ConstantData, Value> {
823 static inline bool doit(const Value &Val) {
824 return Val.getValueID() >= Value::ConstantDataFirstVal &&
825 Val.getValueID() <= Value::ConstantDataLastVal;
826 }
827};
828
829template <> struct isa_impl<ConstantAggregate, Value> {
830 static inline bool doit(const Value &Val) {
831 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
832 Val.getValueID() <= Value::ConstantAggregateLastVal;
833 }
834};
835
836template <> struct isa_impl<Argument, Value> {
837 static inline bool doit (const Value &Val) {
838 return Val.getValueID() == Value::ArgumentVal;
839 }
840};
841
842template <> struct isa_impl<InlineAsm, Value> {
843 static inline bool doit(const Value &Val) {
844 return Val.getValueID() == Value::InlineAsmVal;
845 }
846};
847
848template <> struct isa_impl<Instruction, Value> {
849 static inline bool doit(const Value &Val) {
850 return Val.getValueID() >= Value::InstructionVal;
851 }
852};
853
854template <> struct isa_impl<BasicBlock, Value> {
855 static inline bool doit(const Value &Val) {
856 return Val.getValueID() == Value::BasicBlockVal;
857 }
858};
859
860template <> struct isa_impl<Function, Value> {
861 static inline bool doit(const Value &Val) {
862 return Val.getValueID() == Value::FunctionVal;
863 }
864};
865
866template <> struct isa_impl<GlobalVariable, Value> {
867 static inline bool doit(const Value &Val) {
868 return Val.getValueID() == Value::GlobalVariableVal;
869 }
870};
871
872template <> struct isa_impl<GlobalAlias, Value> {
873 static inline bool doit(const Value &Val) {
874 return Val.getValueID() == Value::GlobalAliasVal;
875 }
876};
877
878template <> struct isa_impl<GlobalIFunc, Value> {
879 static inline bool doit(const Value &Val) {
880 return Val.getValueID() == Value::GlobalIFuncVal;
881 }
882};
883
884template <> struct isa_impl<GlobalIndirectSymbol, Value> {
885 static inline bool doit(const Value &Val) {
886 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
887 }
888};
889
890template <> struct isa_impl<GlobalValue, Value> {
891 static inline bool doit(const Value &Val) {
892 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
893 }
894};
895
896template <> struct isa_impl<GlobalObject, Value> {
897 static inline bool doit(const Value &Val) {
898 return isa<GlobalVariable>(Val) || isa<Function>(Val);
899 }
900};
901
902// Create wrappers for C Binding types (see CBindingWrapping.h).
903DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)inline Value *unwrap(LLVMValueRef P) { return reinterpret_cast
<Value*>(P); } inline LLVMValueRef wrap(const Value *P)
{ return reinterpret_cast<LLVMValueRef>(const_cast<
Value*>(P)); } template<typename T> inline T *unwrap
(LLVMValueRef P) { return cast<T>(unwrap(P)); }
904
905// Specialized opaque value conversions.
906inline Value **unwrap(LLVMValueRef *Vals) {
907 return reinterpret_cast<Value**>(Vals);
908}
909
910template<typename T>
911inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
912#ifndef NDEBUG
913 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
914 unwrap<T>(*I); // For side effect of calling assert on invalid usage.
915#endif
916 (void)Length;
917 return reinterpret_cast<T**>(Vals);
918}
919
920inline LLVMValueRef *wrap(const Value **Vals) {
921 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
922}
923
924} // end namespace llvm
925
926#endif // LLVM_IR_VALUE_H