xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision ec6217c9)
1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===//
2ef860a24SChandler Carruth //
3ef860a24SChandler Carruth //                     The LLVM Compiler Infrastructure
4ef860a24SChandler Carruth //
5ef860a24SChandler Carruth // This file is distributed under the University of Illinois Open Source
6ef860a24SChandler Carruth // License. See LICENSE.TXT for details.
7ef860a24SChandler Carruth //
8ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
9ef860a24SChandler Carruth //
10ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes.
11ef860a24SChandler Carruth //
12ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
13ef860a24SChandler Carruth 
149fb823bbSChandler Carruth #include "llvm/IR/Value.h"
15ef860a24SChandler Carruth #include "LLVMContextImpl.h"
16ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h"
17ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h"
18b0407ba0SHal Finkel #include "llvm/IR/CallSite.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
209fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
212e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
229fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2303eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
249fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
259fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
264b6845c7SChandler Carruth #include "llvm/IR/LeakDetector.h"
279fb823bbSChandler Carruth #include "llvm/IR/Module.h"
289fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
294220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
309fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h"
31ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
32ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
33ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
34ef860a24SChandler Carruth #include <algorithm>
35ef860a24SChandler Carruth using namespace llvm;
36ef860a24SChandler Carruth 
37ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
38ef860a24SChandler Carruth //                                Value Class
39ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
40ef860a24SChandler Carruth 
41ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
42ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
4316bf89ecSReid Kleckner   return Ty;
44ef860a24SChandler Carruth }
45ef860a24SChandler Carruth 
46ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
4716bf89ecSReid Kleckner     : VTy(checkType(ty)), UseList(nullptr), Name(nullptr), SubclassID(scid),
488d5aeb26SDuncan P. N. Exon Smith       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
498d5aeb26SDuncan P. N. Exon Smith       NumOperands(0) {
50ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
51ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
52ef860a24SChandler Carruth   // constructed.
53ef860a24SChandler Carruth   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
54ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
55ef860a24SChandler Carruth            "invalid CallInst type!");
56ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
57ef860a24SChandler Carruth            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
58ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
59ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
60ef860a24SChandler Carruth }
61ef860a24SChandler Carruth 
62ef860a24SChandler Carruth Value::~Value() {
63ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
64ef860a24SChandler Carruth   if (HasValueHandle)
65ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
66ef860a24SChandler Carruth 
67ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
68ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
69ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
70ef860a24SChandler Carruth   // reference and something is wrong.  This code is here to print out what is
71ef860a24SChandler Carruth   // still being referenced.  The value in question should be printed as
72ef860a24SChandler Carruth   // a <badref>
73ef860a24SChandler Carruth   //
74ef860a24SChandler Carruth   if (!use_empty()) {
75ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
76ef860a24SChandler Carruth     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
77ef860a24SChandler Carruth       dbgs() << "Use still stuck around after Def is destroyed:"
78ef860a24SChandler Carruth            << **I << "\n";
79ef860a24SChandler Carruth   }
80ef860a24SChandler Carruth #endif
81ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
82ef860a24SChandler Carruth 
83ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
84ef860a24SChandler Carruth   // at this point.
85ef860a24SChandler Carruth   if (Name && SubclassID != MDStringVal)
86ef860a24SChandler Carruth     Name->Destroy();
87ef860a24SChandler Carruth 
88ef860a24SChandler Carruth   // There should be no uses of this object anymore, remove it.
89ef860a24SChandler Carruth   LeakDetector::removeGarbageObject(this);
90ef860a24SChandler Carruth }
91ef860a24SChandler Carruth 
92ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
93ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
94ef860a24SChandler Carruth 
95ef860a24SChandler Carruth   for (; N; --N, ++UI)
96ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
97ef860a24SChandler Carruth   return UI == E;
98ef860a24SChandler Carruth }
99ef860a24SChandler Carruth 
100ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
101ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
102ef860a24SChandler Carruth 
103ef860a24SChandler Carruth   for (; N; --N, ++UI)
104ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
105ef860a24SChandler Carruth 
106ef860a24SChandler Carruth   return true;
107ef860a24SChandler Carruth }
108ef860a24SChandler Carruth 
109ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1100925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1110925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1120925b24dSJakob Stoklund Olesen   // usually one is quite short.
1130925b24dSJakob Stoklund Olesen   //
1140925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1150925b24dSJakob Stoklund Olesen   // search to the shorter list.
1160925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
117cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1180925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1190925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
1200925b24dSJakob Stoklund Olesen     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
121ef860a24SChandler Carruth       return true;
1220925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
1230925b24dSJakob Stoklund Olesen     const Instruction *User = dyn_cast<Instruction>(*UI);
124ef860a24SChandler Carruth     if (User && User->getParent() == BB)
125ef860a24SChandler Carruth       return true;
126ef860a24SChandler Carruth   }
127ef860a24SChandler Carruth   return false;
128ef860a24SChandler Carruth }
129ef860a24SChandler Carruth 
130ef860a24SChandler Carruth unsigned Value::getNumUses() const {
131ef860a24SChandler Carruth   return (unsigned)std::distance(use_begin(), use_end());
132ef860a24SChandler Carruth }
133ef860a24SChandler Carruth 
134ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
135c620761cSCraig Topper   ST = nullptr;
136ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
137ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
138ef860a24SChandler Carruth       if (Function *PP = P->getParent())
139ef860a24SChandler Carruth         ST = &PP->getValueSymbolTable();
140ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
141ef860a24SChandler Carruth     if (Function *P = BB->getParent())
142ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
143ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
144ef860a24SChandler Carruth     if (Module *P = GV->getParent())
145ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
146ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
147ef860a24SChandler Carruth     if (Function *P = A->getParent())
148ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
149ef860a24SChandler Carruth   } else if (isa<MDString>(V))
150ef860a24SChandler Carruth     return true;
151ef860a24SChandler Carruth   else {
152ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
153ef860a24SChandler Carruth     return true;  // no name is setable for this.
154ef860a24SChandler Carruth   }
155ef860a24SChandler Carruth   return false;
156ef860a24SChandler Carruth }
157ef860a24SChandler Carruth 
158ef860a24SChandler Carruth StringRef Value::getName() const {
159ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
160ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
161ef860a24SChandler Carruth   // terminated.
162ef860a24SChandler Carruth   if (!Name) return StringRef("", 0);
163ef860a24SChandler Carruth   return Name->getKey();
164ef860a24SChandler Carruth }
165ef860a24SChandler Carruth 
166ef860a24SChandler Carruth void Value::setName(const Twine &NewName) {
167ef860a24SChandler Carruth   assert(SubclassID != MDStringVal &&
168ef860a24SChandler Carruth          "Cannot set the name of MDString with this method!");
169ef860a24SChandler Carruth 
170ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
171ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
172ef860a24SChandler Carruth     return;
173ef860a24SChandler Carruth 
174ef860a24SChandler Carruth   SmallString<256> NameData;
175ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
17609d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
17709d689f9SRafael Espindola          "Null bytes are not allowed in names");
178ef860a24SChandler Carruth 
179ef860a24SChandler Carruth   // Name isn't changing?
180ef860a24SChandler Carruth   if (getName() == NameRef)
181ef860a24SChandler Carruth     return;
182ef860a24SChandler Carruth 
183ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
184ef860a24SChandler Carruth 
185ef860a24SChandler Carruth   // Get the symbol table to update for this object.
186ef860a24SChandler Carruth   ValueSymbolTable *ST;
187ef860a24SChandler Carruth   if (getSymTab(this, ST))
188ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
189ef860a24SChandler Carruth 
190516d7039SMichael Ilseman   if (Function *F = dyn_cast<Function>(this))
191516d7039SMichael Ilseman     getContext().pImpl->IntrinsicIDCache.erase(F);
192516d7039SMichael Ilseman 
193ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
194ef860a24SChandler Carruth     if (NameRef.empty()) {
195ef860a24SChandler Carruth       // Free the name for this value.
196ef860a24SChandler Carruth       Name->Destroy();
197c620761cSCraig Topper       Name = nullptr;
198ef860a24SChandler Carruth       return;
199ef860a24SChandler Carruth     }
200ef860a24SChandler Carruth 
201ef860a24SChandler Carruth     if (Name)
202ef860a24SChandler Carruth       Name->Destroy();
203ef860a24SChandler Carruth 
204ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
205ef860a24SChandler Carruth     // then reallocated.
206ef860a24SChandler Carruth 
207ef860a24SChandler Carruth     // Create the new name.
208213d2f79SCraig Topper     Name = ValueName::Create(NameRef);
209ef860a24SChandler Carruth     Name->setValue(this);
210ef860a24SChandler Carruth     return;
211ef860a24SChandler Carruth   }
212ef860a24SChandler Carruth 
213ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
214ef860a24SChandler Carruth   // then reallocated.
215ef860a24SChandler Carruth   if (hasName()) {
216ef860a24SChandler Carruth     // Remove old name.
217ef860a24SChandler Carruth     ST->removeValueName(Name);
218ef860a24SChandler Carruth     Name->Destroy();
219c620761cSCraig Topper     Name = nullptr;
220ef860a24SChandler Carruth 
221ef860a24SChandler Carruth     if (NameRef.empty())
222ef860a24SChandler Carruth       return;
223ef860a24SChandler Carruth   }
224ef860a24SChandler Carruth 
225ef860a24SChandler Carruth   // Name is changing to something new.
226ef860a24SChandler Carruth   Name = ST->createValueName(NameRef, this);
227ef860a24SChandler Carruth }
228ef860a24SChandler Carruth 
229ef860a24SChandler Carruth void Value::takeName(Value *V) {
230ef860a24SChandler Carruth   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
231ef860a24SChandler Carruth 
232c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
233ef860a24SChandler Carruth   // If this value has a name, drop it.
234ef860a24SChandler Carruth   if (hasName()) {
235ef860a24SChandler Carruth     // Get the symtab this is in.
236ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
237ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
238ef860a24SChandler Carruth       // it has one.
239ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
240ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
241ef860a24SChandler Carruth     }
242ef860a24SChandler Carruth 
243ef860a24SChandler Carruth     // Remove old name.
244ef860a24SChandler Carruth     if (ST)
245ef860a24SChandler Carruth       ST->removeValueName(Name);
246ef860a24SChandler Carruth     Name->Destroy();
247c620761cSCraig Topper     Name = nullptr;
248ef860a24SChandler Carruth   }
249ef860a24SChandler Carruth 
250ef860a24SChandler Carruth   // Now we know that this has no name.
251ef860a24SChandler Carruth 
252ef860a24SChandler Carruth   // If V has no name either, we're done.
253ef860a24SChandler Carruth   if (!V->hasName()) return;
254ef860a24SChandler Carruth 
255ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
256ef860a24SChandler Carruth   if (!ST) {
257ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
258ef860a24SChandler Carruth       // Clear V's name.
259ef860a24SChandler Carruth       V->setName("");
260ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
261ef860a24SChandler Carruth     }
262ef860a24SChandler Carruth   }
263ef860a24SChandler Carruth 
264ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
265ef860a24SChandler Carruth   ValueSymbolTable *VST;
266ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
267ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
268ef860a24SChandler Carruth 
269ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
270ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
271ef860a24SChandler Carruth   if (ST == VST) {
272ef860a24SChandler Carruth     // Take the name!
273ef860a24SChandler Carruth     Name = V->Name;
274c620761cSCraig Topper     V->Name = nullptr;
275ef860a24SChandler Carruth     Name->setValue(this);
276ef860a24SChandler Carruth     return;
277ef860a24SChandler Carruth   }
278ef860a24SChandler Carruth 
279ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
280ef860a24SChandler Carruth   // then reinsert it into ST.
281ef860a24SChandler Carruth 
282ef860a24SChandler Carruth   if (VST)
283ef860a24SChandler Carruth     VST->removeValueName(V->Name);
284ef860a24SChandler Carruth   Name = V->Name;
285c620761cSCraig Topper   V->Name = nullptr;
286ef860a24SChandler Carruth   Name->setValue(this);
287ef860a24SChandler Carruth 
288ef860a24SChandler Carruth   if (ST)
289ef860a24SChandler Carruth     ST->reinsertValue(this);
290ef860a24SChandler Carruth }
291ef860a24SChandler Carruth 
2927e2b7567SRafael Espindola #ifndef NDEBUG
29371b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
2947e2b7567SRafael Espindola                      Constant *C) {
29570573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
2967e2b7567SRafael Espindola     return false;
2977e2b7567SRafael Espindola 
2987e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
2997e2b7567SRafael Espindola     if (O == C)
3007e2b7567SRafael Espindola       return true;
3017e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3027e2b7567SRafael Espindola     if (!CE)
3037e2b7567SRafael Espindola       continue;
3047e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3057e2b7567SRafael Espindola       return true;
3067e2b7567SRafael Espindola   }
3077e2b7567SRafael Espindola   return false;
3087e2b7567SRafael Espindola }
3097e2b7567SRafael Espindola 
3107e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3117e2b7567SRafael Espindola   if (Expr == V)
3127e2b7567SRafael Espindola     return true;
3137e2b7567SRafael Espindola 
3147e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3157e2b7567SRafael Espindola   if (!C)
3167e2b7567SRafael Espindola     return false;
3177e2b7567SRafael Espindola 
3187e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
3197e2b7567SRafael Espindola   if (!CE)
3207e2b7567SRafael Espindola     return false;
3217e2b7567SRafael Espindola 
3227e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
3237e2b7567SRafael Espindola   return contains(Cache, CE, C);
3247e2b7567SRafael Espindola }
3257e2b7567SRafael Espindola #endif
326ef860a24SChandler Carruth 
327ef860a24SChandler Carruth void Value::replaceAllUsesWith(Value *New) {
328ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
3297e2b7567SRafael Espindola   assert(!contains(New, this) &&
3307e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
331ef860a24SChandler Carruth   assert(New->getType() == getType() &&
332ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
333ef860a24SChandler Carruth 
334ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
335ef860a24SChandler Carruth   if (HasValueHandle)
336ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   while (!use_empty()) {
339ef860a24SChandler Carruth     Use &U = *UseList;
340ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
341ef860a24SChandler Carruth     // constant because they are uniqued.
3426b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
343ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
344ef860a24SChandler Carruth         C->replaceUsesOfWithOnConstant(this, New, &U);
345ef860a24SChandler Carruth         continue;
346ef860a24SChandler Carruth       }
347ef860a24SChandler Carruth     }
348ef860a24SChandler Carruth 
349ef860a24SChandler Carruth     U.set(New);
350ef860a24SChandler Carruth   }
351ef860a24SChandler Carruth 
352ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
353ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
354ef860a24SChandler Carruth }
355ef860a24SChandler Carruth 
356*ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
357*ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
358*ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
359*ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
360*ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
361*ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
362*ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
363*ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
364*ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
365*ec6217c9SGerolf Hoflehner 
366*ec6217c9SGerolf Hoflehner   use_iterator UI = use_begin(), E = use_end();
367*ec6217c9SGerolf Hoflehner   for (; UI != E;) {
368*ec6217c9SGerolf Hoflehner     Use &U = *UI;
369*ec6217c9SGerolf Hoflehner     ++UI;
370*ec6217c9SGerolf Hoflehner     auto *Usr = dyn_cast<Instruction>(U.getUser());
371*ec6217c9SGerolf Hoflehner     if (Usr && Usr->getParent() == BB)
372*ec6217c9SGerolf Hoflehner       continue;
373*ec6217c9SGerolf Hoflehner     U.set(New);
374*ec6217c9SGerolf Hoflehner   }
375*ec6217c9SGerolf Hoflehner   return;
376*ec6217c9SGerolf Hoflehner }
377*ec6217c9SGerolf Hoflehner 
378ef860a24SChandler Carruth namespace {
379ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
380ef860a24SChandler Carruth enum PointerStripKind {
381ef860a24SChandler Carruth   PSK_ZeroIndices,
382c229a4ffSRafael Espindola   PSK_ZeroIndicesAndAliases,
383ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
384ef860a24SChandler Carruth   PSK_InBounds
385ef860a24SChandler Carruth };
386ef860a24SChandler Carruth 
387ef860a24SChandler Carruth template <PointerStripKind StripKind>
388ef860a24SChandler Carruth static Value *stripPointerCastsAndOffsets(Value *V) {
389ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
390ef860a24SChandler Carruth     return V;
391ef860a24SChandler Carruth 
392ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
393ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
394ef860a24SChandler Carruth   SmallPtrSet<Value *, 4> Visited;
395ef860a24SChandler Carruth 
396ef860a24SChandler Carruth   Visited.insert(V);
397ef860a24SChandler Carruth   do {
398ef860a24SChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
399ef860a24SChandler Carruth       switch (StripKind) {
400c229a4ffSRafael Espindola       case PSK_ZeroIndicesAndAliases:
401ef860a24SChandler Carruth       case PSK_ZeroIndices:
402ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
403ef860a24SChandler Carruth           return V;
404ef860a24SChandler Carruth         break;
405ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
406ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
407ef860a24SChandler Carruth           return V;
408ef860a24SChandler Carruth         // fallthrough
409ef860a24SChandler Carruth       case PSK_InBounds:
410ef860a24SChandler Carruth         if (!GEP->isInBounds())
411ef860a24SChandler Carruth           return V;
412ef860a24SChandler Carruth         break;
413ef860a24SChandler Carruth       }
414ef860a24SChandler Carruth       V = GEP->getPointerOperand();
415b03bd4d9SMatt Arsenault     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
416b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
417ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
418ef860a24SChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
419c229a4ffSRafael Espindola       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
420ef860a24SChandler Carruth         return V;
421ef860a24SChandler Carruth       V = GA->getAliasee();
422ef860a24SChandler Carruth     } else {
423ef860a24SChandler Carruth       return V;
424ef860a24SChandler Carruth     }
425ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
42670573dcdSDavid Blaikie   } while (Visited.insert(V).second);
427ef860a24SChandler Carruth 
428ef860a24SChandler Carruth   return V;
429ef860a24SChandler Carruth }
430ef860a24SChandler Carruth } // namespace
431ef860a24SChandler Carruth 
432ef860a24SChandler Carruth Value *Value::stripPointerCasts() {
433c229a4ffSRafael Espindola   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
434c229a4ffSRafael Espindola }
435c229a4ffSRafael Espindola 
436c229a4ffSRafael Espindola Value *Value::stripPointerCastsNoFollowAliases() {
437ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
438ef860a24SChandler Carruth }
439ef860a24SChandler Carruth 
440ef860a24SChandler Carruth Value *Value::stripInBoundsConstantOffsets() {
441ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
442ef860a24SChandler Carruth }
443ef860a24SChandler Carruth 
444989e6308SChandler Carruth Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
445989e6308SChandler Carruth                                                         APInt &Offset) {
446989e6308SChandler Carruth   if (!getType()->isPointerTy())
447989e6308SChandler Carruth     return this;
448989e6308SChandler Carruth 
449989e6308SChandler Carruth   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
450989e6308SChandler Carruth                                      getType())->getAddressSpace()) &&
451989e6308SChandler Carruth          "The offset must have exactly as many bits as our pointer.");
452989e6308SChandler Carruth 
453989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
454989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
455989e6308SChandler Carruth   SmallPtrSet<Value *, 4> Visited;
456989e6308SChandler Carruth   Visited.insert(this);
457989e6308SChandler Carruth   Value *V = this;
458989e6308SChandler Carruth   do {
459989e6308SChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
460989e6308SChandler Carruth       if (!GEP->isInBounds())
461989e6308SChandler Carruth         return V;
462ba689b33SChandler Carruth       APInt GEPOffset(Offset);
463ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
464989e6308SChandler Carruth         return V;
465ba689b33SChandler Carruth       Offset = GEPOffset;
466989e6308SChandler Carruth       V = GEP->getPointerOperand();
467b8e7c736SHal Finkel     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
468b8e7c736SHal Finkel                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
469989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
470989e6308SChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
471989e6308SChandler Carruth       V = GA->getAliasee();
472989e6308SChandler Carruth     } else {
473989e6308SChandler Carruth       return V;
474989e6308SChandler Carruth     }
475989e6308SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
47670573dcdSDavid Blaikie   } while (Visited.insert(V).second);
477989e6308SChandler Carruth 
478989e6308SChandler Carruth   return V;
479989e6308SChandler Carruth }
480989e6308SChandler Carruth 
481ef860a24SChandler Carruth Value *Value::stripInBoundsOffsets() {
482ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
483ef860a24SChandler Carruth }
484ef860a24SChandler Carruth 
485fcece4d2SDuncan P. N. Exon Smith /// \brief Check if Value is always a dereferenceable pointer.
486fcece4d2SDuncan P. N. Exon Smith ///
487fcece4d2SDuncan P. N. Exon Smith /// Test if V is always a pointer to allocated and suitably aligned memory for
488fcece4d2SDuncan P. N. Exon Smith /// a simple load or store.
4892e42c34dSHal Finkel static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
49071b7b68bSCraig Topper                                      SmallPtrSetImpl<const Value *> &Visited) {
491ef860a24SChandler Carruth   // Note that it is not safe to speculate into a malloc'd region because
492ef860a24SChandler Carruth   // malloc may return null.
493ef860a24SChandler Carruth 
494ef860a24SChandler Carruth   // These are obviously ok.
495ef860a24SChandler Carruth   if (isa<AllocaInst>(V)) return true;
496ef860a24SChandler Carruth 
4972e42c34dSHal Finkel   // It's not always safe to follow a bitcast, for example:
4982e42c34dSHal Finkel   //   bitcast i8* (alloca i8) to i32*
4992e42c34dSHal Finkel   // would result in a 4-byte load from a 1-byte alloca. However,
5002e42c34dSHal Finkel   // if we're casting from a pointer from a type of larger size
5012e42c34dSHal Finkel   // to a type of smaller size (or the same size), and the alignment
5022e42c34dSHal Finkel   // is at least as large as for the resulting pointer type, then
5032e42c34dSHal Finkel   // we can look through the bitcast.
5042e42c34dSHal Finkel   if (DL)
5052e42c34dSHal Finkel     if (const BitCastInst* BC = dyn_cast<BitCastInst>(V)) {
5062e42c34dSHal Finkel       Type *STy = BC->getSrcTy()->getPointerElementType(),
5072e42c34dSHal Finkel            *DTy = BC->getDestTy()->getPointerElementType();
50866e23f12SHal Finkel       if (STy->isSized() && DTy->isSized() &&
50966e23f12SHal Finkel           (DL->getTypeStoreSize(STy) >=
5102e42c34dSHal Finkel            DL->getTypeStoreSize(DTy)) &&
5112e42c34dSHal Finkel           (DL->getABITypeAlignment(STy) >=
5122e42c34dSHal Finkel            DL->getABITypeAlignment(DTy)))
5132e42c34dSHal Finkel         return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
5142e42c34dSHal Finkel     }
5152e42c34dSHal Finkel 
516ef860a24SChandler Carruth   // Global variables which can't collapse to null are ok.
517ef860a24SChandler Carruth   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
518ef860a24SChandler Carruth     return !GV->hasExternalWeakLinkage();
519ef860a24SChandler Carruth 
520b0407ba0SHal Finkel   // byval arguments are okay. Arguments specifically marked as
521b0407ba0SHal Finkel   // dereferenceable are okay too.
522b0407ba0SHal Finkel   if (const Argument *A = dyn_cast<Argument>(V)) {
523b0407ba0SHal Finkel     if (A->hasByValAttr())
524b0407ba0SHal Finkel       return true;
525b0407ba0SHal Finkel     else if (uint64_t Bytes = A->getDereferenceableBytes()) {
526b0407ba0SHal Finkel       Type *Ty = V->getType()->getPointerElementType();
527b0407ba0SHal Finkel       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
528b0407ba0SHal Finkel         return true;
529b0407ba0SHal Finkel     }
530b0407ba0SHal Finkel 
531b0407ba0SHal Finkel     return false;
532b0407ba0SHal Finkel   }
533b0407ba0SHal Finkel 
534b0407ba0SHal Finkel   // Return values from call sites specifically marked as dereferenceable are
535b0407ba0SHal Finkel   // also okay.
536b0407ba0SHal Finkel   if (ImmutableCallSite CS = V) {
537b0407ba0SHal Finkel     if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
538b0407ba0SHal Finkel       Type *Ty = V->getType()->getPointerElementType();
539b0407ba0SHal Finkel       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
540b0407ba0SHal Finkel         return true;
541b0407ba0SHal Finkel     }
542b0407ba0SHal Finkel   }
543ef860a24SChandler Carruth 
544ef860a24SChandler Carruth   // For GEPs, determine if the indexing lands within the allocated object.
545ef860a24SChandler Carruth   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
546ef860a24SChandler Carruth     // Conservatively require that the base pointer be fully dereferenceable.
54770573dcdSDavid Blaikie     if (!Visited.insert(GEP->getOperand(0)).second)
548ef860a24SChandler Carruth       return false;
5492e42c34dSHal Finkel     if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
550ef860a24SChandler Carruth       return false;
551ef860a24SChandler Carruth     // Check the indices.
552ef860a24SChandler Carruth     gep_type_iterator GTI = gep_type_begin(GEP);
553ef860a24SChandler Carruth     for (User::const_op_iterator I = GEP->op_begin()+1,
554ef860a24SChandler Carruth          E = GEP->op_end(); I != E; ++I) {
555ef860a24SChandler Carruth       Value *Index = *I;
556ef860a24SChandler Carruth       Type *Ty = *GTI++;
557ef860a24SChandler Carruth       // Struct indices can't be out of bounds.
558ef860a24SChandler Carruth       if (isa<StructType>(Ty))
559ef860a24SChandler Carruth         continue;
560ef860a24SChandler Carruth       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
561ef860a24SChandler Carruth       if (!CI)
562ef860a24SChandler Carruth         return false;
563ef860a24SChandler Carruth       // Zero is always ok.
564ef860a24SChandler Carruth       if (CI->isZero())
565ef860a24SChandler Carruth         continue;
566ef860a24SChandler Carruth       // Check to see that it's within the bounds of an array.
567ef860a24SChandler Carruth       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
568ef860a24SChandler Carruth       if (!ATy)
569ef860a24SChandler Carruth         return false;
570ef860a24SChandler Carruth       if (CI->getValue().getActiveBits() > 64)
571ef860a24SChandler Carruth         return false;
572ef860a24SChandler Carruth       if (CI->getZExtValue() >= ATy->getNumElements())
573ef860a24SChandler Carruth         return false;
574ef860a24SChandler Carruth     }
575ef860a24SChandler Carruth     // Indices check out; this is dereferenceable.
576ef860a24SChandler Carruth     return true;
577ef860a24SChandler Carruth   }
578ef860a24SChandler Carruth 
579199b39e0SMatt Arsenault   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
580199b39e0SMatt Arsenault     return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
581199b39e0SMatt Arsenault 
582ef860a24SChandler Carruth   // If we don't know, assume the worst.
583ef860a24SChandler Carruth   return false;
584ef860a24SChandler Carruth }
585ef860a24SChandler Carruth 
5862e42c34dSHal Finkel bool Value::isDereferenceablePointer(const DataLayout *DL) const {
5879e440c08SHal Finkel   // When dereferenceability information is provided by a dereferenceable
5889e440c08SHal Finkel   // attribute, we know exactly how many bytes are dereferenceable. If we can
5899e440c08SHal Finkel   // determine the exact offset to the attributed variable, we can use that
5909e440c08SHal Finkel   // information here.
5919e440c08SHal Finkel   Type *Ty = getType()->getPointerElementType();
5929e440c08SHal Finkel   if (Ty->isSized() && DL) {
5939e440c08SHal Finkel     APInt Offset(DL->getTypeStoreSizeInBits(getType()), 0);
5949e440c08SHal Finkel     const Value *BV = stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
5959e440c08SHal Finkel 
5969e440c08SHal Finkel     APInt DerefBytes(Offset.getBitWidth(), 0);
5979e440c08SHal Finkel     if (const Argument *A = dyn_cast<Argument>(BV))
5989e440c08SHal Finkel       DerefBytes = A->getDereferenceableBytes();
5999e440c08SHal Finkel     else if (ImmutableCallSite CS = BV)
6009e440c08SHal Finkel       DerefBytes = CS.getDereferenceableBytes(0);
6019e440c08SHal Finkel 
6029e440c08SHal Finkel     if (DerefBytes.getBoolValue() && Offset.isNonNegative()) {
6039e440c08SHal Finkel       if (DerefBytes.uge(Offset + DL->getTypeStoreSize(Ty)))
6049e440c08SHal Finkel         return true;
6059e440c08SHal Finkel     }
6069e440c08SHal Finkel   }
6079e440c08SHal Finkel 
608ef860a24SChandler Carruth   SmallPtrSet<const Value *, 32> Visited;
6092e42c34dSHal Finkel   return ::isDereferenceablePointer(this, DL, Visited);
610ef860a24SChandler Carruth }
611ef860a24SChandler Carruth 
612ef860a24SChandler Carruth Value *Value::DoPHITranslation(const BasicBlock *CurBB,
613ef860a24SChandler Carruth                                const BasicBlock *PredBB) {
614ef860a24SChandler Carruth   PHINode *PN = dyn_cast<PHINode>(this);
615ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
616ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
617ef860a24SChandler Carruth   return this;
618ef860a24SChandler Carruth }
619ef860a24SChandler Carruth 
620ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
621ef860a24SChandler Carruth 
6223441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
6233441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
6243441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
6253441ffe9SDuncan P. N. Exon Smith     return;
6263441ffe9SDuncan P. N. Exon Smith 
6273441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
6283441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
6293441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
6303441ffe9SDuncan P. N. Exon Smith   while (Current) {
6313441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
6323441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
6333441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
6343441ffe9SDuncan P. N. Exon Smith     Head = Current;
6353441ffe9SDuncan P. N. Exon Smith     Current = Next;
6363441ffe9SDuncan P. N. Exon Smith   }
6373441ffe9SDuncan P. N. Exon Smith   UseList = Head;
6383441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
6393441ffe9SDuncan P. N. Exon Smith }
6403441ffe9SDuncan P. N. Exon Smith 
641ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
642ef860a24SChandler Carruth //                             ValueHandleBase Class
643ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
644ef860a24SChandler Carruth 
645ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
646ef860a24SChandler Carruth   assert(List && "Handle list is null?");
647ef860a24SChandler Carruth 
648ef860a24SChandler Carruth   // Splice ourselves into the list.
649ef860a24SChandler Carruth   Next = *List;
650ef860a24SChandler Carruth   *List = this;
651ef860a24SChandler Carruth   setPrevPtr(List);
652ef860a24SChandler Carruth   if (Next) {
653ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
654ef860a24SChandler Carruth     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
655ef860a24SChandler Carruth   }
656ef860a24SChandler Carruth }
657ef860a24SChandler Carruth 
658ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
659ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
660ef860a24SChandler Carruth 
661ef860a24SChandler Carruth   Next = List->Next;
662ef860a24SChandler Carruth   setPrevPtr(&List->Next);
663ef860a24SChandler Carruth   List->Next = this;
664ef860a24SChandler Carruth   if (Next)
665ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
666ef860a24SChandler Carruth }
667ef860a24SChandler Carruth 
668ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
669ef860a24SChandler Carruth   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
670ef860a24SChandler Carruth 
671ef860a24SChandler Carruth   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
672ef860a24SChandler Carruth 
673ef860a24SChandler Carruth   if (VP.getPointer()->HasValueHandle) {
674ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
675ef860a24SChandler Carruth     // ValueHandles map already.
676ef860a24SChandler Carruth     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
6772617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
678ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
679ef860a24SChandler Carruth     return;
680ef860a24SChandler Carruth   }
681ef860a24SChandler Carruth 
682ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
683ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
684ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
685ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
686ef860a24SChandler Carruth   // updating the stale pointers only if needed.
687ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
688ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
689ef860a24SChandler Carruth 
690ef860a24SChandler Carruth   ValueHandleBase *&Entry = Handles[VP.getPointer()];
6912617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
692ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
693ef860a24SChandler Carruth   VP.getPointer()->HasValueHandle = true;
694ef860a24SChandler Carruth 
695ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
696ef860a24SChandler Carruth   // walk the table.
697ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
698ef860a24SChandler Carruth       Handles.size() == 1) {
699ef860a24SChandler Carruth     return;
700ef860a24SChandler Carruth   }
701ef860a24SChandler Carruth 
702ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
703ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
704ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
705ef860a24SChandler Carruth     assert(I->second && I->first == I->second->VP.getPointer() &&
706ef860a24SChandler Carruth            "List invariant broken!");
707ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
708ef860a24SChandler Carruth   }
709ef860a24SChandler Carruth }
710ef860a24SChandler Carruth 
711ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
712ef860a24SChandler Carruth   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
713ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
714ef860a24SChandler Carruth 
715ef860a24SChandler Carruth   // Unlink this from its use list.
716ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
717ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
718ef860a24SChandler Carruth 
719ef860a24SChandler Carruth   *PrevPtr = Next;
720ef860a24SChandler Carruth   if (Next) {
721ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
722ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
723ef860a24SChandler Carruth     return;
724ef860a24SChandler Carruth   }
725ef860a24SChandler Carruth 
726ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
727ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
728ef860a24SChandler Carruth   // map.
729ef860a24SChandler Carruth   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
730ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
731ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
732ef860a24SChandler Carruth     Handles.erase(VP.getPointer());
733ef860a24SChandler Carruth     VP.getPointer()->HasValueHandle = false;
734ef860a24SChandler Carruth   }
735ef860a24SChandler Carruth }
736ef860a24SChandler Carruth 
737ef860a24SChandler Carruth 
738ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
739ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
740ef860a24SChandler Carruth 
741ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
742ef860a24SChandler Carruth   // HasValueHandle flag is set.
743ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
744ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
745ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
746ef860a24SChandler Carruth 
747ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
748ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
749ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
750ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
751ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
752ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
753ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
754ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
755ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
756ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
757ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
758ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
759ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
760ef860a24SChandler Carruth 
761ef860a24SChandler Carruth     switch (Entry->getKind()) {
762ef860a24SChandler Carruth     case Assert:
763ef860a24SChandler Carruth       break;
764ef860a24SChandler Carruth     case Tracking:
765ef860a24SChandler Carruth       // Mark that this value has been deleted by setting it to an invalid Value
766ef860a24SChandler Carruth       // pointer.
767ef860a24SChandler Carruth       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
768ef860a24SChandler Carruth       break;
769ef860a24SChandler Carruth     case Weak:
770ef860a24SChandler Carruth       // Weak just goes to null, which will unlink it from the list.
771c620761cSCraig Topper       Entry->operator=(nullptr);
772ef860a24SChandler Carruth       break;
773ef860a24SChandler Carruth     case Callback:
774ef860a24SChandler Carruth       // Forward to the subclass's implementation.
775ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
776ef860a24SChandler Carruth       break;
777ef860a24SChandler Carruth     }
778ef860a24SChandler Carruth   }
779ef860a24SChandler Carruth 
780ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
781ef860a24SChandler Carruth   if (V->HasValueHandle) {
782ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
783ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
784ef860a24SChandler Carruth            << "\n";
785ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
786ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
787ef860a24SChandler Carruth                        " value!");
788ef860a24SChandler Carruth 
789ef860a24SChandler Carruth #endif
790ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
791ef860a24SChandler Carruth   }
792ef860a24SChandler Carruth }
793ef860a24SChandler Carruth 
794ef860a24SChandler Carruth 
795ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
796ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
797ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
798c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
799c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
800ef860a24SChandler Carruth 
801ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
802ef860a24SChandler Carruth   // HasValueHandle flag is set.
803ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
804ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
805ef860a24SChandler Carruth 
806ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
807ef860a24SChandler Carruth 
808ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
809ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
810ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
811ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
812ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
813ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
814ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
815ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
816ef860a24SChandler Carruth 
817ef860a24SChandler Carruth     switch (Entry->getKind()) {
818ef860a24SChandler Carruth     case Assert:
819ef860a24SChandler Carruth       // Asserting handle does not follow RAUW implicitly.
820ef860a24SChandler Carruth       break;
821ef860a24SChandler Carruth     case Tracking:
822ef860a24SChandler Carruth       // Tracking goes to new value like a WeakVH. Note that this may make it
823ef860a24SChandler Carruth       // something incompatible with its templated type. We don't want to have a
824ef860a24SChandler Carruth       // virtual (or inline) interface to handle this though, so instead we make
825ef860a24SChandler Carruth       // the TrackingVH accessors guarantee that a client never sees this value.
826ef860a24SChandler Carruth 
827ef860a24SChandler Carruth       // FALLTHROUGH
828ef860a24SChandler Carruth     case Weak:
829ef860a24SChandler Carruth       // Weak goes to the new value, which will unlink it from Old's list.
830ef860a24SChandler Carruth       Entry->operator=(New);
831ef860a24SChandler Carruth       break;
832ef860a24SChandler Carruth     case Callback:
833ef860a24SChandler Carruth       // Forward to the subclass's implementation.
834ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
835ef860a24SChandler Carruth       break;
836ef860a24SChandler Carruth     }
837ef860a24SChandler Carruth   }
838ef860a24SChandler Carruth 
839ef860a24SChandler Carruth #ifndef NDEBUG
840ef860a24SChandler Carruth   // If any new tracking or weak value handles were added while processing the
841ef860a24SChandler Carruth   // list, then complain about it now.
842ef860a24SChandler Carruth   if (Old->HasValueHandle)
843ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
844ef860a24SChandler Carruth       switch (Entry->getKind()) {
845ef860a24SChandler Carruth       case Tracking:
846ef860a24SChandler Carruth       case Weak:
847ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
848ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
849ef860a24SChandler Carruth                << New->getName() << "\n";
850ef860a24SChandler Carruth         llvm_unreachable("A tracking or weak value handle still pointed to the"
851ef860a24SChandler Carruth                          " old value!\n");
852ef860a24SChandler Carruth       default:
853ef860a24SChandler Carruth         break;
854ef860a24SChandler Carruth       }
855ef860a24SChandler Carruth #endif
856ef860a24SChandler Carruth }
857ef860a24SChandler Carruth 
858d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
859d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
860