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