Fix a warning in builds without asserts.
[oota-llvm.git] / lib / IR / Value.cpp
1 //===-- Value.cpp - Implement the Value class -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Value, ValueHandle, and User classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Value.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GetElementPtrTypeIterator.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LeakDetector.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/IR/ValueSymbolTable.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //                                Value Class
37 //===----------------------------------------------------------------------===//
38
39 static inline Type *checkType(Type *Ty) {
40   assert(Ty && "Value defined with a null type: Error!");
41   return const_cast<Type*>(Ty);
42 }
43
44 Value::Value(Type *ty, unsigned scid)
45   : SubclassID(scid), HasValueHandle(0),
46     SubclassOptionalData(0), SubclassData(0), VTy((Type*)checkType(ty)),
47     UseList(nullptr), Name(nullptr) {
48   // FIXME: Why isn't this in the subclass gunk??
49   // Note, we cannot call isa<CallInst> before the CallInst has been
50   // constructed.
51   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
52     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
53            "invalid CallInst type!");
54   else if (SubclassID != BasicBlockVal &&
55            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
56     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
57            "Cannot create non-first-class values except for constants!");
58 }
59
60 Value::~Value() {
61   // Notify all ValueHandles (if present) that this value is going away.
62   if (HasValueHandle)
63     ValueHandleBase::ValueIsDeleted(this);
64
65 #ifndef NDEBUG      // Only in -g mode...
66   // Check to make sure that there are no uses of this value that are still
67   // around when the value is destroyed.  If there are, then we have a dangling
68   // reference and something is wrong.  This code is here to print out what is
69   // still being referenced.  The value in question should be printed as
70   // a <badref>
71   //
72   if (!use_empty()) {
73     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
74     for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
75       dbgs() << "Use still stuck around after Def is destroyed:"
76            << **I << "\n";
77   }
78 #endif
79   assert(use_empty() && "Uses remain when a value is destroyed!");
80
81   // If this value is named, destroy the name.  This should not be in a symtab
82   // at this point.
83   if (Name && SubclassID != MDStringVal)
84     Name->Destroy();
85
86   // There should be no uses of this object anymore, remove it.
87   LeakDetector::removeGarbageObject(this);
88 }
89
90 /// hasNUses - Return true if this Value has exactly N users.
91 ///
92 bool Value::hasNUses(unsigned N) const {
93   const_use_iterator UI = use_begin(), E = use_end();
94
95   for (; N; --N, ++UI)
96     if (UI == E) return false;  // Too few.
97   return UI == E;
98 }
99
100 /// hasNUsesOrMore - Return true if this value has N users or more.  This is
101 /// logically equivalent to getNumUses() >= N.
102 ///
103 bool Value::hasNUsesOrMore(unsigned N) const {
104   const_use_iterator UI = use_begin(), E = use_end();
105
106   for (; N; --N, ++UI)
107     if (UI == E) return false;  // Too few.
108
109   return true;
110 }
111
112 /// isUsedInBasicBlock - Return true if this value is used in the specified
113 /// basic block.
114 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
115   // This can be computed either by scanning the instructions in BB, or by
116   // scanning the use list of this Value. Both lists can be very long, but
117   // usually one is quite short.
118   //
119   // Scan both lists simultaneously until one is exhausted. This limits the
120   // search to the shorter list.
121   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
122   const_user_iterator UI = user_begin(), UE = user_end();
123   for (; BI != BE && UI != UE; ++BI, ++UI) {
124     // Scan basic block: Check if this Value is used by the instruction at BI.
125     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
126       return true;
127     // Scan use list: Check if the use at UI is in BB.
128     const Instruction *User = dyn_cast<Instruction>(*UI);
129     if (User && User->getParent() == BB)
130       return true;
131   }
132   return false;
133 }
134
135
136 /// getNumUses - This method computes the number of uses of this Value.  This
137 /// is a linear time operation.  Use hasOneUse or hasNUses to check for specific
138 /// values.
139 unsigned Value::getNumUses() const {
140   return (unsigned)std::distance(use_begin(), use_end());
141 }
142
143 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
144   ST = nullptr;
145   if (Instruction *I = dyn_cast<Instruction>(V)) {
146     if (BasicBlock *P = I->getParent())
147       if (Function *PP = P->getParent())
148         ST = &PP->getValueSymbolTable();
149   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
150     if (Function *P = BB->getParent())
151       ST = &P->getValueSymbolTable();
152   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
153     if (Module *P = GV->getParent())
154       ST = &P->getValueSymbolTable();
155   } else if (Argument *A = dyn_cast<Argument>(V)) {
156     if (Function *P = A->getParent())
157       ST = &P->getValueSymbolTable();
158   } else if (isa<MDString>(V))
159     return true;
160   else {
161     assert(isa<Constant>(V) && "Unknown value type!");
162     return true;  // no name is setable for this.
163   }
164   return false;
165 }
166
167 StringRef Value::getName() const {
168   // Make sure the empty string is still a C string. For historical reasons,
169   // some clients want to call .data() on the result and expect it to be null
170   // terminated.
171   if (!Name) return StringRef("", 0);
172   return Name->getKey();
173 }
174
175 void Value::setName(const Twine &NewName) {
176   assert(SubclassID != MDStringVal &&
177          "Cannot set the name of MDString with this method!");
178
179   // Fast path for common IRBuilder case of setName("") when there is no name.
180   if (NewName.isTriviallyEmpty() && !hasName())
181     return;
182
183   SmallString<256> NameData;
184   StringRef NameRef = NewName.toStringRef(NameData);
185   assert(NameRef.find_first_of(0) == StringRef::npos &&
186          "Null bytes are not allowed in names");
187
188   // Name isn't changing?
189   if (getName() == NameRef)
190     return;
191
192   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
193
194   // Get the symbol table to update for this object.
195   ValueSymbolTable *ST;
196   if (getSymTab(this, ST))
197     return;  // Cannot set a name on this value (e.g. constant).
198
199   if (Function *F = dyn_cast<Function>(this))
200     getContext().pImpl->IntrinsicIDCache.erase(F);
201
202   if (!ST) { // No symbol table to update?  Just do the change.
203     if (NameRef.empty()) {
204       // Free the name for this value.
205       Name->Destroy();
206       Name = nullptr;
207       return;
208     }
209
210     if (Name)
211       Name->Destroy();
212
213     // NOTE: Could optimize for the case the name is shrinking to not deallocate
214     // then reallocated.
215
216     // Create the new name.
217     Name = ValueName::Create(NameRef.begin(), NameRef.end());
218     Name->setValue(this);
219     return;
220   }
221
222   // NOTE: Could optimize for the case the name is shrinking to not deallocate
223   // then reallocated.
224   if (hasName()) {
225     // Remove old name.
226     ST->removeValueName(Name);
227     Name->Destroy();
228     Name = nullptr;
229
230     if (NameRef.empty())
231       return;
232   }
233
234   // Name is changing to something new.
235   Name = ST->createValueName(NameRef, this);
236 }
237
238
239 /// takeName - transfer the name from V to this value, setting V's name to
240 /// empty.  It is an error to call V->takeName(V).
241 void Value::takeName(Value *V) {
242   assert(SubclassID != MDStringVal && "Cannot take the name of an MDString!");
243
244   ValueSymbolTable *ST = nullptr;
245   // If this value has a name, drop it.
246   if (hasName()) {
247     // Get the symtab this is in.
248     if (getSymTab(this, ST)) {
249       // We can't set a name on this value, but we need to clear V's name if
250       // it has one.
251       if (V->hasName()) V->setName("");
252       return;  // Cannot set a name on this value (e.g. constant).
253     }
254
255     // Remove old name.
256     if (ST)
257       ST->removeValueName(Name);
258     Name->Destroy();
259     Name = nullptr;
260   }
261
262   // Now we know that this has no name.
263
264   // If V has no name either, we're done.
265   if (!V->hasName()) return;
266
267   // Get this's symtab if we didn't before.
268   if (!ST) {
269     if (getSymTab(this, ST)) {
270       // Clear V's name.
271       V->setName("");
272       return;  // Cannot set a name on this value (e.g. constant).
273     }
274   }
275
276   // Get V's ST, this should always succed, because V has a name.
277   ValueSymbolTable *VST;
278   bool Failure = getSymTab(V, VST);
279   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
280
281   // If these values are both in the same symtab, we can do this very fast.
282   // This works even if both values have no symtab yet.
283   if (ST == VST) {
284     // Take the name!
285     Name = V->Name;
286     V->Name = nullptr;
287     Name->setValue(this);
288     return;
289   }
290
291   // Otherwise, things are slightly more complex.  Remove V's name from VST and
292   // then reinsert it into ST.
293
294   if (VST)
295     VST->removeValueName(V->Name);
296   Name = V->Name;
297   V->Name = nullptr;
298   Name->setValue(this);
299
300   if (ST)
301     ST->reinsertValue(this);
302 }
303
304 static GlobalObject &findReplacementForAliasUse(Value &C) {
305   if (auto *GO = dyn_cast<GlobalObject>(&C))
306     return *GO;
307   if (auto *GA = dyn_cast<GlobalAlias>(&C))
308     return *GA->getAliasee();
309   auto *CE = cast<ConstantExpr>(&C);
310   assert(CE->getOpcode() == Instruction::BitCast ||
311          CE->getOpcode() == Instruction::GetElementPtr ||
312          CE->getOpcode() == Instruction::AddrSpaceCast);
313   if (CE->getOpcode() == Instruction::GetElementPtr)
314     assert(cast<GEPOperator>(CE)->hasAllZeroIndices());
315   return findReplacementForAliasUse(*CE->getOperand(0));
316 }
317
318 static void replaceAliasUseWith(Use &U, Value *New) {
319   GlobalObject &Replacement = findReplacementForAliasUse(*New);
320   assert(&cast<GlobalObject>(*U) != &Replacement &&
321          "replaceAliasUseWith cannot form an alias cycle");
322   U.set(&Replacement);
323 }
324
325 #ifndef NDEBUG
326 static bool contains(SmallPtrSet<ConstantExpr *, 4> &Cache, ConstantExpr *Expr,
327                      Constant *C) {
328   if (!Cache.insert(Expr))
329     return false;
330
331   for (auto &O : Expr->operands()) {
332     if (O == C)
333       return true;
334     auto *CE = dyn_cast<ConstantExpr>(O);
335     if (!CE)
336       continue;
337     if (contains(Cache, CE, C))
338       return true;
339   }
340   return false;
341 }
342
343 static bool contains(Value *Expr, Value *V) {
344   if (Expr == V)
345     return true;
346
347   auto *C = dyn_cast<Constant>(V);
348   if (!C)
349     return false;
350
351   auto *CE = dyn_cast<ConstantExpr>(Expr);
352   if (!CE)
353     return false;
354
355   SmallPtrSet<ConstantExpr *, 4> Cache;
356   return contains(Cache, CE, C);
357 }
358 #endif
359
360 void Value::replaceAllUsesWith(Value *New) {
361   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
362   assert(!contains(New, this) &&
363          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
364   assert(New->getType() == getType() &&
365          "replaceAllUses of value with new value of different type!");
366
367   // Notify all ValueHandles (if present) that this value is going away.
368   if (HasValueHandle)
369     ValueHandleBase::ValueIsRAUWd(this, New);
370
371   while (!use_empty()) {
372     Use &U = *UseList;
373     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
374     // constant because they are uniqued.
375     if (auto *C = dyn_cast<Constant>(U.getUser())) {
376       if (isa<GlobalAlias>(C)) {
377         replaceAliasUseWith(U, New);
378         continue;
379       }
380       if (!isa<GlobalValue>(C)) {
381         C->replaceUsesOfWithOnConstant(this, New, &U);
382         continue;
383       }
384     }
385
386     U.set(New);
387   }
388
389   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
390     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
391 }
392
393 namespace {
394 // Various metrics for how much to strip off of pointers.
395 enum PointerStripKind {
396   PSK_ZeroIndices,
397   PSK_ZeroIndicesAndAliases,
398   PSK_InBoundsConstantIndices,
399   PSK_InBounds
400 };
401
402 template <PointerStripKind StripKind>
403 static Value *stripPointerCastsAndOffsets(Value *V) {
404   if (!V->getType()->isPointerTy())
405     return V;
406
407   // Even though we don't look through PHI nodes, we could be called on an
408   // instruction in an unreachable block, which may be on a cycle.
409   SmallPtrSet<Value *, 4> Visited;
410
411   Visited.insert(V);
412   do {
413     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
414       switch (StripKind) {
415       case PSK_ZeroIndicesAndAliases:
416       case PSK_ZeroIndices:
417         if (!GEP->hasAllZeroIndices())
418           return V;
419         break;
420       case PSK_InBoundsConstantIndices:
421         if (!GEP->hasAllConstantIndices())
422           return V;
423         // fallthrough
424       case PSK_InBounds:
425         if (!GEP->isInBounds())
426           return V;
427         break;
428       }
429       V = GEP->getPointerOperand();
430     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
431                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
432       V = cast<Operator>(V)->getOperand(0);
433     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
434       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
435         return V;
436       V = GA->getAliasee();
437     } else {
438       return V;
439     }
440     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
441   } while (Visited.insert(V));
442
443   return V;
444 }
445 } // namespace
446
447 Value *Value::stripPointerCasts() {
448   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
449 }
450
451 Value *Value::stripPointerCastsNoFollowAliases() {
452   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
453 }
454
455 Value *Value::stripInBoundsConstantOffsets() {
456   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
457 }
458
459 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
460                                                         APInt &Offset) {
461   if (!getType()->isPointerTy())
462     return this;
463
464   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
465                                      getType())->getAddressSpace()) &&
466          "The offset must have exactly as many bits as our pointer.");
467
468   // Even though we don't look through PHI nodes, we could be called on an
469   // instruction in an unreachable block, which may be on a cycle.
470   SmallPtrSet<Value *, 4> Visited;
471   Visited.insert(this);
472   Value *V = this;
473   do {
474     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
475       if (!GEP->isInBounds())
476         return V;
477       APInt GEPOffset(Offset);
478       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
479         return V;
480       Offset = GEPOffset;
481       V = GEP->getPointerOperand();
482     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
483       V = cast<Operator>(V)->getOperand(0);
484     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
485       V = GA->getAliasee();
486     } else {
487       return V;
488     }
489     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
490   } while (Visited.insert(V));
491
492   return V;
493 }
494
495 Value *Value::stripInBoundsOffsets() {
496   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
497 }
498
499 /// isDereferenceablePointer - Test if this value is always a pointer to
500 /// allocated and suitably aligned memory for a simple load or store.
501 static bool isDereferenceablePointer(const Value *V,
502                                      SmallPtrSet<const Value *, 32> &Visited) {
503   // Note that it is not safe to speculate into a malloc'd region because
504   // malloc may return null.
505   // It's also not always safe to follow a bitcast, for example:
506   //   bitcast i8* (alloca i8) to i32*
507   // would result in a 4-byte load from a 1-byte alloca. Some cases could
508   // be handled using DataLayout to check sizes and alignments though.
509
510   // These are obviously ok.
511   if (isa<AllocaInst>(V)) return true;
512
513   // Global variables which can't collapse to null are ok.
514   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
515     return !GV->hasExternalWeakLinkage();
516
517   // byval arguments are ok.
518   if (const Argument *A = dyn_cast<Argument>(V))
519     return A->hasByValAttr();
520
521   // For GEPs, determine if the indexing lands within the allocated object.
522   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
523     // Conservatively require that the base pointer be fully dereferenceable.
524     if (!Visited.insert(GEP->getOperand(0)))
525       return false;
526     if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
527       return false;
528     // Check the indices.
529     gep_type_iterator GTI = gep_type_begin(GEP);
530     for (User::const_op_iterator I = GEP->op_begin()+1,
531          E = GEP->op_end(); I != E; ++I) {
532       Value *Index = *I;
533       Type *Ty = *GTI++;
534       // Struct indices can't be out of bounds.
535       if (isa<StructType>(Ty))
536         continue;
537       ConstantInt *CI = dyn_cast<ConstantInt>(Index);
538       if (!CI)
539         return false;
540       // Zero is always ok.
541       if (CI->isZero())
542         continue;
543       // Check to see that it's within the bounds of an array.
544       ArrayType *ATy = dyn_cast<ArrayType>(Ty);
545       if (!ATy)
546         return false;
547       if (CI->getValue().getActiveBits() > 64)
548         return false;
549       if (CI->getZExtValue() >= ATy->getNumElements())
550         return false;
551     }
552     // Indices check out; this is dereferenceable.
553     return true;
554   }
555
556   // If we don't know, assume the worst.
557   return false;
558 }
559
560 /// isDereferenceablePointer - Test if this value is always a pointer to
561 /// allocated and suitably aligned memory for a simple load or store.
562 bool Value::isDereferenceablePointer() const {
563   SmallPtrSet<const Value *, 32> Visited;
564   return ::isDereferenceablePointer(this, Visited);
565 }
566
567 /// DoPHITranslation - If this value is a PHI node with CurBB as its parent,
568 /// return the value in the PHI node corresponding to PredBB.  If not, return
569 /// ourself.  This is useful if you want to know the value something has in a
570 /// predecessor block.
571 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
572                                const BasicBlock *PredBB) {
573   PHINode *PN = dyn_cast<PHINode>(this);
574   if (PN && PN->getParent() == CurBB)
575     return PN->getIncomingValueForBlock(PredBB);
576   return this;
577 }
578
579 LLVMContext &Value::getContext() const { return VTy->getContext(); }
580
581 //===----------------------------------------------------------------------===//
582 //                             ValueHandleBase Class
583 //===----------------------------------------------------------------------===//
584
585 /// AddToExistingUseList - Add this ValueHandle to the use list for VP, where
586 /// List is known to point into the existing use list.
587 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
588   assert(List && "Handle list is null?");
589
590   // Splice ourselves into the list.
591   Next = *List;
592   *List = this;
593   setPrevPtr(List);
594   if (Next) {
595     Next->setPrevPtr(&Next);
596     assert(VP.getPointer() == Next->VP.getPointer() && "Added to wrong list?");
597   }
598 }
599
600 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
601   assert(List && "Must insert after existing node");
602
603   Next = List->Next;
604   setPrevPtr(&List->Next);
605   List->Next = this;
606   if (Next)
607     Next->setPrevPtr(&Next);
608 }
609
610 /// AddToUseList - Add this ValueHandle to the use list for VP.
611 void ValueHandleBase::AddToUseList() {
612   assert(VP.getPointer() && "Null pointer doesn't have a use list!");
613
614   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
615
616   if (VP.getPointer()->HasValueHandle) {
617     // If this value already has a ValueHandle, then it must be in the
618     // ValueHandles map already.
619     ValueHandleBase *&Entry = pImpl->ValueHandles[VP.getPointer()];
620     assert(Entry && "Value doesn't have any handles?");
621     AddToExistingUseList(&Entry);
622     return;
623   }
624
625   // Ok, it doesn't have any handles yet, so we must insert it into the
626   // DenseMap.  However, doing this insertion could cause the DenseMap to
627   // reallocate itself, which would invalidate all of the PrevP pointers that
628   // point into the old table.  Handle this by checking for reallocation and
629   // updating the stale pointers only if needed.
630   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
631   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
632
633   ValueHandleBase *&Entry = Handles[VP.getPointer()];
634   assert(!Entry && "Value really did already have handles?");
635   AddToExistingUseList(&Entry);
636   VP.getPointer()->HasValueHandle = true;
637
638   // If reallocation didn't happen or if this was the first insertion, don't
639   // walk the table.
640   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
641       Handles.size() == 1) {
642     return;
643   }
644
645   // Okay, reallocation did happen.  Fix the Prev Pointers.
646   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
647        E = Handles.end(); I != E; ++I) {
648     assert(I->second && I->first == I->second->VP.getPointer() &&
649            "List invariant broken!");
650     I->second->setPrevPtr(&I->second);
651   }
652 }
653
654 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
655 void ValueHandleBase::RemoveFromUseList() {
656   assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
657          "Pointer doesn't have a use list!");
658
659   // Unlink this from its use list.
660   ValueHandleBase **PrevPtr = getPrevPtr();
661   assert(*PrevPtr == this && "List invariant broken");
662
663   *PrevPtr = Next;
664   if (Next) {
665     assert(Next->getPrevPtr() == &Next && "List invariant broken");
666     Next->setPrevPtr(PrevPtr);
667     return;
668   }
669
670   // If the Next pointer was null, then it is possible that this was the last
671   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
672   // map.
673   LLVMContextImpl *pImpl = VP.getPointer()->getContext().pImpl;
674   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
675   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
676     Handles.erase(VP.getPointer());
677     VP.getPointer()->HasValueHandle = false;
678   }
679 }
680
681
682 void ValueHandleBase::ValueIsDeleted(Value *V) {
683   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
684
685   // Get the linked list base, which is guaranteed to exist since the
686   // HasValueHandle flag is set.
687   LLVMContextImpl *pImpl = V->getContext().pImpl;
688   ValueHandleBase *Entry = pImpl->ValueHandles[V];
689   assert(Entry && "Value bit set but no entries exist");
690
691   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
692   // and remove themselves from the list without breaking our iteration.  This
693   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
694   // Note that we deliberately do not the support the case when dropping a value
695   // handle results in a new value handle being permanently added to the list
696   // (as might occur in theory for CallbackVH's): the new value handle will not
697   // be processed and the checking code will mete out righteous punishment if
698   // the handle is still present once we have finished processing all the other
699   // value handles (it is fine to momentarily add then remove a value handle).
700   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
701     Iterator.RemoveFromUseList();
702     Iterator.AddToExistingUseListAfter(Entry);
703     assert(Entry->Next == &Iterator && "Loop invariant broken.");
704
705     switch (Entry->getKind()) {
706     case Assert:
707       break;
708     case Tracking:
709       // Mark that this value has been deleted by setting it to an invalid Value
710       // pointer.
711       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
712       break;
713     case Weak:
714       // Weak just goes to null, which will unlink it from the list.
715       Entry->operator=(nullptr);
716       break;
717     case Callback:
718       // Forward to the subclass's implementation.
719       static_cast<CallbackVH*>(Entry)->deleted();
720       break;
721     }
722   }
723
724   // All callbacks, weak references, and assertingVHs should be dropped by now.
725   if (V->HasValueHandle) {
726 #ifndef NDEBUG      // Only in +Asserts mode...
727     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
728            << "\n";
729     if (pImpl->ValueHandles[V]->getKind() == Assert)
730       llvm_unreachable("An asserting value handle still pointed to this"
731                        " value!");
732
733 #endif
734     llvm_unreachable("All references to V were not removed?");
735   }
736 }
737
738
739 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
740   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
741   assert(Old != New && "Changing value into itself!");
742
743   // Get the linked list base, which is guaranteed to exist since the
744   // HasValueHandle flag is set.
745   LLVMContextImpl *pImpl = Old->getContext().pImpl;
746   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
747
748   assert(Entry && "Value bit set but no entries exist");
749
750   // We use a local ValueHandleBase as an iterator so that
751   // ValueHandles can add and remove themselves from the list without
752   // breaking our iteration.  This is not really an AssertingVH; we
753   // just have to give ValueHandleBase some kind.
754   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
755     Iterator.RemoveFromUseList();
756     Iterator.AddToExistingUseListAfter(Entry);
757     assert(Entry->Next == &Iterator && "Loop invariant broken.");
758
759     switch (Entry->getKind()) {
760     case Assert:
761       // Asserting handle does not follow RAUW implicitly.
762       break;
763     case Tracking:
764       // Tracking goes to new value like a WeakVH. Note that this may make it
765       // something incompatible with its templated type. We don't want to have a
766       // virtual (or inline) interface to handle this though, so instead we make
767       // the TrackingVH accessors guarantee that a client never sees this value.
768
769       // FALLTHROUGH
770     case Weak:
771       // Weak goes to the new value, which will unlink it from Old's list.
772       Entry->operator=(New);
773       break;
774     case Callback:
775       // Forward to the subclass's implementation.
776       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
777       break;
778     }
779   }
780
781 #ifndef NDEBUG
782   // If any new tracking or weak value handles were added while processing the
783   // list, then complain about it now.
784   if (Old->HasValueHandle)
785     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
786       switch (Entry->getKind()) {
787       case Tracking:
788       case Weak:
789         dbgs() << "After RAUW from " << *Old->getType() << " %"
790                << Old->getName() << " to " << *New->getType() << " %"
791                << New->getName() << "\n";
792         llvm_unreachable("A tracking or weak value handle still pointed to the"
793                          " old value!\n");
794       default:
795         break;
796       }
797 #endif
798 }
799
800 // Pin the vtable to this file.
801 void CallbackVH::anchor() {}