xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision b0407ba0)
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"
18*b0407ba0SHal 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),
4816bf89ecSReid Kleckner       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0) {
49ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
50ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
51ef860a24SChandler Carruth   // constructed.
52ef860a24SChandler Carruth   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
53ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
54ef860a24SChandler Carruth            "invalid CallInst type!");
55ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
56ef860a24SChandler Carruth            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
57ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
58ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
59ef860a24SChandler Carruth }
60ef860a24SChandler Carruth 
61ef860a24SChandler Carruth Value::~Value() {
62ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
63ef860a24SChandler Carruth   if (HasValueHandle)
64ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
65ef860a24SChandler Carruth 
66ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
67ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
68ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
69ef860a24SChandler Carruth   // reference and something is wrong.  This code is here to print out what is
70ef860a24SChandler Carruth   // still being referenced.  The value in question should be printed as
71ef860a24SChandler Carruth   // a <badref>
72ef860a24SChandler Carruth   //
73ef860a24SChandler Carruth   if (!use_empty()) {
74ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
75ef860a24SChandler Carruth     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
76ef860a24SChandler Carruth       dbgs() << "Use still stuck around after Def is destroyed:"
77ef860a24SChandler Carruth            << **I << "\n";
78ef860a24SChandler Carruth   }
79ef860a24SChandler Carruth #endif
80ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
81ef860a24SChandler Carruth 
82ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
83ef860a24SChandler Carruth   // at this point.
84ef860a24SChandler Carruth   if (Name && SubclassID != MDStringVal)
85ef860a24SChandler Carruth     Name->Destroy();
86ef860a24SChandler Carruth 
87ef860a24SChandler Carruth   // There should be no uses of this object anymore, remove it.
88ef860a24SChandler Carruth   LeakDetector::removeGarbageObject(this);
89ef860a24SChandler Carruth }
90ef860a24SChandler Carruth 
91ef860a24SChandler Carruth /// hasNUses - Return true if this Value has exactly N users.
92ef860a24SChandler Carruth ///
93ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
94ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
95ef860a24SChandler Carruth 
96ef860a24SChandler Carruth   for (; N; --N, ++UI)
97ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
98ef860a24SChandler Carruth   return UI == E;
99ef860a24SChandler Carruth }
100ef860a24SChandler Carruth 
101ef860a24SChandler Carruth /// hasNUsesOrMore - Return true if this value has N users or more.  This is
102ef860a24SChandler Carruth /// logically equivalent to getNumUses() >= N.
103ef860a24SChandler Carruth ///
104ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
105ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
106ef860a24SChandler Carruth 
107ef860a24SChandler Carruth   for (; N; --N, ++UI)
108ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
109ef860a24SChandler Carruth 
110ef860a24SChandler Carruth   return true;
111ef860a24SChandler Carruth }
112ef860a24SChandler Carruth 
113ef860a24SChandler Carruth /// isUsedInBasicBlock - Return true if this value is used in the specified
114ef860a24SChandler Carruth /// basic block.
115ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1160925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1170925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1180925b24dSJakob Stoklund Olesen   // usually one is quite short.
1190925b24dSJakob Stoklund Olesen   //
1200925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1210925b24dSJakob Stoklund Olesen   // search to the shorter list.
1220925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
123cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1240925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1250925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
1260925b24dSJakob Stoklund Olesen     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
127ef860a24SChandler Carruth       return true;
1280925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
1290925b24dSJakob Stoklund Olesen     const Instruction *User = dyn_cast<Instruction>(*UI);
130ef860a24SChandler Carruth     if (User && User->getParent() == BB)
131ef860a24SChandler Carruth       return true;
132ef860a24SChandler Carruth   }
133ef860a24SChandler Carruth   return false;
134ef860a24SChandler Carruth }
135ef860a24SChandler Carruth 
136ef860a24SChandler Carruth 
137ef860a24SChandler Carruth /// getNumUses - This method computes the number of uses of this Value.  This
138ef860a24SChandler Carruth /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
139ef860a24SChandler Carruth /// values.
140ef860a24SChandler Carruth unsigned Value::getNumUses() const {
141ef860a24SChandler Carruth   return (unsigned)std::distance(use_begin(), use_end());
142ef860a24SChandler Carruth }
143ef860a24SChandler Carruth 
144ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
145c620761cSCraig Topper   ST = nullptr;
146ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
147ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
148ef860a24SChandler Carruth       if (Function *PP = P->getParent())
149ef860a24SChandler Carruth         ST = &PP->getValueSymbolTable();
150ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
151ef860a24SChandler Carruth     if (Function *P = BB->getParent())
152ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
153ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
154ef860a24SChandler Carruth     if (Module *P = GV->getParent())
155ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
156ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
157ef860a24SChandler Carruth     if (Function *P = A->getParent())
158ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
159ef860a24SChandler Carruth   } else if (isa<MDString>(V))
160ef860a24SChandler Carruth     return true;
161ef860a24SChandler Carruth   else {
162ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
163ef860a24SChandler Carruth     return true;  // no name is setable for this.
164ef860a24SChandler Carruth   }
165ef860a24SChandler Carruth   return false;
166ef860a24SChandler Carruth }
167ef860a24SChandler Carruth 
168ef860a24SChandler Carruth StringRef Value::getName() const {
169ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
170ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
171ef860a24SChandler Carruth   // terminated.
172ef860a24SChandler Carruth   if (!Name) return StringRef("", 0);
173ef860a24SChandler Carruth   return Name->getKey();
174ef860a24SChandler Carruth }
175ef860a24SChandler Carruth 
176ef860a24SChandler Carruth void Value::setName(const Twine &NewName) {
177ef860a24SChandler Carruth   assert(SubclassID != MDStringVal &&
178ef860a24SChandler Carruth          "Cannot set the name of MDString with this method!");
179ef860a24SChandler Carruth 
180ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
181ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
182ef860a24SChandler Carruth     return;
183ef860a24SChandler Carruth 
184ef860a24SChandler Carruth   SmallString<256> NameData;
185ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
18609d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
18709d689f9SRafael Espindola          "Null bytes are not allowed in names");
188ef860a24SChandler Carruth 
189ef860a24SChandler Carruth   // Name isn't changing?
190ef860a24SChandler Carruth   if (getName() == NameRef)
191ef860a24SChandler Carruth     return;
192ef860a24SChandler Carruth 
193ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
194ef860a24SChandler Carruth 
195ef860a24SChandler Carruth   // Get the symbol table to update for this object.
196ef860a24SChandler Carruth   ValueSymbolTable *ST;
197ef860a24SChandler Carruth   if (getSymTab(this, ST))
198ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
199ef860a24SChandler Carruth 
200516d7039SMichael Ilseman   if (Function *F = dyn_cast<Function>(this))
201516d7039SMichael Ilseman     getContext().pImpl->IntrinsicIDCache.erase(F);
202516d7039SMichael Ilseman 
203ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
204ef860a24SChandler Carruth     if (NameRef.empty()) {
205ef860a24SChandler Carruth       // Free the name for this value.
206ef860a24SChandler Carruth       Name->Destroy();
207c620761cSCraig Topper       Name = nullptr;
208ef860a24SChandler Carruth       return;
209ef860a24SChandler Carruth     }
210ef860a24SChandler Carruth 
211ef860a24SChandler Carruth     if (Name)
212ef860a24SChandler Carruth       Name->Destroy();
213ef860a24SChandler Carruth 
214ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
215ef860a24SChandler Carruth     // then reallocated.
216ef860a24SChandler Carruth 
217ef860a24SChandler Carruth     // Create the new name.
218213d2f79SCraig Topper     Name = ValueName::Create(NameRef);
219ef860a24SChandler Carruth     Name->setValue(this);
220ef860a24SChandler Carruth     return;
221ef860a24SChandler Carruth   }
222ef860a24SChandler Carruth 
223ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
224ef860a24SChandler Carruth   // then reallocated.
225ef860a24SChandler Carruth   if (hasName()) {
226ef860a24SChandler Carruth     // Remove old name.
227ef860a24SChandler Carruth     ST->removeValueName(Name);
228ef860a24SChandler Carruth     Name->Destroy();
229c620761cSCraig Topper     Name = nullptr;
230ef860a24SChandler Carruth 
231ef860a24SChandler Carruth     if (NameRef.empty())
232ef860a24SChandler Carruth       return;
233ef860a24SChandler Carruth   }
234ef860a24SChandler Carruth 
235ef860a24SChandler Carruth   // Name is changing to something new.
236ef860a24SChandler Carruth   Name = ST->createValueName(NameRef, this);
237ef860a24SChandler Carruth }
238ef860a24SChandler Carruth 
239ef860a24SChandler Carruth 
240ef860a24SChandler Carruth /// takeName - transfer the name from V to this value, setting V's name to
241ef860a24SChandler Carruth /// empty.  It is an error to call V->takeName(V).
242ef860a24SChandler Carruth void Value::takeName(Value *V) {
243ef860a24SChandler Carruth   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
244ef860a24SChandler Carruth 
245c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
246ef860a24SChandler Carruth   // If this value has a name, drop it.
247ef860a24SChandler Carruth   if (hasName()) {
248ef860a24SChandler Carruth     // Get the symtab this is in.
249ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
250ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
251ef860a24SChandler Carruth       // it has one.
252ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
253ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
254ef860a24SChandler Carruth     }
255ef860a24SChandler Carruth 
256ef860a24SChandler Carruth     // Remove old name.
257ef860a24SChandler Carruth     if (ST)
258ef860a24SChandler Carruth       ST->removeValueName(Name);
259ef860a24SChandler Carruth     Name->Destroy();
260c620761cSCraig Topper     Name = nullptr;
261ef860a24SChandler Carruth   }
262ef860a24SChandler Carruth 
263ef860a24SChandler Carruth   // Now we know that this has no name.
264ef860a24SChandler Carruth 
265ef860a24SChandler Carruth   // If V has no name either, we're done.
266ef860a24SChandler Carruth   if (!V->hasName()) return;
267ef860a24SChandler Carruth 
268ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
269ef860a24SChandler Carruth   if (!ST) {
270ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
271ef860a24SChandler Carruth       // Clear V's name.
272ef860a24SChandler Carruth       V->setName("");
273ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
274ef860a24SChandler Carruth     }
275ef860a24SChandler Carruth   }
276ef860a24SChandler Carruth 
277ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
278ef860a24SChandler Carruth   ValueSymbolTable *VST;
279ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
280ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
281ef860a24SChandler Carruth 
282ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
283ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
284ef860a24SChandler Carruth   if (ST == VST) {
285ef860a24SChandler Carruth     // Take the name!
286ef860a24SChandler Carruth     Name = V->Name;
287c620761cSCraig Topper     V->Name = nullptr;
288ef860a24SChandler Carruth     Name->setValue(this);
289ef860a24SChandler Carruth     return;
290ef860a24SChandler Carruth   }
291ef860a24SChandler Carruth 
292ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
293ef860a24SChandler Carruth   // then reinsert it into ST.
294ef860a24SChandler Carruth 
295ef860a24SChandler Carruth   if (VST)
296ef860a24SChandler Carruth     VST->removeValueName(V->Name);
297ef860a24SChandler Carruth   Name = V->Name;
298c620761cSCraig Topper   V->Name = nullptr;
299ef860a24SChandler Carruth   Name->setValue(this);
300ef860a24SChandler Carruth 
301ef860a24SChandler Carruth   if (ST)
302ef860a24SChandler Carruth     ST->reinsertValue(this);
303ef860a24SChandler Carruth }
304ef860a24SChandler Carruth 
3057e2b7567SRafael Espindola #ifndef NDEBUG
3067e2b7567SRafael Espindola static bool contains(SmallPtrSet<ConstantExpr *, 4> &Cache, ConstantExpr *Expr,
3077e2b7567SRafael Espindola                      Constant *C) {
3087e2b7567SRafael Espindola   if (!Cache.insert(Expr))
3097e2b7567SRafael Espindola     return false;
3107e2b7567SRafael Espindola 
3117e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
3127e2b7567SRafael Espindola     if (O == C)
3137e2b7567SRafael Espindola       return true;
3147e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3157e2b7567SRafael Espindola     if (!CE)
3167e2b7567SRafael Espindola       continue;
3177e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3187e2b7567SRafael Espindola       return true;
3197e2b7567SRafael Espindola   }
3207e2b7567SRafael Espindola   return false;
3217e2b7567SRafael Espindola }
3227e2b7567SRafael Espindola 
3237e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3247e2b7567SRafael Espindola   if (Expr == V)
3257e2b7567SRafael Espindola     return true;
3267e2b7567SRafael Espindola 
3277e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3287e2b7567SRafael Espindola   if (!C)
3297e2b7567SRafael Espindola     return false;
3307e2b7567SRafael Espindola 
3317e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
3327e2b7567SRafael Espindola   if (!CE)
3337e2b7567SRafael Espindola     return false;
3347e2b7567SRafael Espindola 
3357e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
3367e2b7567SRafael Espindola   return contains(Cache, CE, C);
3377e2b7567SRafael Espindola }
3387e2b7567SRafael Espindola #endif
339ef860a24SChandler Carruth 
340ef860a24SChandler Carruth void Value::replaceAllUsesWith(Value *New) {
341ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
3427e2b7567SRafael Espindola   assert(!contains(New, this) &&
3437e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
344ef860a24SChandler Carruth   assert(New->getType() == getType() &&
345ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
346ef860a24SChandler Carruth 
347ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
348ef860a24SChandler Carruth   if (HasValueHandle)
349ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
350ef860a24SChandler Carruth 
351ef860a24SChandler Carruth   while (!use_empty()) {
352ef860a24SChandler Carruth     Use &U = *UseList;
353ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
354ef860a24SChandler Carruth     // constant because they are uniqued.
3556b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
356ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
357ef860a24SChandler Carruth         C->replaceUsesOfWithOnConstant(this, New, &U);
358ef860a24SChandler Carruth         continue;
359ef860a24SChandler Carruth       }
360ef860a24SChandler Carruth     }
361ef860a24SChandler Carruth 
362ef860a24SChandler Carruth     U.set(New);
363ef860a24SChandler Carruth   }
364ef860a24SChandler Carruth 
365ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
366ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
367ef860a24SChandler Carruth }
368ef860a24SChandler Carruth 
369ef860a24SChandler Carruth namespace {
370ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
371ef860a24SChandler Carruth enum PointerStripKind {
372ef860a24SChandler Carruth   PSK_ZeroIndices,
373c229a4ffSRafael Espindola   PSK_ZeroIndicesAndAliases,
374ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
375ef860a24SChandler Carruth   PSK_InBounds
376ef860a24SChandler Carruth };
377ef860a24SChandler Carruth 
378ef860a24SChandler Carruth template <PointerStripKind StripKind>
379ef860a24SChandler Carruth static Value *stripPointerCastsAndOffsets(Value *V) {
380ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
381ef860a24SChandler Carruth     return V;
382ef860a24SChandler Carruth 
383ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
384ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
385ef860a24SChandler Carruth   SmallPtrSet<Value *, 4> Visited;
386ef860a24SChandler Carruth 
387ef860a24SChandler Carruth   Visited.insert(V);
388ef860a24SChandler Carruth   do {
389ef860a24SChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
390ef860a24SChandler Carruth       switch (StripKind) {
391c229a4ffSRafael Espindola       case PSK_ZeroIndicesAndAliases:
392ef860a24SChandler Carruth       case PSK_ZeroIndices:
393ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
394ef860a24SChandler Carruth           return V;
395ef860a24SChandler Carruth         break;
396ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
397ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
398ef860a24SChandler Carruth           return V;
399ef860a24SChandler Carruth         // fallthrough
400ef860a24SChandler Carruth       case PSK_InBounds:
401ef860a24SChandler Carruth         if (!GEP->isInBounds())
402ef860a24SChandler Carruth           return V;
403ef860a24SChandler Carruth         break;
404ef860a24SChandler Carruth       }
405ef860a24SChandler Carruth       V = GEP->getPointerOperand();
406b03bd4d9SMatt Arsenault     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
407b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
408ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
409ef860a24SChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
410c229a4ffSRafael Espindola       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
411ef860a24SChandler Carruth         return V;
412ef860a24SChandler Carruth       V = GA->getAliasee();
413ef860a24SChandler Carruth     } else {
414ef860a24SChandler Carruth       return V;
415ef860a24SChandler Carruth     }
416ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
417ef860a24SChandler Carruth   } while (Visited.insert(V));
418ef860a24SChandler Carruth 
419ef860a24SChandler Carruth   return V;
420ef860a24SChandler Carruth }
421ef860a24SChandler Carruth } // namespace
422ef860a24SChandler Carruth 
423ef860a24SChandler Carruth Value *Value::stripPointerCasts() {
424c229a4ffSRafael Espindola   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
425c229a4ffSRafael Espindola }
426c229a4ffSRafael Espindola 
427c229a4ffSRafael Espindola Value *Value::stripPointerCastsNoFollowAliases() {
428ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
429ef860a24SChandler Carruth }
430ef860a24SChandler Carruth 
431ef860a24SChandler Carruth Value *Value::stripInBoundsConstantOffsets() {
432ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
433ef860a24SChandler Carruth }
434ef860a24SChandler Carruth 
435989e6308SChandler Carruth Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
436989e6308SChandler Carruth                                                         APInt &Offset) {
437989e6308SChandler Carruth   if (!getType()->isPointerTy())
438989e6308SChandler Carruth     return this;
439989e6308SChandler Carruth 
440989e6308SChandler Carruth   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
441989e6308SChandler Carruth                                      getType())->getAddressSpace()) &&
442989e6308SChandler Carruth          "The offset must have exactly as many bits as our pointer.");
443989e6308SChandler Carruth 
444989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
445989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
446989e6308SChandler Carruth   SmallPtrSet<Value *, 4> Visited;
447989e6308SChandler Carruth   Visited.insert(this);
448989e6308SChandler Carruth   Value *V = this;
449989e6308SChandler Carruth   do {
450989e6308SChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
451989e6308SChandler Carruth       if (!GEP->isInBounds())
452989e6308SChandler Carruth         return V;
453ba689b33SChandler Carruth       APInt GEPOffset(Offset);
454ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
455989e6308SChandler Carruth         return V;
456ba689b33SChandler Carruth       Offset = GEPOffset;
457989e6308SChandler Carruth       V = GEP->getPointerOperand();
458989e6308SChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
459989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
460989e6308SChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
461989e6308SChandler Carruth       V = GA->getAliasee();
462989e6308SChandler Carruth     } else {
463989e6308SChandler Carruth       return V;
464989e6308SChandler Carruth     }
465989e6308SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
466989e6308SChandler Carruth   } while (Visited.insert(V));
467989e6308SChandler Carruth 
468989e6308SChandler Carruth   return V;
469989e6308SChandler Carruth }
470989e6308SChandler Carruth 
471ef860a24SChandler Carruth Value *Value::stripInBoundsOffsets() {
472ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
473ef860a24SChandler Carruth }
474ef860a24SChandler Carruth 
475ef860a24SChandler Carruth /// isDereferenceablePointer - Test if this value is always a pointer to
476ef860a24SChandler Carruth /// allocated and suitably aligned memory for a simple load or store.
4772e42c34dSHal Finkel static bool isDereferenceablePointer(const Value *V, const DataLayout *DL,
478ef860a24SChandler Carruth                                      SmallPtrSet<const Value *, 32> &Visited) {
479ef860a24SChandler Carruth   // Note that it is not safe to speculate into a malloc'd region because
480ef860a24SChandler Carruth   // malloc may return null.
481ef860a24SChandler Carruth 
482ef860a24SChandler Carruth   // These are obviously ok.
483ef860a24SChandler Carruth   if (isa<AllocaInst>(V)) return true;
484ef860a24SChandler Carruth 
4852e42c34dSHal Finkel   // It's not always safe to follow a bitcast, for example:
4862e42c34dSHal Finkel   //   bitcast i8* (alloca i8) to i32*
4872e42c34dSHal Finkel   // would result in a 4-byte load from a 1-byte alloca. However,
4882e42c34dSHal Finkel   // if we're casting from a pointer from a type of larger size
4892e42c34dSHal Finkel   // to a type of smaller size (or the same size), and the alignment
4902e42c34dSHal Finkel   // is at least as large as for the resulting pointer type, then
4912e42c34dSHal Finkel   // we can look through the bitcast.
4922e42c34dSHal Finkel   if (DL)
4932e42c34dSHal Finkel     if (const BitCastInst* BC = dyn_cast<BitCastInst>(V)) {
4942e42c34dSHal Finkel       Type *STy = BC->getSrcTy()->getPointerElementType(),
4952e42c34dSHal Finkel            *DTy = BC->getDestTy()->getPointerElementType();
49666e23f12SHal Finkel       if (STy->isSized() && DTy->isSized() &&
49766e23f12SHal Finkel           (DL->getTypeStoreSize(STy) >=
4982e42c34dSHal Finkel            DL->getTypeStoreSize(DTy)) &&
4992e42c34dSHal Finkel           (DL->getABITypeAlignment(STy) >=
5002e42c34dSHal Finkel            DL->getABITypeAlignment(DTy)))
5012e42c34dSHal Finkel         return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
5022e42c34dSHal Finkel     }
5032e42c34dSHal Finkel 
504ef860a24SChandler Carruth   // Global variables which can't collapse to null are ok.
505ef860a24SChandler Carruth   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
506ef860a24SChandler Carruth     return !GV->hasExternalWeakLinkage();
507ef860a24SChandler Carruth 
508*b0407ba0SHal Finkel   // byval arguments are okay. Arguments specifically marked as
509*b0407ba0SHal Finkel   // dereferenceable are okay too.
510*b0407ba0SHal Finkel   if (const Argument *A = dyn_cast<Argument>(V)) {
511*b0407ba0SHal Finkel     if (A->hasByValAttr())
512*b0407ba0SHal Finkel       return true;
513*b0407ba0SHal Finkel     else if (uint64_t Bytes = A->getDereferenceableBytes()) {
514*b0407ba0SHal Finkel       Type *Ty = V->getType()->getPointerElementType();
515*b0407ba0SHal Finkel       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
516*b0407ba0SHal Finkel         return true;
517*b0407ba0SHal Finkel     }
518*b0407ba0SHal Finkel 
519*b0407ba0SHal Finkel     return false;
520*b0407ba0SHal Finkel   }
521*b0407ba0SHal Finkel 
522*b0407ba0SHal Finkel   // Return values from call sites specifically marked as dereferenceable are
523*b0407ba0SHal Finkel   // also okay.
524*b0407ba0SHal Finkel   if (ImmutableCallSite CS = V) {
525*b0407ba0SHal Finkel     if (uint64_t Bytes = CS.getDereferenceableBytes(0)) {
526*b0407ba0SHal Finkel       Type *Ty = V->getType()->getPointerElementType();
527*b0407ba0SHal Finkel       if (Ty->isSized() && DL && DL->getTypeStoreSize(Ty) <= Bytes)
528*b0407ba0SHal Finkel         return true;
529*b0407ba0SHal Finkel     }
530*b0407ba0SHal Finkel   }
531ef860a24SChandler Carruth 
532ef860a24SChandler Carruth   // For GEPs, determine if the indexing lands within the allocated object.
533ef860a24SChandler Carruth   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
534ef860a24SChandler Carruth     // Conservatively require that the base pointer be fully dereferenceable.
535ef860a24SChandler Carruth     if (!Visited.insert(GEP->getOperand(0)))
536ef860a24SChandler Carruth       return false;
5372e42c34dSHal Finkel     if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
538ef860a24SChandler Carruth       return false;
539ef860a24SChandler Carruth     // Check the indices.
540ef860a24SChandler Carruth     gep_type_iterator GTI = gep_type_begin(GEP);
541ef860a24SChandler Carruth     for (User::const_op_iterator I = GEP->op_begin()+1,
542ef860a24SChandler Carruth          E = GEP->op_end(); I != E; ++I) {
543ef860a24SChandler Carruth       Value *Index = *I;
544ef860a24SChandler Carruth       Type *Ty = *GTI++;
545ef860a24SChandler Carruth       // Struct indices can't be out of bounds.
546ef860a24SChandler Carruth       if (isa<StructType>(Ty))
547ef860a24SChandler Carruth         continue;
548ef860a24SChandler Carruth       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
549ef860a24SChandler Carruth       if (!CI)
550ef860a24SChandler Carruth         return false;
551ef860a24SChandler Carruth       // Zero is always ok.
552ef860a24SChandler Carruth       if (CI->isZero())
553ef860a24SChandler Carruth         continue;
554ef860a24SChandler Carruth       // Check to see that it's within the bounds of an array.
555ef860a24SChandler Carruth       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
556ef860a24SChandler Carruth       if (!ATy)
557ef860a24SChandler Carruth         return false;
558ef860a24SChandler Carruth       if (CI->getValue().getActiveBits() > 64)
559ef860a24SChandler Carruth         return false;
560ef860a24SChandler Carruth       if (CI->getZExtValue() >= ATy->getNumElements())
561ef860a24SChandler Carruth         return false;
562ef860a24SChandler Carruth     }
563ef860a24SChandler Carruth     // Indices check out; this is dereferenceable.
564ef860a24SChandler Carruth     return true;
565ef860a24SChandler Carruth   }
566ef860a24SChandler Carruth 
567199b39e0SMatt Arsenault   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
568199b39e0SMatt Arsenault     return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
569199b39e0SMatt Arsenault 
570ef860a24SChandler Carruth   // If we don't know, assume the worst.
571ef860a24SChandler Carruth   return false;
572ef860a24SChandler Carruth }
573ef860a24SChandler Carruth 
574ef860a24SChandler Carruth /// isDereferenceablePointer - Test if this value is always a pointer to
575ef860a24SChandler Carruth /// allocated and suitably aligned memory for a simple load or store.
5762e42c34dSHal Finkel bool Value::isDereferenceablePointer(const DataLayout *DL) const {
577ef860a24SChandler Carruth   SmallPtrSet<const Value *, 32> Visited;
5782e42c34dSHal Finkel   return ::isDereferenceablePointer(this, DL, Visited);
579ef860a24SChandler Carruth }
580ef860a24SChandler Carruth 
581ef860a24SChandler Carruth /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
582ef860a24SChandler Carruth /// return the value in the PHI node corresponding to PredBB.  If not, return
583ef860a24SChandler Carruth /// ourself.  This is useful if you want to know the value something has in a
584ef860a24SChandler Carruth /// predecessor block.
585ef860a24SChandler Carruth Value *Value::DoPHITranslation(const BasicBlock *CurBB,
586ef860a24SChandler Carruth                                const BasicBlock *PredBB) {
587ef860a24SChandler Carruth   PHINode *PN = dyn_cast<PHINode>(this);
588ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
589ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
590ef860a24SChandler Carruth   return this;
591ef860a24SChandler Carruth }
592ef860a24SChandler Carruth 
593ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
594ef860a24SChandler Carruth 
595ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
596ef860a24SChandler Carruth //                             ValueHandleBase Class
597ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
598ef860a24SChandler Carruth 
599ef860a24SChandler Carruth /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
600ef860a24SChandler Carruth /// List is known to point into the existing use list.
601ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
602ef860a24SChandler Carruth   assert(List && "Handle list is null?");
603ef860a24SChandler Carruth 
604ef860a24SChandler Carruth   // Splice ourselves into the list.
605ef860a24SChandler Carruth   Next = *List;
606ef860a24SChandler Carruth   *List = this;
607ef860a24SChandler Carruth   setPrevPtr(List);
608ef860a24SChandler Carruth   if (Next) {
609ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
610ef860a24SChandler Carruth     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
611ef860a24SChandler Carruth   }
612ef860a24SChandler Carruth }
613ef860a24SChandler Carruth 
614ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
615ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
616ef860a24SChandler Carruth 
617ef860a24SChandler Carruth   Next = List->Next;
618ef860a24SChandler Carruth   setPrevPtr(&List->Next);
619ef860a24SChandler Carruth   List->Next = this;
620ef860a24SChandler Carruth   if (Next)
621ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
622ef860a24SChandler Carruth }
623ef860a24SChandler Carruth 
624ef860a24SChandler Carruth /// AddToUseList - Add this ValueHandle to the use list for VP.
625ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
626ef860a24SChandler Carruth   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
627ef860a24SChandler Carruth 
628ef860a24SChandler Carruth   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
629ef860a24SChandler Carruth 
630ef860a24SChandler Carruth   if (VP.getPointer()->HasValueHandle) {
631ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
632ef860a24SChandler Carruth     // ValueHandles map already.
633ef860a24SChandler Carruth     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
6342617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
635ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
636ef860a24SChandler Carruth     return;
637ef860a24SChandler Carruth   }
638ef860a24SChandler Carruth 
639ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
640ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
641ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
642ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
643ef860a24SChandler Carruth   // updating the stale pointers only if needed.
644ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
645ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
646ef860a24SChandler Carruth 
647ef860a24SChandler Carruth   ValueHandleBase *&Entry = Handles[VP.getPointer()];
6482617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
649ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
650ef860a24SChandler Carruth   VP.getPointer()->HasValueHandle = true;
651ef860a24SChandler Carruth 
652ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
653ef860a24SChandler Carruth   // walk the table.
654ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
655ef860a24SChandler Carruth       Handles.size() == 1) {
656ef860a24SChandler Carruth     return;
657ef860a24SChandler Carruth   }
658ef860a24SChandler Carruth 
659ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
660ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
661ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
662ef860a24SChandler Carruth     assert(I->second && I->first == I->second->VP.getPointer() &&
663ef860a24SChandler Carruth            "List invariant broken!");
664ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
665ef860a24SChandler Carruth   }
666ef860a24SChandler Carruth }
667ef860a24SChandler Carruth 
668ef860a24SChandler Carruth /// RemoveFromUseList - Remove this ValueHandle from its current use list.
669ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
670ef860a24SChandler Carruth   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
671ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
672ef860a24SChandler Carruth 
673ef860a24SChandler Carruth   // Unlink this from its use list.
674ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
675ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
676ef860a24SChandler Carruth 
677ef860a24SChandler Carruth   *PrevPtr = Next;
678ef860a24SChandler Carruth   if (Next) {
679ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
680ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
681ef860a24SChandler Carruth     return;
682ef860a24SChandler Carruth   }
683ef860a24SChandler Carruth 
684ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
685ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
686ef860a24SChandler Carruth   // map.
687ef860a24SChandler Carruth   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
688ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
689ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
690ef860a24SChandler Carruth     Handles.erase(VP.getPointer());
691ef860a24SChandler Carruth     VP.getPointer()->HasValueHandle = false;
692ef860a24SChandler Carruth   }
693ef860a24SChandler Carruth }
694ef860a24SChandler Carruth 
695ef860a24SChandler Carruth 
696ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
697ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
698ef860a24SChandler Carruth 
699ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
700ef860a24SChandler Carruth   // HasValueHandle flag is set.
701ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
702ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
703ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
704ef860a24SChandler Carruth 
705ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
706ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
707ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
708ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
709ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
710ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
711ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
712ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
713ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
714ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
715ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
716ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
717ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
718ef860a24SChandler Carruth 
719ef860a24SChandler Carruth     switch (Entry->getKind()) {
720ef860a24SChandler Carruth     case Assert:
721ef860a24SChandler Carruth       break;
722ef860a24SChandler Carruth     case Tracking:
723ef860a24SChandler Carruth       // Mark that this value has been deleted by setting it to an invalid Value
724ef860a24SChandler Carruth       // pointer.
725ef860a24SChandler Carruth       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
726ef860a24SChandler Carruth       break;
727ef860a24SChandler Carruth     case Weak:
728ef860a24SChandler Carruth       // Weak just goes to null, which will unlink it from the list.
729c620761cSCraig Topper       Entry->operator=(nullptr);
730ef860a24SChandler Carruth       break;
731ef860a24SChandler Carruth     case Callback:
732ef860a24SChandler Carruth       // Forward to the subclass's implementation.
733ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
734ef860a24SChandler Carruth       break;
735ef860a24SChandler Carruth     }
736ef860a24SChandler Carruth   }
737ef860a24SChandler Carruth 
738ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
739ef860a24SChandler Carruth   if (V->HasValueHandle) {
740ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
741ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
742ef860a24SChandler Carruth            << "\n";
743ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
744ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
745ef860a24SChandler Carruth                        " value!");
746ef860a24SChandler Carruth 
747ef860a24SChandler Carruth #endif
748ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
749ef860a24SChandler Carruth   }
750ef860a24SChandler Carruth }
751ef860a24SChandler Carruth 
752ef860a24SChandler Carruth 
753ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
754ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
755ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
756ef860a24SChandler Carruth 
757ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
758ef860a24SChandler Carruth   // HasValueHandle flag is set.
759ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
760ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
761ef860a24SChandler Carruth 
762ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
763ef860a24SChandler Carruth 
764ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
765ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
766ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
767ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
768ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
769ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
770ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
771ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
772ef860a24SChandler Carruth 
773ef860a24SChandler Carruth     switch (Entry->getKind()) {
774ef860a24SChandler Carruth     case Assert:
775ef860a24SChandler Carruth       // Asserting handle does not follow RAUW implicitly.
776ef860a24SChandler Carruth       break;
777ef860a24SChandler Carruth     case Tracking:
778ef860a24SChandler Carruth       // Tracking goes to new value like a WeakVH. Note that this may make it
779ef860a24SChandler Carruth       // something incompatible with its templated type. We don't want to have a
780ef860a24SChandler Carruth       // virtual (or inline) interface to handle this though, so instead we make
781ef860a24SChandler Carruth       // the TrackingVH accessors guarantee that a client never sees this value.
782ef860a24SChandler Carruth 
783ef860a24SChandler Carruth       // FALLTHROUGH
784ef860a24SChandler Carruth     case Weak:
785ef860a24SChandler Carruth       // Weak goes to the new value, which will unlink it from Old's list.
786ef860a24SChandler Carruth       Entry->operator=(New);
787ef860a24SChandler Carruth       break;
788ef860a24SChandler Carruth     case Callback:
789ef860a24SChandler Carruth       // Forward to the subclass's implementation.
790ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
791ef860a24SChandler Carruth       break;
792ef860a24SChandler Carruth     }
793ef860a24SChandler Carruth   }
794ef860a24SChandler Carruth 
795ef860a24SChandler Carruth #ifndef NDEBUG
796ef860a24SChandler Carruth   // If any new tracking or weak value handles were added while processing the
797ef860a24SChandler Carruth   // list, then complain about it now.
798ef860a24SChandler Carruth   if (Old->HasValueHandle)
799ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
800ef860a24SChandler Carruth       switch (Entry->getKind()) {
801ef860a24SChandler Carruth       case Tracking:
802ef860a24SChandler Carruth       case Weak:
803ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
804ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
805ef860a24SChandler Carruth                << New->getName() << "\n";
806ef860a24SChandler Carruth         llvm_unreachable("A tracking or weak value handle still pointed to the"
807ef860a24SChandler Carruth                          " old value!\n");
808ef860a24SChandler Carruth       default:
809ef860a24SChandler Carruth         break;
810ef860a24SChandler Carruth       }
811ef860a24SChandler Carruth #endif
812ef860a24SChandler Carruth }
813ef860a24SChandler Carruth 
814d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
815d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
816