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