blob: 5bdce2b542503fd697c925b69fbcbb8896b8c054 [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===-- Value.cpp - Implement the Value class -----------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattner722272d2009-03-31 22:11:05 +000010// This file implements the Value, ValueHandle, and User classes.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000014#include "llvm/IR/Value.h"
Owen Anderson4d919432009-08-18 18:28:58 +000015#include "LLVMContextImpl.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/SmallString.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/Constant.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
25#include "llvm/IR/ValueSymbolTable.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000026#include "llvm/Support/Debug.h"
Torok Edwinab7c09b2009-07-08 18:01:40 +000027#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000029#include "llvm/Support/LeakDetector.h"
Chris Lattner722272d2009-03-31 22:11:05 +000030#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/ValueHandle.h"
Chris Lattner00950542001-06-06 20:29:01 +000032#include <algorithm>
Chris Lattner31f84992003-11-21 20:23:48 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner00950542001-06-06 20:29:01 +000035//===----------------------------------------------------------------------===//
36// Value Class
37//===----------------------------------------------------------------------===//
38
Chris Lattnerdb125cf2011-07-18 04:54:35 +000039static inline Type *checkType(Type *Ty) {
Chris Lattner82d18aa2001-12-13 00:41:27 +000040 assert(Ty && "Value defined with a null type: Error!");
Chris Lattner1afcace2011-07-09 17:41:24 +000041 return const_cast<Type*>(Ty);
Chris Lattner82d18aa2001-12-13 00:41:27 +000042}
43
Chris Lattnerdb125cf2011-07-18 04:54:35 +000044Value::Value(Type *ty, unsigned scid)
Chris Lattner3990b122009-12-28 23:41:32 +000045 : SubclassID(scid), HasValueHandle(0),
Chris Lattner1afcace2011-07-09 17:41:24 +000046 SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
Gabor Greif6f426652008-09-19 15:13:20 +000047 UseList(0), Name(0) {
Chris Lattner1afcace2011-07-09 17:41:24 +000048 // FIXME: Why isn't this in the subclass gunk??
Richard Smith488fdce2012-12-20 04:11:02 +000049 // Note, we cannot call isa<CallInst> before the CallInst has been
50 // constructed.
51 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
Chris Lattner1afcace2011-07-09 17:41:24 +000052 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
53 "invalid CallInst type!");
Richard Smith488fdce2012-12-20 04:11:02 +000054 else if (SubclassID != BasicBlockVal &&
55 (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
Chris Lattner1afcace2011-07-09 17:41:24 +000056 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
Chris Lattnera9e77812004-07-06 17:44:17 +000057 "Cannot create non-first-class values except for constants!");
Chris Lattner00950542001-06-06 20:29:01 +000058}
59
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000060Value::~Value() {
Chris Lattner722272d2009-03-31 22:11:05 +000061 // Notify all ValueHandles (if present) that this value is going away.
62 if (HasValueHandle)
63 ValueHandleBase::ValueIsDeleted(this);
Daniel Dunbarce99a6e2009-09-20 04:03:34 +000064
Chris Lattner00950542001-06-06 20:29:01 +000065#ifndef NDEBUG // Only in -g mode...
Chris Lattneree976f32001-06-11 15:04:40 +000066 // Check to make sure that there are no uses of this value that are still
67 // around when the value is destroyed. If there are, then we have a dangling
68 // reference and something is wrong. This code is here to print out what is
Misha Brukmanfd939082005-04-21 23:48:37 +000069 // still being referenced. The value in question should be printed as
Chris Lattneree976f32001-06-11 15:04:40 +000070 // a <badref>
71 //
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000072 if (!use_empty()) {
Benjamin Kramera7b0cb72011-11-15 16:27:03 +000073 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000074 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
David Greene6892c7a2010-01-05 01:30:09 +000075 dbgs() << "Use still stuck around after Def is destroyed:"
Bill Wendling2e3def12006-11-17 08:03:48 +000076 << **I << "\n";
Chris Lattner00950542001-06-06 20:29:01 +000077 }
78#endif
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000079 assert(use_empty() && "Uses remain when a value is destroyed!");
Chris Lattner4f95d2b2009-08-04 23:07:12 +000080
81 // If this value is named, destroy the name. This should not be in a symtab
82 // at this point.
Bill Wendling3ecb4472012-04-10 20:12:16 +000083 if (Name && SubclassID != MDStringVal)
Chris Lattner4f95d2b2009-08-04 23:07:12 +000084 Name->Destroy();
Daniel Dunbarce99a6e2009-09-20 04:03:34 +000085
Chris Lattner4f95d2b2009-08-04 23:07:12 +000086 // There should be no uses of this object anymore, remove it.
87 LeakDetector::removeGarbageObject(this);
Chris Lattner00950542001-06-06 20:29:01 +000088}
89
Chris Lattner29d1ca62005-02-01 01:24:21 +000090/// hasNUses - Return true if this Value has exactly N users.
91///
92bool Value::hasNUses(unsigned N) const {
Gabor Greif60ad7812010-03-25 23:06:16 +000093 const_use_iterator UI = use_begin(), E = use_end();
Chris Lattner29d1ca62005-02-01 01:24:21 +000094
95 for (; N; --N, ++UI)
96 if (UI == E) return false; // Too few.
97 return UI == E;
98}
99
Chris Lattner8daf0562005-02-23 16:51:11 +0000100/// hasNUsesOrMore - Return true if this value has N users or more. This is
101/// logically equivalent to getNumUses() >= N.
102///
103bool Value::hasNUsesOrMore(unsigned N) const {
Gabor Greif60ad7812010-03-25 23:06:16 +0000104 const_use_iterator UI = use_begin(), E = use_end();
Chris Lattner8daf0562005-02-23 16:51:11 +0000105
106 for (; N; --N, ++UI)
107 if (UI == E) return false; // Too few.
108
109 return true;
110}
111
Evan Cheng502a4f52008-06-12 21:15:59 +0000112/// isUsedInBasicBlock - Return true if this value is used in the specified
113/// basic block.
Bill Wendlingc4f72dd2008-09-25 22:42:01 +0000114bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
Benjamin Kramer4da7f902011-12-05 17:23:27 +0000115 // Start by scanning over the instructions looking for a use before we start
116 // the expensive use iteration.
117 unsigned MaxBlockSize = 3;
118 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
119 if (std::find(I->op_begin(), I->op_end(), this) != I->op_end())
120 return true;
121 if (MaxBlockSize-- == 0) // If the block is larger fall back to use_iterator
122 break;
123 }
124
125 if (MaxBlockSize != 0) // We scanned the entire block and found no use.
126 return false;
127
Gabor Greif60ad7812010-03-25 23:06:16 +0000128 for (const_use_iterator I = use_begin(), E = use_end(); I != E; ++I) {
Evan Cheng502a4f52008-06-12 21:15:59 +0000129 const Instruction *User = dyn_cast<Instruction>(*I);
130 if (User && User->getParent() == BB)
131 return true;
132 }
133 return false;
134}
135
Chris Lattner8daf0562005-02-23 16:51:11 +0000136
Chris Lattner29d1ca62005-02-01 01:24:21 +0000137/// getNumUses - This method computes the number of uses of this Value. This
138/// is a linear time operation. Use hasOneUse or hasNUses to check for specific
139/// values.
140unsigned Value::getNumUses() const {
141 return (unsigned)std::distance(use_begin(), use_end());
142}
143
Chris Lattner72168112007-02-11 00:37:27 +0000144static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
Chris Lattnerea7acb82007-02-11 19:12:18 +0000145 ST = 0;
Chris Lattner72168112007-02-11 00:37:27 +0000146 if (Instruction *I = dyn_cast<Instruction>(V)) {
147 if (BasicBlock *P = I->getParent())
148 if (Function *PP = P->getParent())
149 ST = &PP->getValueSymbolTable();
150 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000151 if (Function *P = BB->getParent())
Chris Lattner72168112007-02-11 00:37:27 +0000152 ST = &P->getValueSymbolTable();
153 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000154 if (Module *P = GV->getParent())
Chris Lattner72168112007-02-11 00:37:27 +0000155 ST = &P->getValueSymbolTable();
156 } else if (Argument *A = dyn_cast<Argument>(V)) {
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000157 if (Function *P = A->getParent())
Chris Lattner72168112007-02-11 00:37:27 +0000158 ST = &P->getValueSymbolTable();
Devang Patele54abc92009-07-22 17:43:22 +0000159 } else if (isa<MDString>(V))
160 return true;
161 else {
Chris Lattner72168112007-02-11 00:37:27 +0000162 assert(isa<Constant>(V) && "Unknown value type!");
163 return true; // no name is setable for this.
164 }
165 return false;
166}
Chris Lattner28eca8b2002-10-09 23:12:59 +0000167
Daniel Dunbar499027f2009-07-26 00:51:56 +0000168StringRef Value::getName() const {
Daniel Dunbar4fa49902009-07-26 09:22:02 +0000169 // Make sure the empty string is still a C string. For historical reasons,
170 // some clients want to call .data() on the result and expect it to be null
171 // terminated.
172 if (!Name) return StringRef("", 0);
Daniel Dunbar499027f2009-07-26 00:51:56 +0000173 return Name->getKey();
Chris Lattner71996e72007-08-10 15:34:35 +0000174}
175
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000176void Value::setName(const Twine &NewName) {
Bill Wendling3ecb4472012-04-10 20:12:16 +0000177 assert(SubclassID != MDStringVal &&
178 "Cannot set the name of MDString with this method!");
179
Daniel Dunbar51499322009-08-19 23:37:23 +0000180 // Fast path for common IRBuilder case of setName("") when there is no name.
181 if (NewName.isTriviallyEmpty() && !hasName())
182 return;
183
Daniel Dunbare4760042009-08-19 05:08:06 +0000184 SmallString<256> NameData;
Benjamin Kramerb357e062010-01-13 12:45:23 +0000185 StringRef NameRef = NewName.toStringRef(NameData);
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000186
Daniel Dunbar07f69032009-07-26 00:42:33 +0000187 // Name isn't changing?
Benjamin Kramerb357e062010-01-13 12:45:23 +0000188 if (getName() == NameRef)
Daniel Dunbar07f69032009-07-26 00:42:33 +0000189 return;
190
Benjamin Kramerf0127052010-01-05 13:12:22 +0000191 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000192
Chris Lattner04cb8002005-03-06 02:14:28 +0000193 // Get the symbol table to update for this object.
Chris Lattner72168112007-02-11 00:37:27 +0000194 ValueSymbolTable *ST;
195 if (getSymTab(this, ST))
196 return; // Cannot set a name on this value (e.g. constant).
Chris Lattner0d1e4072005-03-05 19:51:50 +0000197
Chris Lattnerdec628e2007-02-12 05:18:08 +0000198 if (!ST) { // No symbol table to update? Just do the change.
Benjamin Kramerb357e062010-01-13 12:45:23 +0000199 if (NameRef.empty()) {
Chris Lattnerdec628e2007-02-12 05:18:08 +0000200 // Free the name for this value.
201 Name->Destroy();
202 Name = 0;
Chris Lattner042ad362007-02-12 18:52:59 +0000203 return;
Chris Lattner04cb8002005-03-06 02:14:28 +0000204 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000205
Daniel Dunbar07f69032009-07-26 00:42:33 +0000206 if (Name)
Chris Lattner042ad362007-02-12 18:52:59 +0000207 Name->Destroy();
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000208
Chris Lattner042ad362007-02-12 18:52:59 +0000209 // NOTE: Could optimize for the case the name is shrinking to not deallocate
210 // then reallocated.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000211
Chris Lattner042ad362007-02-12 18:52:59 +0000212 // Create the new name.
Benjamin Kramerb357e062010-01-13 12:45:23 +0000213 Name = ValueName::Create(NameRef.begin(), NameRef.end());
Chris Lattner042ad362007-02-12 18:52:59 +0000214 Name->setValue(this);
Chris Lattnerdec628e2007-02-12 05:18:08 +0000215 return;
Chris Lattner04cb8002005-03-06 02:14:28 +0000216 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000217
Chris Lattnerdec628e2007-02-12 05:18:08 +0000218 // NOTE: Could optimize for the case the name is shrinking to not deallocate
219 // then reallocated.
220 if (hasName()) {
Chris Lattnerdec628e2007-02-12 05:18:08 +0000221 // Remove old name.
222 ST->removeValueName(Name);
223 Name->Destroy();
224 Name = 0;
225
Benjamin Kramerb357e062010-01-13 12:45:23 +0000226 if (NameRef.empty())
Chris Lattner042ad362007-02-12 18:52:59 +0000227 return;
Chris Lattnerdec628e2007-02-12 05:18:08 +0000228 }
229
230 // Name is changing to something new.
Benjamin Kramerb357e062010-01-13 12:45:23 +0000231 Name = ST->createValueName(NameRef, this);
Chris Lattner0d1e4072005-03-05 19:51:50 +0000232}
233
Chris Lattner042ad362007-02-12 18:52:59 +0000234
Chris Lattner72168112007-02-11 00:37:27 +0000235/// takeName - transfer the name from V to this value, setting V's name to
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000236/// empty. It is an error to call V->takeName(V).
Chris Lattner72168112007-02-11 00:37:27 +0000237void Value::takeName(Value *V) {
Bill Wendling3ecb4472012-04-10 20:12:16 +0000238 assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
239
Chris Lattner0878c312007-02-15 20:01:43 +0000240 ValueSymbolTable *ST = 0;
241 // If this value has a name, drop it.
242 if (hasName()) {
243 // Get the symtab this is in.
244 if (getSymTab(this, ST)) {
245 // We can't set a name on this value, but we need to clear V's name if
246 // it has one.
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000247 if (V->hasName()) V->setName("");
Chris Lattner0878c312007-02-15 20:01:43 +0000248 return; // Cannot set a name on this value (e.g. constant).
249 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000250
Chris Lattner0878c312007-02-15 20:01:43 +0000251 // Remove old name.
252 if (ST)
253 ST->removeValueName(Name);
254 Name->Destroy();
255 Name = 0;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000256 }
257
Chris Lattner0878c312007-02-15 20:01:43 +0000258 // Now we know that this has no name.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000259
Chris Lattner0878c312007-02-15 20:01:43 +0000260 // If V has no name either, we're done.
261 if (!V->hasName()) return;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000262
Chris Lattner0878c312007-02-15 20:01:43 +0000263 // Get this's symtab if we didn't before.
264 if (!ST) {
265 if (getSymTab(this, ST)) {
266 // Clear V's name.
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000267 V->setName("");
Chris Lattner0878c312007-02-15 20:01:43 +0000268 return; // Cannot set a name on this value (e.g. constant).
269 }
270 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000271
Chris Lattner0878c312007-02-15 20:01:43 +0000272 // Get V's ST, this should always succed, because V has a name.
273 ValueSymbolTable *VST;
274 bool Failure = getSymTab(V, VST);
Jeffrey Yasskin8e68c382010-12-23 00:58:24 +0000275 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000276
Chris Lattner0878c312007-02-15 20:01:43 +0000277 // If these values are both in the same symtab, we can do this very fast.
278 // This works even if both values have no symtab yet.
279 if (ST == VST) {
280 // Take the name!
281 Name = V->Name;
282 V->Name = 0;
283 Name->setValue(this);
Chris Lattnerf41916e2007-02-11 01:04:09 +0000284 return;
285 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000286
Chris Lattner0878c312007-02-15 20:01:43 +0000287 // Otherwise, things are slightly more complex. Remove V's name from VST and
288 // then reinsert it into ST.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000289
Chris Lattner0878c312007-02-15 20:01:43 +0000290 if (VST)
291 VST->removeValueName(V->Name);
292 Name = V->Name;
293 V->Name = 0;
294 Name->setValue(this);
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000295
Chris Lattner0878c312007-02-15 20:01:43 +0000296 if (ST)
297 ST->reinsertValue(this);
Chris Lattner72168112007-02-11 00:37:27 +0000298}
299
300
Chris Lattner678f9e02011-07-15 06:18:52 +0000301void Value::replaceAllUsesWith(Value *New) {
302 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
303 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
304 assert(New->getType() == getType() &&
305 "replaceAllUses of value with new value of different type!");
306
Chris Lattner722272d2009-03-31 22:11:05 +0000307 // Notify all ValueHandles (if present) that this value is going away.
308 if (HasValueHandle)
309 ValueHandleBase::ValueIsRAUWd(this, New);
Chris Lattner678f9e02011-07-15 06:18:52 +0000310
Chris Lattner29d1ca62005-02-01 01:24:21 +0000311 while (!use_empty()) {
Gabor Greif6f426652008-09-19 15:13:20 +0000312 Use &U = *UseList;
Chris Lattner2bc065b2003-08-29 05:09:37 +0000313 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
Chris Lattner2d691332007-08-21 00:21:07 +0000314 // constant because they are uniqued.
Chris Lattnerc3cc71a2003-10-16 16:53:07 +0000315 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
Chris Lattner2d691332007-08-21 00:21:07 +0000316 if (!isa<GlobalValue>(C)) {
Chris Lattnerd0ff1ad2005-10-04 18:13:04 +0000317 C->replaceUsesOfWithOnConstant(this, New, &U);
Chris Lattner2d691332007-08-21 00:21:07 +0000318 continue;
319 }
Chris Lattner2bc065b2003-08-29 05:09:37 +0000320 }
Chris Lattner678f9e02011-07-15 06:18:52 +0000321
Chris Lattner2d691332007-08-21 00:21:07 +0000322 U.set(New);
Chris Lattner2bc065b2003-08-29 05:09:37 +0000323 }
Chris Lattner678f9e02011-07-15 06:18:52 +0000324
Jay Foad95c3e482011-06-23 09:09:15 +0000325 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
326 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
Chris Lattner2bc065b2003-08-29 05:09:37 +0000327}
328
Chandler Carruth84dfc322012-03-10 08:39:09 +0000329namespace {
330// Various metrics for how much to strip off of pointers.
331enum PointerStripKind {
332 PSK_ZeroIndices,
Chandler Carruth274d3772012-03-14 23:19:53 +0000333 PSK_InBoundsConstantIndices,
334 PSK_InBounds
Chandler Carruth84dfc322012-03-10 08:39:09 +0000335};
336
337template <PointerStripKind StripKind>
338static Value *stripPointerCastsAndOffsets(Value *V) {
339 if (!V->getType()->isPointerTy())
340 return V;
Dan Gohman50f424c2010-06-28 21:16:52 +0000341
342 // Even though we don't look through PHI nodes, we could be called on an
343 // instruction in an unreachable block, which may be on a cycle.
344 SmallPtrSet<Value *, 4> Visited;
345
Dan Gohman50f424c2010-06-28 21:16:52 +0000346 Visited.insert(V);
Duncan Sandsf08bf112008-12-29 21:06:19 +0000347 do {
Dan Gohman016de812009-07-17 23:55:56 +0000348 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +0000349 switch (StripKind) {
350 case PSK_ZeroIndices:
351 if (!GEP->hasAllZeroIndices())
352 return V;
353 break;
Chandler Carruth274d3772012-03-14 23:19:53 +0000354 case PSK_InBoundsConstantIndices:
Chandler Carruth84dfc322012-03-10 08:39:09 +0000355 if (!GEP->hasAllConstantIndices())
356 return V;
Chandler Carruth274d3772012-03-14 23:19:53 +0000357 // fallthrough
Chandler Carruth84dfc322012-03-10 08:39:09 +0000358 case PSK_InBounds:
359 if (!GEP->isInBounds())
360 return V;
361 break;
Chandler Carruth84dfc322012-03-10 08:39:09 +0000362 }
Dan Gohman016de812009-07-17 23:55:56 +0000363 V = GEP->getPointerOperand();
364 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
365 V = cast<Operator>(V)->getOperand(0);
Dan Gohmanaac1bfb2009-08-27 17:55:13 +0000366 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
367 if (GA->mayBeOverridden())
368 return V;
369 V = GA->getAliasee();
Duncan Sandsf08bf112008-12-29 21:06:19 +0000370 } else {
371 return V;
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000372 }
Duncan Sands1df98592010-02-16 11:11:14 +0000373 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
Dan Gohman50f424c2010-06-28 21:16:52 +0000374 } while (Visited.insert(V));
375
376 return V;
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000377}
Chandler Carruth84dfc322012-03-10 08:39:09 +0000378} // namespace
379
380Value *Value::stripPointerCasts() {
381 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
382}
383
Chandler Carruth274d3772012-03-14 23:19:53 +0000384Value *Value::stripInBoundsConstantOffsets() {
385 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
Chandler Carruth84dfc322012-03-10 08:39:09 +0000386}
387
388Value *Value::stripInBoundsOffsets() {
389 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
390}
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000391
Dan Gohman4d70a292010-11-11 21:23:25 +0000392/// isDereferenceablePointer - Test if this value is always a pointer to
Nick Lewycky67b64642010-11-11 21:51:44 +0000393/// allocated and suitably aligned memory for a simple load or store.
Nick Lewycky37abc482012-01-23 00:05:17 +0000394static bool isDereferenceablePointer(const Value *V,
395 SmallPtrSet<const Value *, 32> &Visited) {
Dan Gohman4d70a292010-11-11 21:23:25 +0000396 // Note that it is not safe to speculate into a malloc'd region because
397 // malloc may return null.
398 // It's also not always safe to follow a bitcast, for example:
399 // bitcast i8* (alloca i8) to i32*
400 // would result in a 4-byte load from a 1-byte alloca. Some cases could
Micah Villmow3574eca2012-10-08 16:38:25 +0000401 // be handled using DataLayout to check sizes and alignments though.
Dan Gohman4d70a292010-11-11 21:23:25 +0000402
403 // These are obviously ok.
Nick Lewycky37abc482012-01-23 00:05:17 +0000404 if (isa<AllocaInst>(V)) return true;
Dan Gohman4d70a292010-11-11 21:23:25 +0000405
406 // Global variables which can't collapse to null are ok.
Nick Lewycky37abc482012-01-23 00:05:17 +0000407 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Dan Gohman4d70a292010-11-11 21:23:25 +0000408 return !GV->hasExternalWeakLinkage();
409
Chris Lattner3928af62011-01-23 21:15:29 +0000410 // byval arguments are ok.
Nick Lewycky37abc482012-01-23 00:05:17 +0000411 if (const Argument *A = dyn_cast<Argument>(V))
Chris Lattner3928af62011-01-23 21:15:29 +0000412 return A->hasByValAttr();
Nick Lewycky37abc482012-01-23 00:05:17 +0000413
Dan Gohman4d70a292010-11-11 21:23:25 +0000414 // For GEPs, determine if the indexing lands within the allocated object.
Nick Lewycky37abc482012-01-23 00:05:17 +0000415 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Dan Gohman4d70a292010-11-11 21:23:25 +0000416 // Conservatively require that the base pointer be fully dereferenceable.
Nick Lewycky37abc482012-01-23 00:05:17 +0000417 if (!Visited.insert(GEP->getOperand(0)))
418 return false;
419 if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
Dan Gohman4d70a292010-11-11 21:23:25 +0000420 return false;
421 // Check the indices.
422 gep_type_iterator GTI = gep_type_begin(GEP);
423 for (User::const_op_iterator I = GEP->op_begin()+1,
424 E = GEP->op_end(); I != E; ++I) {
425 Value *Index = *I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000426 Type *Ty = *GTI++;
Dan Gohman4d70a292010-11-11 21:23:25 +0000427 // Struct indices can't be out of bounds.
428 if (isa<StructType>(Ty))
429 continue;
430 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
431 if (!CI)
432 return false;
433 // Zero is always ok.
434 if (CI->isZero())
435 continue;
436 // Check to see that it's within the bounds of an array.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000437 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
Dan Gohman4d70a292010-11-11 21:23:25 +0000438 if (!ATy)
439 return false;
440 if (CI->getValue().getActiveBits() > 64)
441 return false;
442 if (CI->getZExtValue() >= ATy->getNumElements())
443 return false;
444 }
445 // Indices check out; this is dereferenceable.
446 return true;
447 }
448
449 // If we don't know, assume the worst.
450 return false;
451}
452
Nick Lewycky37abc482012-01-23 00:05:17 +0000453/// isDereferenceablePointer - Test if this value is always a pointer to
454/// allocated and suitably aligned memory for a simple load or store.
455bool Value::isDereferenceablePointer() const {
456 SmallPtrSet<const Value *, 32> Visited;
457 return ::isDereferenceablePointer(this, Visited);
458}
459
Chris Lattner01c8e022008-12-02 18:33:11 +0000460/// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
Chris Lattnerc7f7c1d2008-12-02 07:16:45 +0000461/// return the value in the PHI node corresponding to PredBB. If not, return
462/// ourself. This is useful if you want to know the value something has in a
463/// predecessor block.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000464Value *Value::DoPHITranslation(const BasicBlock *CurBB,
Chris Lattnerc7f7c1d2008-12-02 07:16:45 +0000465 const BasicBlock *PredBB) {
466 PHINode *PN = dyn_cast<PHINode>(this);
467 if (PN && PN->getParent() == CurBB)
468 return PN->getIncomingValueForBlock(PredBB);
469 return this;
470}
471
Owen Andersone922c022009-07-22 00:24:57 +0000472LLVMContext &Value::getContext() const { return VTy->getContext(); }
473
Chris Lattner722272d2009-03-31 22:11:05 +0000474//===----------------------------------------------------------------------===//
475// ValueHandleBase Class
476//===----------------------------------------------------------------------===//
477
Mike Stumpfe095f32009-05-04 18:40:41 +0000478/// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
479/// List is known to point into the existing use list.
Chris Lattner722272d2009-03-31 22:11:05 +0000480void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
481 assert(List && "Handle list is null?");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000482
Chris Lattner722272d2009-03-31 22:11:05 +0000483 // Splice ourselves into the list.
484 Next = *List;
485 *List = this;
486 setPrevPtr(List);
487 if (Next) {
488 Next->setPrevPtr(&Next);
Bill Wendling5252c432012-04-08 10:16:43 +0000489 assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
Chris Lattner722272d2009-03-31 22:11:05 +0000490 }
491}
492
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000493void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
494 assert(List && "Must insert after existing node");
495
496 Next = List->Next;
497 setPrevPtr(&List->Next);
498 List->Next = this;
499 if (Next)
500 Next->setPrevPtr(&Next);
501}
502
Chris Lattner722272d2009-03-31 22:11:05 +0000503/// AddToUseList - Add this ValueHandle to the use list for VP.
504void ValueHandleBase::AddToUseList() {
Bill Wendling5252c432012-04-08 10:16:43 +0000505 assert(VP.getPointer() && "Null pointer doesn't have a use list!");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000506
Bill Wendling5252c432012-04-08 10:16:43 +0000507 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000508
Bill Wendling5252c432012-04-08 10:16:43 +0000509 if (VP.getPointer()->HasValueHandle) {
Chris Lattner722272d2009-03-31 22:11:05 +0000510 // If this value already has a ValueHandle, then it must be in the
511 // ValueHandles map already.
Bill Wendling5252c432012-04-08 10:16:43 +0000512 ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
Chris Lattner722272d2009-03-31 22:11:05 +0000513 assert(Entry != 0 && "Value doesn't have any handles?");
Owen Andersonf2aac282009-06-17 17:36:57 +0000514 AddToExistingUseList(&Entry);
Owen Andersonf2aac282009-06-17 17:36:57 +0000515 return;
Chris Lattner722272d2009-03-31 22:11:05 +0000516 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000517
Chris Lattner722272d2009-03-31 22:11:05 +0000518 // Ok, it doesn't have any handles yet, so we must insert it into the
519 // DenseMap. However, doing this insertion could cause the DenseMap to
520 // reallocate itself, which would invalidate all of the PrevP pointers that
521 // point into the old table. Handle this by checking for reallocation and
522 // updating the stale pointers only if needed.
Owen Anderson4d919432009-08-18 18:28:58 +0000523 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
Chris Lattner722272d2009-03-31 22:11:05 +0000524 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000525
Bill Wendling5252c432012-04-08 10:16:43 +0000526 ValueHandleBase *&Entry = Handles[VP.getPointer()];
Chris Lattner722272d2009-03-31 22:11:05 +0000527 assert(Entry == 0 && "Value really did already have handles?");
528 AddToExistingUseList(&Entry);
Bill Wendling5252c432012-04-08 10:16:43 +0000529 VP.getPointer()->HasValueHandle = true;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000530
Chris Lattner722272d2009-03-31 22:11:05 +0000531 // If reallocation didn't happen or if this was the first insertion, don't
532 // walk the table.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000533 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
Owen Andersonf2aac282009-06-17 17:36:57 +0000534 Handles.size() == 1) {
Chris Lattner722272d2009-03-31 22:11:05 +0000535 return;
Owen Andersonf2aac282009-06-17 17:36:57 +0000536 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000537
Chris Lattner722272d2009-03-31 22:11:05 +0000538 // Okay, reallocation did happen. Fix the Prev Pointers.
Owen Anderson4d919432009-08-18 18:28:58 +0000539 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
540 E = Handles.end(); I != E; ++I) {
Bill Wendling5252c432012-04-08 10:16:43 +0000541 assert(I->second && I->first == I->second->VP.getPointer() &&
542 "List invariant broken!");
Chris Lattner722272d2009-03-31 22:11:05 +0000543 I->second->setPrevPtr(&I->second);
544 }
545}
546
547/// RemoveFromUseList - Remove this ValueHandle from its current use list.
548void ValueHandleBase::RemoveFromUseList() {
Bill Wendling5252c432012-04-08 10:16:43 +0000549 assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
550 "Pointer doesn't have a use list!");
Chris Lattner722272d2009-03-31 22:11:05 +0000551
552 // Unlink this from its use list.
553 ValueHandleBase **PrevPtr = getPrevPtr();
554 assert(*PrevPtr == this && "List invariant broken");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000555
Chris Lattner722272d2009-03-31 22:11:05 +0000556 *PrevPtr = Next;
557 if (Next) {
558 assert(Next->getPrevPtr() == &Next && "List invariant broken");
559 Next->setPrevPtr(PrevPtr);
560 return;
561 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000562
Chris Lattner722272d2009-03-31 22:11:05 +0000563 // If the Next pointer was null, then it is possible that this was the last
564 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
565 // map.
Bill Wendling5252c432012-04-08 10:16:43 +0000566 LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
Owen Anderson4d919432009-08-18 18:28:58 +0000567 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
Chris Lattner722272d2009-03-31 22:11:05 +0000568 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
Bill Wendling5252c432012-04-08 10:16:43 +0000569 Handles.erase(VP.getPointer());
570 VP.getPointer()->HasValueHandle = false;
Chris Lattner722272d2009-03-31 22:11:05 +0000571 }
572}
573
574
575void ValueHandleBase::ValueIsDeleted(Value *V) {
576 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
577
578 // Get the linked list base, which is guaranteed to exist since the
579 // HasValueHandle flag is set.
Owen Anderson4d919432009-08-18 18:28:58 +0000580 LLVMContextImpl *pImpl = V->getContext().pImpl;
581 ValueHandleBase *Entry = pImpl->ValueHandles[V];
Chris Lattner722272d2009-03-31 22:11:05 +0000582 assert(Entry && "Value bit set but no entries exist");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000583
Duncan Sandsffe8c882010-07-24 12:09:22 +0000584 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
585 // and remove themselves from the list without breaking our iteration. This
586 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
587 // Note that we deliberately do not the support the case when dropping a value
588 // handle results in a new value handle being permanently added to the list
589 // (as might occur in theory for CallbackVH's): the new value handle will not
Duncan Sands2c110462010-07-27 06:53:14 +0000590 // be processed and the checking code will mete out righteous punishment if
Duncan Sandsffe8c882010-07-24 12:09:22 +0000591 // the handle is still present once we have finished processing all the other
592 // value handles (it is fine to momentarily add then remove a value handle).
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000593 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
594 Iterator.RemoveFromUseList();
595 Iterator.AddToExistingUseListAfter(Entry);
596 assert(Entry->Next == &Iterator && "Loop invariant broken.");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000597
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000598 switch (Entry->getKind()) {
Chris Lattner722272d2009-03-31 22:11:05 +0000599 case Assert:
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000600 break;
Daniel Dunbare5b18362009-09-22 02:02:33 +0000601 case Tracking:
602 // Mark that this value has been deleted by setting it to an invalid Value
603 // pointer.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000604 Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
Daniel Dunbare5b18362009-09-22 02:02:33 +0000605 break;
Chris Lattner722272d2009-03-31 22:11:05 +0000606 case Weak:
607 // Weak just goes to null, which will unlink it from the list.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000608 Entry->operator=(0);
Chris Lattner722272d2009-03-31 22:11:05 +0000609 break;
610 case Callback:
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000611 // Forward to the subclass's implementation.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000612 static_cast<CallbackVH*>(Entry)->deleted();
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000613 break;
Chris Lattner722272d2009-03-31 22:11:05 +0000614 }
615 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000616
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000617 // All callbacks, weak references, and assertingVHs should be dropped by now.
618 if (V->HasValueHandle) {
619#ifndef NDEBUG // Only in +Asserts mode...
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000620 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000621 << "\n";
622 if (pImpl->ValueHandles[V]->getKind() == Assert)
623 llvm_unreachable("An asserting value handle still pointed to this"
624 " value!");
625
626#endif
627 llvm_unreachable("All references to V were not removed?");
628 }
Chris Lattner722272d2009-03-31 22:11:05 +0000629}
630
631
632void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
633 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
634 assert(Old != New && "Changing value into itself!");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000635
Chris Lattner722272d2009-03-31 22:11:05 +0000636 // Get the linked list base, which is guaranteed to exist since the
637 // HasValueHandle flag is set.
Owen Anderson4d919432009-08-18 18:28:58 +0000638 LLVMContextImpl *pImpl = Old->getContext().pImpl;
639 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
640
Chris Lattner722272d2009-03-31 22:11:05 +0000641 assert(Entry && "Value bit set but no entries exist");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000642
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000643 // We use a local ValueHandleBase as an iterator so that
644 // ValueHandles can add and remove themselves from the list without
645 // breaking our iteration. This is not really an AssertingVH; we
646 // just have to give ValueHandleBase some kind.
647 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
648 Iterator.RemoveFromUseList();
649 Iterator.AddToExistingUseListAfter(Entry);
650 assert(Entry->Next == &Iterator && "Loop invariant broken.");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000651
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000652 switch (Entry->getKind()) {
Chris Lattner722272d2009-03-31 22:11:05 +0000653 case Assert:
654 // Asserting handle does not follow RAUW implicitly.
655 break;
Daniel Dunbare5b18362009-09-22 02:02:33 +0000656 case Tracking:
657 // Tracking goes to new value like a WeakVH. Note that this may make it
658 // something incompatible with its templated type. We don't want to have a
659 // virtual (or inline) interface to handle this though, so instead we make
Daniel Dunbar460a7862009-09-22 10:30:34 +0000660 // the TrackingVH accessors guarantee that a client never sees this value.
Daniel Dunbare5b18362009-09-22 02:02:33 +0000661
662 // FALLTHROUGH
Chris Lattner722272d2009-03-31 22:11:05 +0000663 case Weak:
664 // Weak goes to the new value, which will unlink it from Old's list.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000665 Entry->operator=(New);
Chris Lattner722272d2009-03-31 22:11:05 +0000666 break;
667 case Callback:
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000668 // Forward to the subclass's implementation.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000669 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000670 break;
Chris Lattner722272d2009-03-31 22:11:05 +0000671 }
672 }
Duncan Sands2c110462010-07-27 06:53:14 +0000673
674#ifndef NDEBUG
675 // If any new tracking or weak value handles were added while processing the
676 // list, then complain about it now.
677 if (Old->HasValueHandle)
678 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
679 switch (Entry->getKind()) {
680 case Tracking:
681 case Weak:
682 dbgs() << "After RAUW from " << *Old->getType() << " %"
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000683 << Old->getName() << " to " << *New->getType() << " %"
684 << New->getName() << "\n";
Duncan Sands2c110462010-07-27 06:53:14 +0000685 llvm_unreachable("A tracking or weak value handle still pointed to the"
686 " old value!\n");
687 default:
688 break;
689 }
690#endif
Chris Lattner722272d2009-03-31 22:11:05 +0000691}
692
Benjamin Kramer4e4c3402012-05-19 19:15:25 +0000693// Default implementation for CallbackVH.
694void CallbackVH::allUsesReplacedWith(Value *) {}
695
696void CallbackVH::deleted() {
697 setValPtr(NULL);
698}