blob: 80b993c89f7f75b28e9061333a97e0be88e9f142 [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"
Dmitry Mikulin6d3e69e2017-11-17 00:30:24 +000018#include "llvm/ADT/SetVector.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000019#include "llvm/IR/Constant.h"
20#include "llvm/IR/Constants.h"
Hal Finkela7398342014-07-10 05:27:53 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/DerivedTypes.h"
Reid Kleckner816047d2017-05-18 17:24:10 +000023#include "llvm/IR/DerivedUser.h"
Chandler Carruthbd7cba02014-03-04 10:40:04 +000024#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/InstrTypes.h"
26#include "llvm/IR/Instructions.h"
Ramkumar Ramachandraba59efd2015-02-09 21:08:03 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
29#include "llvm/IR/Operator.h"
Ramkumar Ramachandraba59efd2015-02-09 21:08:03 +000030#include "llvm/IR/Statepoint.h"
Chandler Carrutheb3d76d2014-03-04 11:17:44 +000031#include "llvm/IR/ValueHandle.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000032#include "llvm/IR/ValueSymbolTable.h"
Bill Wendling2e3def12006-11-17 08:03:48 +000033#include "llvm/Support/Debug.h"
Torok Edwinab7c09b2009-07-08 18:01:40 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattner722272d2009-03-31 22:11:05 +000035#include "llvm/Support/ManagedStatic.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000036#include "llvm/Support/raw_ostream.h"
Chris Lattner00950542001-06-06 20:29:01 +000037#include <algorithm>
Eugene Zelenko380d47d2016-02-02 18:20:45 +000038
Chris Lattner31f84992003-11-21 20:23:48 +000039using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000040
Serge Guelton4c23def2018-01-05 19:41:19 +000041static cl::opt<unsigned> NonGlobalValueMaxNameSize(
42 "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
43 cl::desc("Maximum size for the name of non-global values."));
44
Chris Lattner00950542001-06-06 20:29:01 +000045//===----------------------------------------------------------------------===//
46// Value Class
47//===----------------------------------------------------------------------===//
Chris Lattnerdb125cf2011-07-18 04:54:35 +000048static inline Type *checkType(Type *Ty) {
Chris Lattner82d18aa2001-12-13 00:41:27 +000049 assert(Ty && "Value defined with a null type: Error!");
Reid Kleckner9de6eef2014-06-09 23:32:20 +000050 return Ty;
Chris Lattner82d18aa2001-12-13 00:41:27 +000051}
52
Chris Lattnerdb125cf2011-07-18 04:54:35 +000053Value::Value(Type *ty, unsigned scid)
Owen Andersonbd84bdb2015-06-01 22:24:01 +000054 : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
55 HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
Pete Cooperaaa3fa62015-06-12 17:48:10 +000056 NumUserOperands(0), IsUsedByMD(false), HasName(false) {
Serge Gueltonf3d06a22017-11-13 21:55:01 +000057 static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
Chris Lattner1afcace2011-07-09 17:41:24 +000058 // FIXME: Why isn't this in the subclass gunk??
Richard Smith488fdce2012-12-20 04:11:02 +000059 // Note, we cannot call isa<CallInst> before the CallInst has been
60 // constructed.
61 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
Chris Lattner1afcace2011-07-09 17:41:24 +000062 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
63 "invalid CallInst type!");
Richard Smith488fdce2012-12-20 04:11:02 +000064 else if (SubclassID != BasicBlockVal &&
Serge Gueltonf3d06a22017-11-13 21:55:01 +000065 (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
Chris Lattner1afcace2011-07-09 17:41:24 +000066 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
Chris Lattnera9e77812004-07-06 17:44:17 +000067 "Cannot create non-first-class values except for constants!");
Reid Kleckner816047d2017-05-18 17:24:10 +000068 static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
Reid Kleckner4f8c4be2016-02-26 18:08:59 +000069 "Value too big");
Chris Lattner00950542001-06-06 20:29:01 +000070}
71
Gordon Henriksenafba8fe662007-12-10 02:14:30 +000072Value::~Value() {
Chris Lattner722272d2009-03-31 22:11:05 +000073 // Notify all ValueHandles (if present) that this value is going away.
74 if (HasValueHandle)
75 ValueHandleBase::ValueIsDeleted(this);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +000076 if (isUsedByMetadata())
77 ValueAsMetadata::handleDeletion(this);
Daniel Dunbarce99a6e2009-09-20 04:03:34 +000078
Chris Lattner00950542001-06-06 20:29:01 +000079#ifndef NDEBUG // Only in -g mode...
Chris Lattneree976f32001-06-11 15:04:40 +000080 // Check to make sure that there are no uses of this value that are still
81 // around when the value is destroyed. If there are, then we have a dangling
Andrew Kaylordd3224b2015-03-10 23:55:38 +000082 // reference and something is wrong. This code is here to print out where
83 // the value is still being referenced.
Chris Lattneree976f32001-06-11 15:04:40 +000084 //
Gordon Henriksenafba8fe662007-12-10 02:14:30 +000085 if (!use_empty()) {
Benjamin Kramera7b0cb72011-11-15 16:27:03 +000086 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
Andrew Kaylordd3224b2015-03-10 23:55:38 +000087 for (auto *U : users())
88 dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
Chris Lattner00950542001-06-06 20:29:01 +000089 }
90#endif
Gordon Henriksenafba8fe662007-12-10 02:14:30 +000091 assert(use_empty() && "Uses remain when a value is destroyed!");
Chris Lattner4f95d2b2009-08-04 23:07:12 +000092
93 // If this value is named, destroy the name. This should not be in a symtab
94 // at this point.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +000095 destroyValueName();
Chris Lattner00950542001-06-06 20:29:01 +000096}
97
Reid Kleckner816047d2017-05-18 17:24:10 +000098void Value::deleteValue() {
99 switch (getValueID()) {
100#define HANDLE_VALUE(Name) \
101 case Value::Name##Val: \
102 delete static_cast<Name *>(this); \
103 break;
104#define HANDLE_MEMORY_VALUE(Name) \
105 case Value::Name##Val: \
106 static_cast<DerivedUser *>(this)->DeleteValue( \
107 static_cast<DerivedUser *>(this)); \
108 break;
109#define HANDLE_INSTRUCTION(Name) /* nothing */
110#include "llvm/IR/Value.def"
111
112#define HANDLE_INST(N, OPC, CLASS) \
113 case Value::InstructionVal + Instruction::OPC: \
114 delete static_cast<CLASS *>(this); \
115 break;
116#define HANDLE_USER_INST(N, OPC, CLASS)
117#include "llvm/IR/Instruction.def"
118
119 default:
120 llvm_unreachable("attempting to delete unknown value kind");
121 }
122}
123
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000124void Value::destroyValueName() {
125 ValueName *Name = getValueName();
126 if (Name)
127 Name->Destroy();
128 setValueName(nullptr);
129}
130
Chris Lattner29d1ca62005-02-01 01:24:21 +0000131bool Value::hasNUses(unsigned N) const {
Vedant Kumar94a229e2018-11-19 19:54:27 +0000132 return hasNItems(use_begin(), use_end(), N);
Chris Lattner29d1ca62005-02-01 01:24:21 +0000133}
134
Chris Lattner8daf0562005-02-23 16:51:11 +0000135bool Value::hasNUsesOrMore(unsigned N) const {
Vedant Kumar94a229e2018-11-19 19:54:27 +0000136 return hasNItemsOrMore(use_begin(), use_end(), N);
Chris Lattner8daf0562005-02-23 16:51:11 +0000137}
138
Bill Wendlingc4f72dd2008-09-25 22:42:01 +0000139bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
Jakob Stoklund Olesena88d9742013-05-14 23:45:56 +0000140 // This can be computed either by scanning the instructions in BB, or by
141 // scanning the use list of this Value. Both lists can be very long, but
142 // usually one is quite short.
143 //
144 // Scan both lists simultaneously until one is exhausted. This limits the
145 // search to the shorter list.
146 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
Chandler Carruth36b699f2014-03-09 03:16:01 +0000147 const_user_iterator UI = user_begin(), UE = user_end();
Jakob Stoklund Olesena88d9742013-05-14 23:45:56 +0000148 for (; BI != BE && UI != UE; ++BI, ++UI) {
149 // Scan basic block: Check if this Value is used by the instruction at BI.
David Majnemer2d62ce62016-08-12 03:55:06 +0000150 if (is_contained(BI->operands(), this))
Benjamin Kramer4da7f902011-12-05 17:23:27 +0000151 return true;
Jakob Stoklund Olesena88d9742013-05-14 23:45:56 +0000152 // Scan use list: Check if the use at UI is in BB.
David Majnemer2d62ce62016-08-12 03:55:06 +0000153 const auto *User = dyn_cast<Instruction>(*UI);
Evan Cheng502a4f52008-06-12 21:15:59 +0000154 if (User && User->getParent() == BB)
155 return true;
156 }
157 return false;
158}
159
Vedant Kumarca6a4d92018-05-16 23:20:42 +0000160unsigned Value::getNumUses() const {
161 return (unsigned)std::distance(use_begin(), use_end());
162}
Chris Lattner29d1ca62005-02-01 01:24:21 +0000163
Chris Lattner72168112007-02-11 00:37:27 +0000164static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
Craig Topperec0f0bc2014-04-09 06:08:46 +0000165 ST = nullptr;
Chris Lattner72168112007-02-11 00:37:27 +0000166 if (Instruction *I = dyn_cast<Instruction>(V)) {
167 if (BasicBlock *P = I->getParent())
168 if (Function *PP = P->getParent())
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +0000169 ST = PP->getValueSymbolTable();
Chris Lattner72168112007-02-11 00:37:27 +0000170 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000171 if (Function *P = BB->getParent())
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +0000172 ST = P->getValueSymbolTable();
Chris Lattner72168112007-02-11 00:37:27 +0000173 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000174 if (Module *P = GV->getParent())
Chris Lattner72168112007-02-11 00:37:27 +0000175 ST = &P->getValueSymbolTable();
176 } else if (Argument *A = dyn_cast<Argument>(V)) {
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000177 if (Function *P = A->getParent())
Mehdi Aminid1e3c5a2016-09-17 06:00:02 +0000178 ST = P->getValueSymbolTable();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000179 } else {
Chris Lattner72168112007-02-11 00:37:27 +0000180 assert(isa<Constant>(V) && "Unknown value type!");
181 return true; // no name is setable for this.
182 }
183 return false;
184}
Chris Lattner28eca8b2002-10-09 23:12:59 +0000185
Owen Andersonbd84bdb2015-06-01 22:24:01 +0000186ValueName *Value::getValueName() const {
187 if (!HasName) return nullptr;
188
189 LLVMContext &Ctx = getContext();
190 auto I = Ctx.pImpl->ValueNames.find(this);
191 assert(I != Ctx.pImpl->ValueNames.end() &&
192 "No name entry found!");
193
194 return I->second;
195}
196
197void Value::setValueName(ValueName *VN) {
198 LLVMContext &Ctx = getContext();
199
200 assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
201 "HasName bit out of sync!");
202
203 if (!VN) {
204 if (HasName)
205 Ctx.pImpl->ValueNames.erase(this);
206 HasName = false;
207 return;
208 }
209
210 HasName = true;
211 Ctx.pImpl->ValueNames[this] = VN;
212}
213
Daniel Dunbar499027f2009-07-26 00:51:56 +0000214StringRef Value::getName() const {
Daniel Dunbar4fa49902009-07-26 09:22:02 +0000215 // Make sure the empty string is still a C string. For historical reasons,
216 // some clients want to call .data() on the result and expect it to be null
217 // terminated.
Owen Andersonbd84bdb2015-06-01 22:24:01 +0000218 if (!hasName())
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000219 return StringRef("", 0);
220 return getValueName()->getKey();
Chris Lattner71996e72007-08-10 15:34:35 +0000221}
222
Pete Coopera641a4a2015-05-19 00:24:26 +0000223void Value::setNameImpl(const Twine &NewName) {
Mehdi Amini2de99272016-03-10 01:28:54 +0000224 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
Mehdi Amini64a77d02016-04-02 03:46:17 +0000225 if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
Mehdi Amini2de99272016-03-10 01:28:54 +0000226 return;
227
Daniel Dunbar51499322009-08-19 23:37:23 +0000228 // Fast path for common IRBuilder case of setName("") when there is no name.
229 if (NewName.isTriviallyEmpty() && !hasName())
230 return;
231
Daniel Dunbare4760042009-08-19 05:08:06 +0000232 SmallString<256> NameData;
Benjamin Kramerb357e062010-01-13 12:45:23 +0000233 StringRef NameRef = NewName.toStringRef(NameData);
Rafael Espindolaedeaa642013-11-19 21:12:39 +0000234 assert(NameRef.find_first_of(0) == StringRef::npos &&
235 "Null bytes are not allowed in names");
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000236
Daniel Dunbar07f69032009-07-26 00:42:33 +0000237 // Name isn't changing?
Benjamin Kramerb357e062010-01-13 12:45:23 +0000238 if (getName() == NameRef)
Daniel Dunbar07f69032009-07-26 00:42:33 +0000239 return;
240
Serge Guelton4c23def2018-01-05 19:41:19 +0000241 // Cap the size of non-GlobalValue names.
242 if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
243 NameRef =
244 NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
245
Benjamin Kramerf0127052010-01-05 13:12:22 +0000246 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000247
Chris Lattner04cb8002005-03-06 02:14:28 +0000248 // Get the symbol table to update for this object.
Chris Lattner72168112007-02-11 00:37:27 +0000249 ValueSymbolTable *ST;
250 if (getSymTab(this, ST))
251 return; // Cannot set a name on this value (e.g. constant).
Chris Lattner0d1e4072005-03-05 19:51:50 +0000252
Chris Lattnerdec628e2007-02-12 05:18:08 +0000253 if (!ST) { // No symbol table to update? Just do the change.
Benjamin Kramerb357e062010-01-13 12:45:23 +0000254 if (NameRef.empty()) {
Chris Lattnerdec628e2007-02-12 05:18:08 +0000255 // Free the name for this value.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000256 destroyValueName();
Chris Lattner042ad362007-02-12 18:52:59 +0000257 return;
Chris Lattner04cb8002005-03-06 02:14:28 +0000258 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000259
Chris Lattner042ad362007-02-12 18:52:59 +0000260 // NOTE: Could optimize for the case the name is shrinking to not deallocate
261 // then reallocated.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000262 destroyValueName();
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000263
Chris Lattner042ad362007-02-12 18:52:59 +0000264 // Create the new name.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000265 setValueName(ValueName::Create(NameRef));
266 getValueName()->setValue(this);
Chris Lattnerdec628e2007-02-12 05:18:08 +0000267 return;
Chris Lattner04cb8002005-03-06 02:14:28 +0000268 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000269
Chris Lattnerdec628e2007-02-12 05:18:08 +0000270 // NOTE: Could optimize for the case the name is shrinking to not deallocate
271 // then reallocated.
272 if (hasName()) {
Chris Lattnerdec628e2007-02-12 05:18:08 +0000273 // Remove old name.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000274 ST->removeValueName(getValueName());
275 destroyValueName();
Chris Lattnerdec628e2007-02-12 05:18:08 +0000276
Benjamin Kramerb357e062010-01-13 12:45:23 +0000277 if (NameRef.empty())
Chris Lattner042ad362007-02-12 18:52:59 +0000278 return;
Chris Lattnerdec628e2007-02-12 05:18:08 +0000279 }
280
281 // Name is changing to something new.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000282 setValueName(ST->createValueName(NameRef, this));
Chris Lattner0d1e4072005-03-05 19:51:50 +0000283}
284
Pete Coopera641a4a2015-05-19 00:24:26 +0000285void Value::setName(const Twine &NewName) {
286 setNameImpl(NewName);
287 if (Function *F = dyn_cast<Function>(this))
288 F->recalculateIntrinsicID();
289}
290
Chris Lattner72168112007-02-11 00:37:27 +0000291void Value::takeName(Value *V) {
Craig Topperec0f0bc2014-04-09 06:08:46 +0000292 ValueSymbolTable *ST = nullptr;
Chris Lattner0878c312007-02-15 20:01:43 +0000293 // If this value has a name, drop it.
294 if (hasName()) {
295 // Get the symtab this is in.
296 if (getSymTab(this, ST)) {
297 // We can't set a name on this value, but we need to clear V's name if
298 // it has one.
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000299 if (V->hasName()) V->setName("");
Chris Lattner0878c312007-02-15 20:01:43 +0000300 return; // Cannot set a name on this value (e.g. constant).
301 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000302
Chris Lattner0878c312007-02-15 20:01:43 +0000303 // Remove old name.
304 if (ST)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000305 ST->removeValueName(getValueName());
306 destroyValueName();
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000307 }
308
Chris Lattner0878c312007-02-15 20:01:43 +0000309 // Now we know that this has no name.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000310
Chris Lattner0878c312007-02-15 20:01:43 +0000311 // If V has no name either, we're done.
312 if (!V->hasName()) return;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000313
Chris Lattner0878c312007-02-15 20:01:43 +0000314 // Get this's symtab if we didn't before.
315 if (!ST) {
316 if (getSymTab(this, ST)) {
317 // Clear V's name.
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000318 V->setName("");
Chris Lattner0878c312007-02-15 20:01:43 +0000319 return; // Cannot set a name on this value (e.g. constant).
320 }
321 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000322
Chris Lattner0878c312007-02-15 20:01:43 +0000323 // Get V's ST, this should always succed, because V has a name.
324 ValueSymbolTable *VST;
325 bool Failure = getSymTab(V, VST);
Jeffrey Yasskin8e68c382010-12-23 00:58:24 +0000326 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000327
Chris Lattner0878c312007-02-15 20:01:43 +0000328 // If these values are both in the same symtab, we can do this very fast.
329 // This works even if both values have no symtab yet.
330 if (ST == VST) {
331 // Take the name!
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000332 setValueName(V->getValueName());
333 V->setValueName(nullptr);
334 getValueName()->setValue(this);
Chris Lattnerf41916e2007-02-11 01:04:09 +0000335 return;
336 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000337
Chris Lattner0878c312007-02-15 20:01:43 +0000338 // Otherwise, things are slightly more complex. Remove V's name from VST and
339 // then reinsert it into ST.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000340
Chris Lattner0878c312007-02-15 20:01:43 +0000341 if (VST)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000342 VST->removeValueName(V->getValueName());
343 setValueName(V->getValueName());
344 V->setValueName(nullptr);
345 getValueName()->setValue(this);
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000346
Chris Lattner0878c312007-02-15 20:01:43 +0000347 if (ST)
348 ST->reinsertValue(this);
Chris Lattner72168112007-02-11 00:37:27 +0000349}
350
Craig Topper6ffcfe02017-01-13 06:26:18 +0000351void Value::assertModuleIsMaterializedImpl() const {
Todd Fiala888a66d2016-02-03 21:13:23 +0000352#ifndef NDEBUG
Rafael Espindola17920c22016-01-15 19:00:20 +0000353 const GlobalValue *GV = dyn_cast<GlobalValue>(this);
354 if (!GV)
355 return;
356 const Module *M = GV->getParent();
357 if (!M)
358 return;
359 assert(M->isMaterialized());
Todd Fiala888a66d2016-02-03 21:13:23 +0000360#endif
Rafael Espindola17920c22016-01-15 19:00:20 +0000361}
362
Todd Fiala888a66d2016-02-03 21:13:23 +0000363#ifndef NDEBUG
Craig Topper431bdfc2014-08-21 05:55:13 +0000364static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
Rafael Espindolae2b37442014-05-13 01:23:21 +0000365 Constant *C) {
David Blaikie5401ba72014-11-19 07:49:26 +0000366 if (!Cache.insert(Expr).second)
Rafael Espindolae2b37442014-05-13 01:23:21 +0000367 return false;
368
369 for (auto &O : Expr->operands()) {
370 if (O == C)
371 return true;
372 auto *CE = dyn_cast<ConstantExpr>(O);
373 if (!CE)
374 continue;
375 if (contains(Cache, CE, C))
376 return true;
377 }
378 return false;
379}
380
381static bool contains(Value *Expr, Value *V) {
382 if (Expr == V)
383 return true;
384
385 auto *C = dyn_cast<Constant>(V);
386 if (!C)
387 return false;
388
389 auto *CE = dyn_cast<ConstantExpr>(Expr);
390 if (!CE)
391 return false;
392
393 SmallPtrSet<ConstantExpr *, 4> Cache;
394 return contains(Cache, CE, C);
395}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000396#endif // NDEBUG
Chris Lattner72168112007-02-11 00:37:27 +0000397
JF Bastien4afd04a2018-08-09 18:28:54 +0000398void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
Chris Lattner678f9e02011-07-15 06:18:52 +0000399 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
Rafael Espindolae2b37442014-05-13 01:23:21 +0000400 assert(!contains(New, this) &&
401 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
Chris Lattner678f9e02011-07-15 06:18:52 +0000402 assert(New->getType() == getType() &&
403 "replaceAllUses of value with new value of different type!");
404
Chris Lattner722272d2009-03-31 22:11:05 +0000405 // Notify all ValueHandles (if present) that this value is going away.
406 if (HasValueHandle)
407 ValueHandleBase::ValueIsRAUWd(this, New);
JF Bastien4afd04a2018-08-09 18:28:54 +0000408 if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000409 ValueAsMetadata::handleRAUW(this, New);
Michael Ilseman4c8e74f2013-03-01 18:48:54 +0000410
Teresa Johnson2140d922017-12-16 00:18:12 +0000411 while (!materialized_use_empty()) {
Gabor Greif6f426652008-09-19 15:13:20 +0000412 Use &U = *UseList;
Chris Lattner2bc065b2003-08-29 05:09:37 +0000413 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
Chris Lattner2d691332007-08-21 00:21:07 +0000414 // constant because they are uniqued.
Rafael Espindola27c076a2014-05-16 19:35:39 +0000415 if (auto *C = dyn_cast<Constant>(U.getUser())) {
Chris Lattner2d691332007-08-21 00:21:07 +0000416 if (!isa<GlobalValue>(C)) {
Mehdi Amini4c696962016-02-10 22:47:15 +0000417 C->handleOperandChange(this, New);
Chris Lattner2d691332007-08-21 00:21:07 +0000418 continue;
419 }
Chris Lattner2bc065b2003-08-29 05:09:37 +0000420 }
Michael Ilseman4c8e74f2013-03-01 18:48:54 +0000421
Chris Lattner2d691332007-08-21 00:21:07 +0000422 U.set(New);
Chris Lattner2bc065b2003-08-29 05:09:37 +0000423 }
Michael Ilseman4c8e74f2013-03-01 18:48:54 +0000424
Jay Foad95c3e482011-06-23 09:09:15 +0000425 if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
426 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
Chris Lattner2bc065b2003-08-29 05:09:37 +0000427}
428
Davide Italiano4e519832016-12-07 21:47:32 +0000429void Value::replaceAllUsesWith(Value *New) {
JF Bastien4afd04a2018-08-09 18:28:54 +0000430 doRAUW(New, ReplaceMetadataUses::Yes);
Davide Italiano4e519832016-12-07 21:47:32 +0000431}
432
433void Value::replaceNonMetadataUsesWith(Value *New) {
JF Bastien4afd04a2018-08-09 18:28:54 +0000434 doRAUW(New, ReplaceMetadataUses::No);
Davide Italiano4e519832016-12-07 21:47:32 +0000435}
436
Gerolf Hoflehner5182ad52014-11-21 23:36:44 +0000437// Like replaceAllUsesWith except it does not handle constants or basic blocks.
438// This routine leaves uses within BB.
439void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
440 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
441 assert(!contains(New, this) &&
442 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
443 assert(New->getType() == getType() &&
444 "replaceUses of value with new value of different type!");
445 assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
446
447 use_iterator UI = use_begin(), E = use_end();
448 for (; UI != E;) {
449 Use &U = *UI;
450 ++UI;
451 auto *Usr = dyn_cast<Instruction>(U.getUser());
452 if (Usr && Usr->getParent() == BB)
453 continue;
454 U.set(New);
455 }
Gerolf Hoflehner5182ad52014-11-21 23:36:44 +0000456}
457
Chandler Carruth84dfc322012-03-10 08:39:09 +0000458namespace {
459// Various metrics for how much to strip off of pointers.
460enum PointerStripKind {
461 PSK_ZeroIndices,
Rafael Espindolaeaf14782013-05-06 01:48:55 +0000462 PSK_ZeroIndicesAndAliases,
Piotr Padlewski9648b462018-05-03 11:03:01 +0000463 PSK_ZeroIndicesAndAliasesAndInvariantGroups,
Chandler Carruth274d3772012-03-14 23:19:53 +0000464 PSK_InBoundsConstantIndices,
465 PSK_InBounds
Chandler Carruth84dfc322012-03-10 08:39:09 +0000466};
467
468template <PointerStripKind StripKind>
Craig Topper306a7df2017-03-27 05:47:03 +0000469static const Value *stripPointerCastsAndOffsets(const Value *V) {
Chandler Carruth84dfc322012-03-10 08:39:09 +0000470 if (!V->getType()->isPointerTy())
471 return V;
Dan Gohman50f424c2010-06-28 21:16:52 +0000472
473 // Even though we don't look through PHI nodes, we could be called on an
474 // instruction in an unreachable block, which may be on a cycle.
Craig Topper306a7df2017-03-27 05:47:03 +0000475 SmallPtrSet<const Value *, 4> Visited;
Dan Gohman50f424c2010-06-28 21:16:52 +0000476
Dan Gohman50f424c2010-06-28 21:16:52 +0000477 Visited.insert(V);
Duncan Sandsf08bf112008-12-29 21:06:19 +0000478 do {
Craig Topper306a7df2017-03-27 05:47:03 +0000479 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +0000480 switch (StripKind) {
Rafael Espindolaeaf14782013-05-06 01:48:55 +0000481 case PSK_ZeroIndicesAndAliases:
Piotr Padlewski9648b462018-05-03 11:03:01 +0000482 case PSK_ZeroIndicesAndAliasesAndInvariantGroups:
Chandler Carruth84dfc322012-03-10 08:39:09 +0000483 case PSK_ZeroIndices:
484 if (!GEP->hasAllZeroIndices())
485 return V;
486 break;
Chandler Carruth274d3772012-03-14 23:19:53 +0000487 case PSK_InBoundsConstantIndices:
Chandler Carruth84dfc322012-03-10 08:39:09 +0000488 if (!GEP->hasAllConstantIndices())
489 return V;
Justin Bogner6673ea82016-08-17 05:10:15 +0000490 LLVM_FALLTHROUGH;
Chandler Carruth84dfc322012-03-10 08:39:09 +0000491 case PSK_InBounds:
492 if (!GEP->isInBounds())
493 return V;
494 break;
Chandler Carruth84dfc322012-03-10 08:39:09 +0000495 }
Dan Gohman016de812009-07-17 23:55:56 +0000496 V = GEP->getPointerOperand();
Matt Arsenault59d3ae62013-11-15 01:34:59 +0000497 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
498 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohman016de812009-07-17 23:55:56 +0000499 V = cast<Operator>(V)->getOperand(0);
Craig Topper306a7df2017-03-27 05:47:03 +0000500 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Dasc9e3e3c2016-04-08 00:48:30 +0000501 if (StripKind == PSK_ZeroIndices || GA->isInterposable())
Dan Gohmanaac1bfb2009-08-27 17:55:13 +0000502 return V;
503 V = GA->getAliasee();
Duncan Sandsf08bf112008-12-29 21:06:19 +0000504 } else {
Chandler Carruth9f32dc92019-01-07 07:31:49 +0000505 if (const auto *Call = dyn_cast<CallBase>(V)) {
506 if (const Value *RV = Call->getReturnedArgOperand()) {
Hal Finkel4cb33662016-07-11 01:32:20 +0000507 V = RV;
508 continue;
509 }
Piotr Padlewski9648b462018-05-03 11:03:01 +0000510 // The result of launder.invariant.group must alias it's argument,
Piotr Padlewski69866702017-04-24 19:37:17 +0000511 // but it can't be marked with returned attribute, that's why it needs
512 // special case.
Piotr Padlewski9648b462018-05-03 11:03:01 +0000513 if (StripKind == PSK_ZeroIndicesAndAliasesAndInvariantGroups &&
Chandler Carruth9f32dc92019-01-07 07:31:49 +0000514 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
515 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
516 V = Call->getArgOperand(0);
Piotr Padlewski69866702017-04-24 19:37:17 +0000517 continue;
518 }
519 }
Duncan Sandsf08bf112008-12-29 21:06:19 +0000520 return V;
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000521 }
Duncan Sands1df98592010-02-16 11:11:14 +0000522 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie5401ba72014-11-19 07:49:26 +0000523 } while (Visited.insert(V).second);
Dan Gohman50f424c2010-06-28 21:16:52 +0000524
525 return V;
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000526}
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000527} // end anonymous namespace
Chandler Carruth84dfc322012-03-10 08:39:09 +0000528
Craig Topper306a7df2017-03-27 05:47:03 +0000529const Value *Value::stripPointerCasts() const {
Rafael Espindolaeaf14782013-05-06 01:48:55 +0000530 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
531}
532
Craig Topper306a7df2017-03-27 05:47:03 +0000533const Value *Value::stripPointerCastsNoFollowAliases() const {
Chandler Carruth84dfc322012-03-10 08:39:09 +0000534 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
535}
536
Craig Topper306a7df2017-03-27 05:47:03 +0000537const Value *Value::stripInBoundsConstantOffsets() const {
Chandler Carruth274d3772012-03-14 23:19:53 +0000538 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
Chandler Carruth84dfc322012-03-10 08:39:09 +0000539}
540
Piotr Padlewski9648b462018-05-03 11:03:01 +0000541const Value *Value::stripPointerCastsAndInvariantGroups() const {
542 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliasesAndInvariantGroups>(
Piotr Padlewski69866702017-04-24 19:37:17 +0000543 this);
544}
545
Craig Topper306a7df2017-03-27 05:47:03 +0000546const Value *
547Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
548 APInt &Offset) const {
Chandler Carruthf73826b2013-08-22 11:25:11 +0000549 if (!getType()->isPointerTy())
550 return this;
551
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000552 assert(Offset.getBitWidth() == DL.getIndexSizeInBits(cast<PointerType>(
Chandler Carruthf73826b2013-08-22 11:25:11 +0000553 getType())->getAddressSpace()) &&
Elena Demikhovsky8e229ec2018-02-14 06:58:08 +0000554 "The offset bit width does not match the DL specification.");
Chandler Carruthf73826b2013-08-22 11:25:11 +0000555
556 // Even though we don't look through PHI nodes, we could be called on an
557 // instruction in an unreachable block, which may be on a cycle.
Craig Topper306a7df2017-03-27 05:47:03 +0000558 SmallPtrSet<const Value *, 4> Visited;
Chandler Carruthf73826b2013-08-22 11:25:11 +0000559 Visited.insert(this);
Craig Topper306a7df2017-03-27 05:47:03 +0000560 const Value *V = this;
Chandler Carruthf73826b2013-08-22 11:25:11 +0000561 do {
Craig Topper306a7df2017-03-27 05:47:03 +0000562 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruthf73826b2013-08-22 11:25:11 +0000563 if (!GEP->isInBounds())
564 return V;
Chandler Carruthc99a0d82013-08-25 10:46:39 +0000565 APInt GEPOffset(Offset);
566 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruthf73826b2013-08-22 11:25:11 +0000567 return V;
Chandler Carruthc99a0d82013-08-25 10:46:39 +0000568 Offset = GEPOffset;
Chandler Carruthf73826b2013-08-22 11:25:11 +0000569 V = GEP->getPointerOperand();
Philip Reamesf29442d2015-09-23 19:48:43 +0000570 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Chandler Carruthf73826b2013-08-22 11:25:11 +0000571 V = cast<Operator>(V)->getOperand(0);
Craig Topper306a7df2017-03-27 05:47:03 +0000572 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
Chandler Carruthf73826b2013-08-22 11:25:11 +0000573 V = GA->getAliasee();
574 } else {
Chandler Carruth9f32dc92019-01-07 07:31:49 +0000575 if (const auto *Call = dyn_cast<CallBase>(V))
576 if (const Value *RV = Call->getReturnedArgOperand()) {
Hal Finkel4cb33662016-07-11 01:32:20 +0000577 V = RV;
578 continue;
579 }
580
Chandler Carruthf73826b2013-08-22 11:25:11 +0000581 return V;
582 }
583 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie5401ba72014-11-19 07:49:26 +0000584 } while (Visited.insert(V).second);
Chandler Carruthf73826b2013-08-22 11:25:11 +0000585
586 return V;
587}
588
Craig Topper306a7df2017-03-27 05:47:03 +0000589const Value *Value::stripInBoundsOffsets() const {
Chandler Carruth84dfc322012-03-10 08:39:09 +0000590 return stripPointerCastsAndOffsets<PSK_InBounds>(this);
591}
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +0000592
Bjorn Steinbrink53f82892017-12-17 21:20:16 +0000593uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
Sanjoy Dasca4fdcc2016-06-02 00:52:48 +0000594 bool &CanBeNull) const {
Artur Pilipenko25f648c2016-04-27 12:51:01 +0000595 assert(getType()->isPointerTy() && "must be pointer");
596
Bjorn Steinbrink53f82892017-12-17 21:20:16 +0000597 uint64_t DerefBytes = 0;
Artur Pilipenko25f648c2016-04-27 12:51:01 +0000598 CanBeNull = false;
599 if (const Argument *A = dyn_cast<Argument>(this)) {
600 DerefBytes = A->getDereferenceableBytes();
Bjorn Steinbrink9cf20672017-12-19 08:46:46 +0000601 if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
Bjorn Steinbrinkb2ce4832017-12-17 02:37:42 +0000602 Type *PT = cast<PointerType>(A->getType())->getElementType();
Bjorn Steinbrink9cf20672017-12-19 08:46:46 +0000603 if (PT->isSized())
604 DerefBytes = DL.getTypeStoreSize(PT);
Sanjoy Dasca4fdcc2016-06-02 00:52:48 +0000605 }
Artur Pilipenko25f648c2016-04-27 12:51:01 +0000606 if (DerefBytes == 0) {
607 DerefBytes = A->getDereferenceableOrNullBytes();
608 CanBeNull = true;
609 }
Chandler Carruth9f32dc92019-01-07 07:31:49 +0000610 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
611 DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
Artur Pilipenko25f648c2016-04-27 12:51:01 +0000612 if (DerefBytes == 0) {
Chandler Carruth9f32dc92019-01-07 07:31:49 +0000613 DerefBytes =
614 Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
Artur Pilipenko25f648c2016-04-27 12:51:01 +0000615 CanBeNull = true;
616 }
617 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
618 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
619 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
620 DerefBytes = CI->getLimitedValue();
621 }
622 if (DerefBytes == 0) {
623 if (MDNode *MD =
624 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
625 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
626 DerefBytes = CI->getLimitedValue();
627 }
628 CanBeNull = true;
629 }
Sanjoy Dasca4fdcc2016-06-02 00:52:48 +0000630 } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
Bjorn Steinbrinkea96fe12017-12-20 10:01:30 +0000631 if (!AI->isArrayAllocation()) {
632 DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
Sanjoy Dasca4fdcc2016-06-02 00:52:48 +0000633 CanBeNull = false;
634 }
635 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
636 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
637 // TODO: Don't outright reject hasExternalWeakLinkage but set the
638 // CanBeNull flag.
639 DerefBytes = DL.getTypeStoreSize(GV->getValueType());
640 CanBeNull = false;
641 }
Artur Pilipenko25f648c2016-04-27 12:51:01 +0000642 }
643 return DerefBytes;
644}
645
Artur Pilipenkof5b27492016-02-24 12:25:10 +0000646unsigned Value::getPointerAlignment(const DataLayout &DL) const {
647 assert(getType()->isPointerTy() && "must be pointer");
648
649 unsigned Align = 0;
650 if (auto *GO = dyn_cast<GlobalObject>(this)) {
Mikhail Maltsev90b5ec22018-04-27 09:12:12 +0000651 // Don't make any assumptions about function pointer alignment. Some
652 // targets use the LSBs to store additional information.
653 if (isa<Function>(GO))
654 return 0;
Artur Pilipenkof5b27492016-02-24 12:25:10 +0000655 Align = GO->getAlignment();
656 if (Align == 0) {
657 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
658 Type *ObjectType = GVar->getValueType();
659 if (ObjectType->isSized()) {
660 // If the object is defined in the current Module, we'll be giving
661 // it the preferred alignment. Otherwise, we have to assume that it
662 // may only have the minimum ABI alignment.
663 if (GVar->isStrongDefinitionForLinker())
664 Align = DL.getPreferredAlignment(GVar);
665 else
666 Align = DL.getABITypeAlignment(ObjectType);
667 }
668 }
669 }
670 } else if (const Argument *A = dyn_cast<Argument>(this)) {
671 Align = A->getParamAlignment();
672
673 if (!Align && A->hasStructRetAttr()) {
674 // An sret parameter has at least the ABI alignment of the return type.
675 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
676 if (EltTy->isSized())
677 Align = DL.getABITypeAlignment(EltTy);
678 }
Artur Pilipenko5f2b68d2016-04-27 10:42:29 +0000679 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
Artur Pilipenkof5b27492016-02-24 12:25:10 +0000680 Align = AI->getAlignment();
Artur Pilipenko5f2b68d2016-04-27 10:42:29 +0000681 if (Align == 0) {
682 Type *AllocatedType = AI->getAllocatedType();
683 if (AllocatedType->isSized())
684 Align = DL.getPrefTypeAlignment(AllocatedType);
685 }
Chandler Carruth9f32dc92019-01-07 07:31:49 +0000686 } else if (const auto *Call = dyn_cast<CallBase>(this))
687 Align = Call->getAttributes().getRetAlignment();
Artur Pilipenkof5b27492016-02-24 12:25:10 +0000688 else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
689 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
690 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
691 Align = CI->getLimitedValue();
692 }
693
694 return Align;
695}
696
Craig Topper306a7df2017-03-27 05:47:03 +0000697const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
698 const BasicBlock *PredBB) const {
699 auto *PN = dyn_cast<PHINode>(this);
Chris Lattnerc7f7c1d2008-12-02 07:16:45 +0000700 if (PN && PN->getParent() == CurBB)
701 return PN->getIncomingValueForBlock(PredBB);
702 return this;
703}
704
Owen Andersone922c022009-07-22 00:24:57 +0000705LLVMContext &Value::getContext() const { return VTy->getContext(); }
706
Duncan P. N. Exon Smith99a43c22014-08-01 23:28:49 +0000707void Value::reverseUseList() {
708 if (!UseList || !UseList->Next)
709 // No need to reverse 0 or 1 uses.
710 return;
711
712 Use *Head = UseList;
713 Use *Current = UseList->Next;
714 Head->Next = nullptr;
715 while (Current) {
716 Use *Next = Current->Next;
717 Current->Next = Head;
718 Head->setPrev(&Current->Next);
719 Head = Current;
720 Current = Next;
721 }
722 UseList = Head;
723 Head->setPrev(&UseList);
724}
725
Arnold Schwaighoferdf708a52016-09-10 18:14:54 +0000726bool Value::isSwiftError() const {
727 auto *Arg = dyn_cast<Argument>(this);
728 if (Arg)
729 return Arg->hasSwiftErrorAttr();
730 auto *Alloca = dyn_cast<AllocaInst>(this);
731 if (!Alloca)
732 return false;
733 return Alloca->isSwiftError();
734}
735
Chris Lattner722272d2009-03-31 22:11:05 +0000736//===----------------------------------------------------------------------===//
737// ValueHandleBase Class
738//===----------------------------------------------------------------------===//
739
Chris Lattner722272d2009-03-31 22:11:05 +0000740void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
741 assert(List && "Handle list is null?");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000742
Chris Lattner722272d2009-03-31 22:11:05 +0000743 // Splice ourselves into the list.
744 Next = *List;
745 *List = this;
746 setPrevPtr(List);
747 if (Next) {
748 Next->setPrevPtr(&Next);
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000749 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
Chris Lattner722272d2009-03-31 22:11:05 +0000750 }
751}
752
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000753void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
754 assert(List && "Must insert after existing node");
755
756 Next = List->Next;
757 setPrevPtr(&List->Next);
758 List->Next = this;
759 if (Next)
760 Next->setPrevPtr(&Next);
761}
762
Chris Lattner722272d2009-03-31 22:11:05 +0000763void ValueHandleBase::AddToUseList() {
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000764 assert(getValPtr() && "Null pointer doesn't have a use list!");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000765
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000766 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000767
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000768 if (getValPtr()->HasValueHandle) {
Chris Lattner722272d2009-03-31 22:11:05 +0000769 // If this value already has a ValueHandle, then it must be in the
770 // ValueHandles map already.
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000771 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
Craig Topper0b6cb712014-04-15 06:32:26 +0000772 assert(Entry && "Value doesn't have any handles?");
Owen Andersonf2aac282009-06-17 17:36:57 +0000773 AddToExistingUseList(&Entry);
Owen Andersonf2aac282009-06-17 17:36:57 +0000774 return;
Chris Lattner722272d2009-03-31 22:11:05 +0000775 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000776
Chris Lattner722272d2009-03-31 22:11:05 +0000777 // Ok, it doesn't have any handles yet, so we must insert it into the
778 // DenseMap. However, doing this insertion could cause the DenseMap to
779 // reallocate itself, which would invalidate all of the PrevP pointers that
780 // point into the old table. Handle this by checking for reallocation and
781 // updating the stale pointers only if needed.
Owen Anderson4d919432009-08-18 18:28:58 +0000782 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
Chris Lattner722272d2009-03-31 22:11:05 +0000783 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000784
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000785 ValueHandleBase *&Entry = Handles[getValPtr()];
Craig Topper0b6cb712014-04-15 06:32:26 +0000786 assert(!Entry && "Value really did already have handles?");
Chris Lattner722272d2009-03-31 22:11:05 +0000787 AddToExistingUseList(&Entry);
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000788 getValPtr()->HasValueHandle = true;
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000789
Chris Lattner722272d2009-03-31 22:11:05 +0000790 // If reallocation didn't happen or if this was the first insertion, don't
791 // walk the table.
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000792 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
Owen Andersonf2aac282009-06-17 17:36:57 +0000793 Handles.size() == 1) {
Chris Lattner722272d2009-03-31 22:11:05 +0000794 return;
Owen Andersonf2aac282009-06-17 17:36:57 +0000795 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000796
Chris Lattner722272d2009-03-31 22:11:05 +0000797 // Okay, reallocation did happen. Fix the Prev Pointers.
Owen Anderson4d919432009-08-18 18:28:58 +0000798 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
799 E = Handles.end(); I != E; ++I) {
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000800 assert(I->second && I->first == I->second->getValPtr() &&
Bill Wendling5252c432012-04-08 10:16:43 +0000801 "List invariant broken!");
Chris Lattner722272d2009-03-31 22:11:05 +0000802 I->second->setPrevPtr(&I->second);
803 }
804}
805
Chris Lattner722272d2009-03-31 22:11:05 +0000806void ValueHandleBase::RemoveFromUseList() {
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000807 assert(getValPtr() && getValPtr()->HasValueHandle &&
Bill Wendling5252c432012-04-08 10:16:43 +0000808 "Pointer doesn't have a use list!");
Chris Lattner722272d2009-03-31 22:11:05 +0000809
810 // Unlink this from its use list.
811 ValueHandleBase **PrevPtr = getPrevPtr();
812 assert(*PrevPtr == this && "List invariant broken");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000813
Chris Lattner722272d2009-03-31 22:11:05 +0000814 *PrevPtr = Next;
815 if (Next) {
816 assert(Next->getPrevPtr() == &Next && "List invariant broken");
817 Next->setPrevPtr(PrevPtr);
818 return;
819 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000820
Chris Lattner722272d2009-03-31 22:11:05 +0000821 // If the Next pointer was null, then it is possible that this was the last
822 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
823 // map.
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000824 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
Owen Anderson4d919432009-08-18 18:28:58 +0000825 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
Chris Lattner722272d2009-03-31 22:11:05 +0000826 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
Sanjoy Das9f5bf2cd2017-04-27 06:02:18 +0000827 Handles.erase(getValPtr());
828 getValPtr()->HasValueHandle = false;
Chris Lattner722272d2009-03-31 22:11:05 +0000829 }
830}
831
Chris Lattner722272d2009-03-31 22:11:05 +0000832void ValueHandleBase::ValueIsDeleted(Value *V) {
833 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
834
835 // Get the linked list base, which is guaranteed to exist since the
836 // HasValueHandle flag is set.
Owen Anderson4d919432009-08-18 18:28:58 +0000837 LLVMContextImpl *pImpl = V->getContext().pImpl;
838 ValueHandleBase *Entry = pImpl->ValueHandles[V];
Chris Lattner722272d2009-03-31 22:11:05 +0000839 assert(Entry && "Value bit set but no entries exist");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000840
Duncan Sandsffe8c882010-07-24 12:09:22 +0000841 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
842 // and remove themselves from the list without breaking our iteration. This
843 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
844 // Note that we deliberately do not the support the case when dropping a value
845 // handle results in a new value handle being permanently added to the list
846 // (as might occur in theory for CallbackVH's): the new value handle will not
Duncan Sands2c110462010-07-27 06:53:14 +0000847 // be processed and the checking code will mete out righteous punishment if
Duncan Sandsffe8c882010-07-24 12:09:22 +0000848 // the handle is still present once we have finished processing all the other
849 // value handles (it is fine to momentarily add then remove a value handle).
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000850 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
851 Iterator.RemoveFromUseList();
852 Iterator.AddToExistingUseListAfter(Entry);
853 assert(Entry->Next == &Iterator && "Loop invariant broken.");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000854
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000855 switch (Entry->getKind()) {
Chris Lattner722272d2009-03-31 22:11:05 +0000856 case Assert:
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000857 break;
Sanjoy Das41673c62017-05-01 17:07:54 +0000858 case Weak:
Sanjoy Das399b4d02017-05-01 17:07:49 +0000859 case WeakTracking:
Sanjoy Das41673c62017-05-01 17:07:54 +0000860 // WeakTracking and Weak just go to null, which unlinks them
861 // from the list.
Craig Topperec0f0bc2014-04-09 06:08:46 +0000862 Entry->operator=(nullptr);
Chris Lattner722272d2009-03-31 22:11:05 +0000863 break;
864 case Callback:
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000865 // Forward to the subclass's implementation.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000866 static_cast<CallbackVH*>(Entry)->deleted();
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000867 break;
Chris Lattner722272d2009-03-31 22:11:05 +0000868 }
869 }
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000870
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000871 // All callbacks, weak references, and assertingVHs should be dropped by now.
872 if (V->HasValueHandle) {
873#ifndef NDEBUG // Only in +Asserts mode...
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000874 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000875 << "\n";
876 if (pImpl->ValueHandles[V]->getKind() == Assert)
877 llvm_unreachable("An asserting value handle still pointed to this"
878 " value!");
879
880#endif
881 llvm_unreachable("All references to V were not removed?");
882 }
Chris Lattner722272d2009-03-31 22:11:05 +0000883}
884
Chris Lattner722272d2009-03-31 22:11:05 +0000885void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
886 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
887 assert(Old != New && "Changing value into itself!");
Frederic Riss648728d2014-10-23 04:08:42 +0000888 assert(Old->getType() == New->getType() &&
889 "replaceAllUses of value with new value of different type!");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000890
Chris Lattner722272d2009-03-31 22:11:05 +0000891 // Get the linked list base, which is guaranteed to exist since the
892 // HasValueHandle flag is set.
Owen Anderson4d919432009-08-18 18:28:58 +0000893 LLVMContextImpl *pImpl = Old->getContext().pImpl;
894 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
895
Chris Lattner722272d2009-03-31 22:11:05 +0000896 assert(Entry && "Value bit set but no entries exist");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000897
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000898 // We use a local ValueHandleBase as an iterator so that
899 // ValueHandles can add and remove themselves from the list without
900 // breaking our iteration. This is not really an AssertingVH; we
901 // just have to give ValueHandleBase some kind.
902 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
903 Iterator.RemoveFromUseList();
904 Iterator.AddToExistingUseListAfter(Entry);
905 assert(Entry->Next == &Iterator && "Loop invariant broken.");
Daniel Dunbarce99a6e2009-09-20 04:03:34 +0000906
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000907 switch (Entry->getKind()) {
Chris Lattner722272d2009-03-31 22:11:05 +0000908 case Assert:
Sanjoy Das41673c62017-05-01 17:07:54 +0000909 case Weak:
910 // Asserting and Weak handles do not follow RAUW implicitly.
Chris Lattner722272d2009-03-31 22:11:05 +0000911 break;
Sanjoy Das399b4d02017-05-01 17:07:49 +0000912 case WeakTracking:
Sanjoy Das263da122017-04-26 16:37:05 +0000913 // Weak goes to the new value, which will unlink it from Old's list.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000914 Entry->operator=(New);
Chris Lattner722272d2009-03-31 22:11:05 +0000915 break;
916 case Callback:
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000917 // Forward to the subclass's implementation.
Jeffrey Yasskin6a9291a2009-10-12 17:43:32 +0000918 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
Dan Gohmanc09b12c2009-05-02 21:10:48 +0000919 break;
Chris Lattner722272d2009-03-31 22:11:05 +0000920 }
921 }
Duncan Sands2c110462010-07-27 06:53:14 +0000922
923#ifndef NDEBUG
Sanjoy Das3284bd72017-05-01 16:28:58 +0000924 // If any new weak value handles were added while processing the
Duncan Sands2c110462010-07-27 06:53:14 +0000925 // list, then complain about it now.
926 if (Old->HasValueHandle)
927 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
928 switch (Entry->getKind()) {
Sanjoy Das399b4d02017-05-01 17:07:49 +0000929 case WeakTracking:
Duncan Sands2c110462010-07-27 06:53:14 +0000930 dbgs() << "After RAUW from " << *Old->getType() << " %"
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000931 << Old->getName() << " to " << *New->getType() << " %"
932 << New->getName() << "\n";
Sanjoy Das3284bd72017-05-01 16:28:58 +0000933 llvm_unreachable(
Sanjoy Das399b4d02017-05-01 17:07:49 +0000934 "A weak tracking value handle still pointed to the old value!\n");
Duncan Sands2c110462010-07-27 06:53:14 +0000935 default:
936 break;
937 }
938#endif
Chris Lattner722272d2009-03-31 22:11:05 +0000939}
940
Juergen Ributzka35436252013-11-19 00:57:56 +0000941// Pin the vtable to this file.
942void CallbackVH::anchor() {}