LLVM  mainline
Value.cpp
Go to the documentation of this file.
00001 //===-- Value.cpp - Implement the Value class -----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Value, ValueHandle, and User classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Value.h"
00015 #include "LLVMContextImpl.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/SmallString.h"
00018 #include "llvm/IR/CallSite.h"
00019 #include "llvm/IR/Constant.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/GetElementPtrTypeIterator.h"
00024 #include "llvm/IR/InstrTypes.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/IntrinsicInst.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/Operator.h"
00029 #include "llvm/IR/Statepoint.h"
00030 #include "llvm/IR/ValueHandle.h"
00031 #include "llvm/IR/ValueSymbolTable.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/ManagedStatic.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include <algorithm>
00037 using namespace llvm;
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                                Value Class
00041 //===----------------------------------------------------------------------===//
00042 const unsigned Value::NumUserOperandsBits;
00043 
00044 static inline Type *checkType(Type *Ty) {
00045   assert(Ty && "Value defined with a null type: Error!");
00046   return Ty;
00047 }
00048 
00049 Value::Value(Type *ty, unsigned scid)
00050     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
00051       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
00052       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
00053   // FIXME: Why isn't this in the subclass gunk??
00054   // Note, we cannot call isa<CallInst> before the CallInst has been
00055   // constructed.
00056   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
00057     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
00058            "invalid CallInst type!");
00059   else if (SubclassID != BasicBlockVal &&
00060            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
00061     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
00062            "Cannot create non-first-class values except for constants!");
00063 }
00064 
00065 Value::~Value() {
00066   // Notify all ValueHandles (if present) that this value is going away.
00067   if (HasValueHandle)
00068     ValueHandleBase::ValueIsDeleted(this);
00069   if (isUsedByMetadata())
00070     ValueAsMetadata::handleDeletion(this);
00071 
00072 #ifndef NDEBUG      // Only in -g mode...
00073   // Check to make sure that there are no uses of this value that are still
00074   // around when the value is destroyed.  If there are, then we have a dangling
00075   // reference and something is wrong.  This code is here to print out where
00076   // the value is still being referenced.
00077   //
00078   if (!use_empty()) {
00079     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
00080     for (auto *U : users())
00081       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
00082   }
00083 #endif
00084   assert(use_empty() && "Uses remain when a value is destroyed!");
00085 
00086   // If this value is named, destroy the name.  This should not be in a symtab
00087   // at this point.
00088   destroyValueName();
00089 }
00090 
00091 void Value::destroyValueName() {
00092   ValueName *Name = getValueName();
00093   if (Name)
00094     Name->Destroy();
00095   setValueName(nullptr);
00096 }
00097 
00098 bool Value::hasNUses(unsigned N) const {
00099   const_use_iterator UI = use_begin(), E = use_end();
00100 
00101   for (; N; --N, ++UI)
00102     if (UI == E) return false;  // Too few.
00103   return UI == E;
00104 }
00105 
00106 bool Value::hasNUsesOrMore(unsigned N) const {
00107   const_use_iterator UI = use_begin(), E = use_end();
00108 
00109   for (; N; --N, ++UI)
00110     if (UI == E) return false;  // Too few.
00111 
00112   return true;
00113 }
00114 
00115 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
00116   // This can be computed either by scanning the instructions in BB, or by
00117   // scanning the use list of this Value. Both lists can be very long, but
00118   // usually one is quite short.
00119   //
00120   // Scan both lists simultaneously until one is exhausted. This limits the
00121   // search to the shorter list.
00122   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
00123   const_user_iterator UI = user_begin(), UE = user_end();
00124   for (; BI != BE && UI != UE; ++BI, ++UI) {
00125     // Scan basic block: Check if this Value is used by the instruction at BI.
00126     if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
00127       return true;
00128     // Scan use list: Check if the use at UI is in BB.
00129     const Instruction *User = dyn_cast<Instruction>(*UI);
00130     if (User && User->getParent() == BB)
00131       return true;
00132   }
00133   return false;
00134 }
00135 
00136 unsigned Value::getNumUses() const {
00137   return (unsigned)std::distance(use_begin(), use_end());
00138 }
00139 
00140 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
00141   ST = nullptr;
00142   if (Instruction *I = dyn_cast<Instruction>(V)) {
00143     if (BasicBlock *P = I->getParent())
00144       if (Function *PP = P->getParent())
00145         ST = &PP->getValueSymbolTable();
00146   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
00147     if (Function *P = BB->getParent())
00148       ST = &P->getValueSymbolTable();
00149   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00150     if (Module *P = GV->getParent())
00151       ST = &P->getValueSymbolTable();
00152   } else if (Argument *A = dyn_cast<Argument>(V)) {
00153     if (Function *P = A->getParent())
00154       ST = &P->getValueSymbolTable();
00155   } else {
00156     assert(isa<Constant>(V) && "Unknown value type!");
00157     return true;  // no name is setable for this.
00158   }
00159   return false;
00160 }
00161 
00162 ValueName *Value::getValueName() const {
00163   if (!HasName) return nullptr;
00164 
00165   LLVMContext &Ctx = getContext();
00166   auto I = Ctx.pImpl->ValueNames.find(this);
00167   assert(I != Ctx.pImpl->ValueNames.end() &&
00168          "No name entry found!");
00169 
00170   return I->second;
00171 }
00172 
00173 void Value::setValueName(ValueName *VN) {
00174   LLVMContext &Ctx = getContext();
00175 
00176   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
00177          "HasName bit out of sync!");
00178 
00179   if (!VN) {
00180     if (HasName)
00181       Ctx.pImpl->ValueNames.erase(this);
00182     HasName = false;
00183     return;
00184   }
00185 
00186   HasName = true;
00187   Ctx.pImpl->ValueNames[this] = VN;
00188 }
00189 
00190 StringRef Value::getName() const {
00191   // Make sure the empty string is still a C string. For historical reasons,
00192   // some clients want to call .data() on the result and expect it to be null
00193   // terminated.
00194   if (!hasName())
00195     return StringRef("", 0);
00196   return getValueName()->getKey();
00197 }
00198 
00199 void Value::setNameImpl(const Twine &NewName) {
00200   // Fast path for common IRBuilder case of setName("") when there is no name.
00201   if (NewName.isTriviallyEmpty() && !hasName())
00202     return;
00203 
00204   SmallString<256> NameData;
00205   StringRef NameRef = NewName.toStringRef(NameData);
00206   assert(NameRef.find_first_of(0) == StringRef::npos &&
00207          "Null bytes are not allowed in names");
00208 
00209   // Name isn't changing?
00210   if (getName() == NameRef)
00211     return;
00212 
00213   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
00214 
00215   // Get the symbol table to update for this object.
00216   ValueSymbolTable *ST;
00217   if (getSymTab(this, ST))
00218     return;  // Cannot set a name on this value (e.g. constant).
00219 
00220   if (!ST) { // No symbol table to update?  Just do the change.
00221     if (NameRef.empty()) {
00222       // Free the name for this value.
00223       destroyValueName();
00224       return;
00225     }
00226 
00227     // NOTE: Could optimize for the case the name is shrinking to not deallocate
00228     // then reallocated.
00229     destroyValueName();
00230 
00231     // Create the new name.
00232     setValueName(ValueName::Create(NameRef));
00233     getValueName()->setValue(this);
00234     return;
00235   }
00236 
00237   // NOTE: Could optimize for the case the name is shrinking to not deallocate
00238   // then reallocated.
00239   if (hasName()) {
00240     // Remove old name.
00241     ST->removeValueName(getValueName());
00242     destroyValueName();
00243 
00244     if (NameRef.empty())
00245       return;
00246   }
00247 
00248   // Name is changing to something new.
00249   setValueName(ST->createValueName(NameRef, this));
00250 }
00251 
00252 void Value::setName(const Twine &NewName) {
00253   setNameImpl(NewName);
00254   if (Function *F = dyn_cast<Function>(this))
00255     F->recalculateIntrinsicID();
00256 }
00257 
00258 void Value::takeName(Value *V) {
00259   ValueSymbolTable *ST = nullptr;
00260   // If this value has a name, drop it.
00261   if (hasName()) {
00262     // Get the symtab this is in.
00263     if (getSymTab(this, ST)) {
00264       // We can't set a name on this value, but we need to clear V's name if
00265       // it has one.
00266       if (V->hasName()) V->setName("");
00267       return;  // Cannot set a name on this value (e.g. constant).
00268     }
00269 
00270     // Remove old name.
00271     if (ST)
00272       ST->removeValueName(getValueName());
00273     destroyValueName();
00274   }
00275 
00276   // Now we know that this has no name.
00277 
00278   // If V has no name either, we're done.
00279   if (!V->hasName()) return;
00280 
00281   // Get this's symtab if we didn't before.
00282   if (!ST) {
00283     if (getSymTab(this, ST)) {
00284       // Clear V's name.
00285       V->setName("");
00286       return;  // Cannot set a name on this value (e.g. constant).
00287     }
00288   }
00289 
00290   // Get V's ST, this should always succed, because V has a name.
00291   ValueSymbolTable *VST;
00292   bool Failure = getSymTab(V, VST);
00293   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
00294 
00295   // If these values are both in the same symtab, we can do this very fast.
00296   // This works even if both values have no symtab yet.
00297   if (ST == VST) {
00298     // Take the name!
00299     setValueName(V->getValueName());
00300     V->setValueName(nullptr);
00301     getValueName()->setValue(this);
00302     return;
00303   }
00304 
00305   // Otherwise, things are slightly more complex.  Remove V's name from VST and
00306   // then reinsert it into ST.
00307 
00308   if (VST)
00309     VST->removeValueName(V->getValueName());
00310   setValueName(V->getValueName());
00311   V->setValueName(nullptr);
00312   getValueName()->setValue(this);
00313 
00314   if (ST)
00315     ST->reinsertValue(this);
00316 }
00317 
00318 #ifndef NDEBUG
00319 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
00320                      Constant *C) {
00321   if (!Cache.insert(Expr).second)
00322     return false;
00323 
00324   for (auto &O : Expr->operands()) {
00325     if (O == C)
00326       return true;
00327     auto *CE = dyn_cast<ConstantExpr>(O);
00328     if (!CE)
00329       continue;
00330     if (contains(Cache, CE, C))
00331       return true;
00332   }
00333   return false;
00334 }
00335 
00336 static bool contains(Value *Expr, Value *V) {
00337   if (Expr == V)
00338     return true;
00339 
00340   auto *C = dyn_cast<Constant>(V);
00341   if (!C)
00342     return false;
00343 
00344   auto *CE = dyn_cast<ConstantExpr>(Expr);
00345   if (!CE)
00346     return false;
00347 
00348   SmallPtrSet<ConstantExpr *, 4> Cache;
00349   return contains(Cache, CE, C);
00350 }
00351 #endif
00352 
00353 void Value::replaceAllUsesWith(Value *New) {
00354   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
00355   assert(!contains(New, this) &&
00356          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
00357   assert(New->getType() == getType() &&
00358          "replaceAllUses of value with new value of different type!");
00359 
00360   // Notify all ValueHandles (if present) that this value is going away.
00361   if (HasValueHandle)
00362     ValueHandleBase::ValueIsRAUWd(this, New);
00363   if (isUsedByMetadata())
00364     ValueAsMetadata::handleRAUW(this, New);
00365 
00366   while (!use_empty()) {
00367     Use &U = *UseList;
00368     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
00369     // constant because they are uniqued.
00370     if (auto *C = dyn_cast<Constant>(U.getUser())) {
00371       if (!isa<GlobalValue>(C)) {
00372         C->replaceUsesOfWithOnConstant(this, New, &U);
00373         continue;
00374       }
00375     }
00376 
00377     U.set(New);
00378   }
00379 
00380   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
00381     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
00382 }
00383 
00384 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
00385 // This routine leaves uses within BB.
00386 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
00387   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
00388   assert(!contains(New, this) &&
00389          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
00390   assert(New->getType() == getType() &&
00391          "replaceUses of value with new value of different type!");
00392   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
00393 
00394   use_iterator UI = use_begin(), E = use_end();
00395   for (; UI != E;) {
00396     Use &U = *UI;
00397     ++UI;
00398     auto *Usr = dyn_cast<Instruction>(U.getUser());
00399     if (Usr && Usr->getParent() == BB)
00400       continue;
00401     U.set(New);
00402   }
00403   return;
00404 }
00405 
00406 namespace {
00407 // Various metrics for how much to strip off of pointers.
00408 enum PointerStripKind {
00409   PSK_ZeroIndices,
00410   PSK_ZeroIndicesAndAliases,
00411   PSK_InBoundsConstantIndices,
00412   PSK_InBounds
00413 };
00414 
00415 template <PointerStripKind StripKind>
00416 static Value *stripPointerCastsAndOffsets(Value *V) {
00417   if (!V->getType()->isPointerTy())
00418     return V;
00419 
00420   // Even though we don't look through PHI nodes, we could be called on an
00421   // instruction in an unreachable block, which may be on a cycle.
00422   SmallPtrSet<Value *, 4> Visited;
00423 
00424   Visited.insert(V);
00425   do {
00426     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00427       switch (StripKind) {
00428       case PSK_ZeroIndicesAndAliases:
00429       case PSK_ZeroIndices:
00430         if (!GEP->hasAllZeroIndices())
00431           return V;
00432         break;
00433       case PSK_InBoundsConstantIndices:
00434         if (!GEP->hasAllConstantIndices())
00435           return V;
00436         // fallthrough
00437       case PSK_InBounds:
00438         if (!GEP->isInBounds())
00439           return V;
00440         break;
00441       }
00442       V = GEP->getPointerOperand();
00443     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00444                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00445       V = cast<Operator>(V)->getOperand(0);
00446     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00447       if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
00448         return V;
00449       V = GA->getAliasee();
00450     } else {
00451       return V;
00452     }
00453     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00454   } while (Visited.insert(V).second);
00455 
00456   return V;
00457 }
00458 } // namespace
00459 
00460 Value *Value::stripPointerCasts() {
00461   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
00462 }
00463 
00464 Value *Value::stripPointerCastsNoFollowAliases() {
00465   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
00466 }
00467 
00468 Value *Value::stripInBoundsConstantOffsets() {
00469   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
00470 }
00471 
00472 Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
00473                                                         APInt &Offset) {
00474   if (!getType()->isPointerTy())
00475     return this;
00476 
00477   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
00478                                      getType())->getAddressSpace()) &&
00479          "The offset must have exactly as many bits as our pointer.");
00480 
00481   // Even though we don't look through PHI nodes, we could be called on an
00482   // instruction in an unreachable block, which may be on a cycle.
00483   SmallPtrSet<Value *, 4> Visited;
00484   Visited.insert(this);
00485   Value *V = this;
00486   do {
00487     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00488       if (!GEP->isInBounds())
00489         return V;
00490       APInt GEPOffset(Offset);
00491       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
00492         return V;
00493       Offset = GEPOffset;
00494       V = GEP->getPointerOperand();
00495     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
00496                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
00497       V = cast<Operator>(V)->getOperand(0);
00498     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00499       V = GA->getAliasee();
00500     } else {
00501       return V;
00502     }
00503     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00504   } while (Visited.insert(V).second);
00505 
00506   return V;
00507 }
00508 
00509 Value *Value::stripInBoundsOffsets() {
00510   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
00511 }
00512 
00513 Value *Value::DoPHITranslation(const BasicBlock *CurBB,
00514                                const BasicBlock *PredBB) {
00515   PHINode *PN = dyn_cast<PHINode>(this);
00516   if (PN && PN->getParent() == CurBB)
00517     return PN->getIncomingValueForBlock(PredBB);
00518   return this;
00519 }
00520 
00521 LLVMContext &Value::getContext() const { return VTy->getContext(); }
00522 
00523 void Value::reverseUseList() {
00524   if (!UseList || !UseList->Next)
00525     // No need to reverse 0 or 1 uses.
00526     return;
00527 
00528   Use *Head = UseList;
00529   Use *Current = UseList->Next;
00530   Head->Next = nullptr;
00531   while (Current) {
00532     Use *Next = Current->Next;
00533     Current->Next = Head;
00534     Head->setPrev(&Current->Next);
00535     Head = Current;
00536     Current = Next;
00537   }
00538   UseList = Head;
00539   Head->setPrev(&UseList);
00540 }
00541 
00542 //===----------------------------------------------------------------------===//
00543 //                             ValueHandleBase Class
00544 //===----------------------------------------------------------------------===//
00545 
00546 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
00547   assert(List && "Handle list is null?");
00548 
00549   // Splice ourselves into the list.
00550   Next = *List;
00551   *List = this;
00552   setPrevPtr(List);
00553   if (Next) {
00554     Next->setPrevPtr(&Next);
00555     assert(V == Next->V && "Added to wrong list?");
00556   }
00557 }
00558 
00559 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
00560   assert(List && "Must insert after existing node");
00561 
00562   Next = List->Next;
00563   setPrevPtr(&List->Next);
00564   List->Next = this;
00565   if (Next)
00566     Next->setPrevPtr(&Next);
00567 }
00568 
00569 void ValueHandleBase::AddToUseList() {
00570   assert(V && "Null pointer doesn't have a use list!");
00571 
00572   LLVMContextImpl *pImpl = V->getContext().pImpl;
00573 
00574   if (V->HasValueHandle) {
00575     // If this value already has a ValueHandle, then it must be in the
00576     // ValueHandles map already.
00577     ValueHandleBase *&Entry = pImpl->ValueHandles[V];
00578     assert(Entry && "Value doesn't have any handles?");
00579     AddToExistingUseList(&Entry);
00580     return;
00581   }
00582 
00583   // Ok, it doesn't have any handles yet, so we must insert it into the
00584   // DenseMap.  However, doing this insertion could cause the DenseMap to
00585   // reallocate itself, which would invalidate all of the PrevP pointers that
00586   // point into the old table.  Handle this by checking for reallocation and
00587   // updating the stale pointers only if needed.
00588   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00589   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
00590 
00591   ValueHandleBase *&Entry = Handles[V];
00592   assert(!Entry && "Value really did already have handles?");
00593   AddToExistingUseList(&Entry);
00594   V->HasValueHandle = true;
00595 
00596   // If reallocation didn't happen or if this was the first insertion, don't
00597   // walk the table.
00598   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
00599       Handles.size() == 1) {
00600     return;
00601   }
00602 
00603   // Okay, reallocation did happen.  Fix the Prev Pointers.
00604   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
00605        E = Handles.end(); I != E; ++I) {
00606     assert(I->second && I->first == I->second->V &&
00607            "List invariant broken!");
00608     I->second->setPrevPtr(&I->second);
00609   }
00610 }
00611 
00612 void ValueHandleBase::RemoveFromUseList() {
00613   assert(V && V->HasValueHandle &&
00614          "Pointer doesn't have a use list!");
00615 
00616   // Unlink this from its use list.
00617   ValueHandleBase **PrevPtr = getPrevPtr();
00618   assert(*PrevPtr == this && "List invariant broken");
00619 
00620   *PrevPtr = Next;
00621   if (Next) {
00622     assert(Next->getPrevPtr() == &Next && "List invariant broken");
00623     Next->setPrevPtr(PrevPtr);
00624     return;
00625   }
00626 
00627   // If the Next pointer was null, then it is possible that this was the last
00628   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
00629   // map.
00630   LLVMContextImpl *pImpl = V->getContext().pImpl;
00631   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
00632   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
00633     Handles.erase(V);
00634     V->HasValueHandle = false;
00635   }
00636 }
00637 
00638 
00639 void ValueHandleBase::ValueIsDeleted(Value *V) {
00640   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
00641 
00642   // Get the linked list base, which is guaranteed to exist since the
00643   // HasValueHandle flag is set.
00644   LLVMContextImpl *pImpl = V->getContext().pImpl;
00645   ValueHandleBase *Entry = pImpl->ValueHandles[V];
00646   assert(Entry && "Value bit set but no entries exist");
00647 
00648   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
00649   // and remove themselves from the list without breaking our iteration.  This
00650   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
00651   // Note that we deliberately do not the support the case when dropping a value
00652   // handle results in a new value handle being permanently added to the list
00653   // (as might occur in theory for CallbackVH's): the new value handle will not
00654   // be processed and the checking code will mete out righteous punishment if
00655   // the handle is still present once we have finished processing all the other
00656   // value handles (it is fine to momentarily add then remove a value handle).
00657   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00658     Iterator.RemoveFromUseList();
00659     Iterator.AddToExistingUseListAfter(Entry);
00660     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00661 
00662     switch (Entry->getKind()) {
00663     case Assert:
00664       break;
00665     case Tracking:
00666       // Mark that this value has been deleted by setting it to an invalid Value
00667       // pointer.
00668       Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
00669       break;
00670     case Weak:
00671       // Weak just goes to null, which will unlink it from the list.
00672       Entry->operator=(nullptr);
00673       break;
00674     case Callback:
00675       // Forward to the subclass's implementation.
00676       static_cast<CallbackVH*>(Entry)->deleted();
00677       break;
00678     }
00679   }
00680 
00681   // All callbacks, weak references, and assertingVHs should be dropped by now.
00682   if (V->HasValueHandle) {
00683 #ifndef NDEBUG      // Only in +Asserts mode...
00684     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
00685            << "\n";
00686     if (pImpl->ValueHandles[V]->getKind() == Assert)
00687       llvm_unreachable("An asserting value handle still pointed to this"
00688                        " value!");
00689 
00690 #endif
00691     llvm_unreachable("All references to V were not removed?");
00692   }
00693 }
00694 
00695 
00696 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
00697   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
00698   assert(Old != New && "Changing value into itself!");
00699   assert(Old->getType() == New->getType() &&
00700          "replaceAllUses of value with new value of different type!");
00701 
00702   // Get the linked list base, which is guaranteed to exist since the
00703   // HasValueHandle flag is set.
00704   LLVMContextImpl *pImpl = Old->getContext().pImpl;
00705   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
00706 
00707   assert(Entry && "Value bit set but no entries exist");
00708 
00709   // We use a local ValueHandleBase as an iterator so that
00710   // ValueHandles can add and remove themselves from the list without
00711   // breaking our iteration.  This is not really an AssertingVH; we
00712   // just have to give ValueHandleBase some kind.
00713   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
00714     Iterator.RemoveFromUseList();
00715     Iterator.AddToExistingUseListAfter(Entry);
00716     assert(Entry->Next == &Iterator && "Loop invariant broken.");
00717 
00718     switch (Entry->getKind()) {
00719     case Assert:
00720       // Asserting handle does not follow RAUW implicitly.
00721       break;
00722     case Tracking:
00723       // Tracking goes to new value like a WeakVH. Note that this may make it
00724       // something incompatible with its templated type. We don't want to have a
00725       // virtual (or inline) interface to handle this though, so instead we make
00726       // the TrackingVH accessors guarantee that a client never sees this value.
00727 
00728       // FALLTHROUGH
00729     case Weak:
00730       // Weak goes to the new value, which will unlink it from Old's list.
00731       Entry->operator=(New);
00732       break;
00733     case Callback:
00734       // Forward to the subclass's implementation.
00735       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
00736       break;
00737     }
00738   }
00739 
00740 #ifndef NDEBUG
00741   // If any new tracking or weak value handles were added while processing the
00742   // list, then complain about it now.
00743   if (Old->HasValueHandle)
00744     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
00745       switch (Entry->getKind()) {
00746       case Tracking:
00747       case Weak:
00748         dbgs() << "After RAUW from " << *Old->getType() << " %"
00749                << Old->getName() << " to " << *New->getType() << " %"
00750                << New->getName() << "\n";
00751         llvm_unreachable("A tracking or weak value handle still pointed to the"
00752                          " old value!\n");
00753       default:
00754         break;
00755       }
00756 #endif
00757 }
00758 
00759 // Pin the vtable to this file.
00760 void CallbackVH::anchor() {}