Value.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. #include "llvm/IR/Value.h"
  14. #include "LLVMContextImpl.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/IR/CallSite.h"
  18. #include "llvm/IR/Constant.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/GetElementPtrTypeIterator.h"
  23. #include "llvm/IR/InstrTypes.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/Operator.h"
  28. #include "llvm/IR/Statepoint.h"
  29. #include "llvm/IR/ValueHandle.h"
  30. #include "llvm/IR/ValueSymbolTable.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/ManagedStatic.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <algorithm>
  36. using namespace llvm;
  37. //===----------------------------------------------------------------------===//
  38. // Value Class
  39. //===----------------------------------------------------------------------===//
  40. static inline Type *checkType(Type *Ty) {
  41. assert(Ty && "Value defined with a null type: Error!");
  42. return Ty;
  43. }
  44. Value::Value(Type *ty, unsigned scid)
  45. : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
  46. HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
  47. NumUserOperands(0), IsUsedByMD(false), HasName(false) {
  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. Value::~Value() {
  60. // Notify all ValueHandles (if present) that this value is going away.
  61. if (HasValueHandle)
  62. ValueHandleBase::ValueIsDeleted(this);
  63. if (isUsedByMetadata())
  64. ValueAsMetadata::handleDeletion(this);
  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 where
  69. // the value is still being referenced.
  70. //
  71. if (!use_empty()) {
  72. dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
  73. for (auto *U : users())
  74. dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
  75. }
  76. #endif
  77. assert(use_empty() && "Uses remain when a value is destroyed!");
  78. // If this value is named, destroy the name. This should not be in a symtab
  79. // at this point.
  80. destroyValueName();
  81. }
  82. void Value::destroyValueName() {
  83. ValueName *Name = getValueName();
  84. if (Name)
  85. Name->Destroy();
  86. setValueName(nullptr);
  87. }
  88. bool Value::hasNUses(unsigned N) const {
  89. const_use_iterator UI = use_begin(), E = use_end();
  90. for (; N; --N, ++UI)
  91. if (UI == E) return false; // Too few.
  92. return UI == E;
  93. }
  94. bool Value::hasNUsesOrMore(unsigned N) const {
  95. const_use_iterator UI = use_begin(), E = use_end();
  96. for (; N; --N, ++UI)
  97. if (UI == E) return false; // Too few.
  98. return true;
  99. }
  100. bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
  101. // This can be computed either by scanning the instructions in BB, or by
  102. // scanning the use list of this Value. Both lists can be very long, but
  103. // usually one is quite short.
  104. //
  105. // Scan both lists simultaneously until one is exhausted. This limits the
  106. // search to the shorter list.
  107. BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
  108. const_user_iterator UI = user_begin(), UE = user_end();
  109. for (; BI != BE && UI != UE; ++BI, ++UI) {
  110. // Scan basic block: Check if this Value is used by the instruction at BI.
  111. if (std::find(BI->op_begin(), BI->op_end(), this) != BI->op_end())
  112. return true;
  113. // Scan use list: Check if the use at UI is in BB.
  114. const Instruction *User = dyn_cast<Instruction>(*UI);
  115. if (User && User->getParent() == BB)
  116. return true;
  117. }
  118. return false;
  119. }
  120. unsigned Value::getNumUses() const {
  121. return (unsigned)std::distance(use_begin(), use_end());
  122. }
  123. static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
  124. ST = nullptr;
  125. if (Instruction *I = dyn_cast<Instruction>(V)) {
  126. if (BasicBlock *P = I->getParent())
  127. if (Function *PP = P->getParent())
  128. ST = &PP->getValueSymbolTable();
  129. } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
  130. if (Function *P = BB->getParent())
  131. ST = &P->getValueSymbolTable();
  132. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  133. if (Module *P = GV->getParent())
  134. ST = &P->getValueSymbolTable();
  135. } else if (Argument *A = dyn_cast<Argument>(V)) {
  136. if (Function *P = A->getParent())
  137. ST = &P->getValueSymbolTable();
  138. } else {
  139. assert(isa<Constant>(V) && "Unknown value type!");
  140. return true; // no name is setable for this.
  141. }
  142. return false;
  143. }
  144. ValueName *Value::getValueName() const {
  145. if (!HasName) return nullptr;
  146. LLVMContext &Ctx = getContext();
  147. auto I = Ctx.pImpl->ValueNames.find(this);
  148. assert(I != Ctx.pImpl->ValueNames.end() &&
  149. "No name entry found!");
  150. return I->second;
  151. }
  152. void Value::setValueName(ValueName *VN) {
  153. LLVMContext &Ctx = getContext();
  154. assert(HasName == (bool)Ctx.pImpl->ValueNames.count(this) && // HLSL Change - bool == int
  155. "HasName bit out of sync!");
  156. if (!VN) {
  157. if (HasName)
  158. Ctx.pImpl->ValueNames.erase(this);
  159. HasName = false;
  160. return;
  161. }
  162. Ctx.pImpl->ValueNames[this] = VN;
  163. HasName = true; // HLSL Change - only set this to true after assignment
  164. }
  165. StringRef Value::getName() const {
  166. // Make sure the empty string is still a C string. For historical reasons,
  167. // some clients want to call .data() on the result and expect it to be null
  168. // terminated.
  169. if (!hasName())
  170. return StringRef("", 0);
  171. return getValueName()->getKey();
  172. }
  173. void Value::setNameImpl(const Twine &NewName) {
  174. // Fast path for common IRBuilder case of setName("") when there is no name.
  175. if (NewName.isTriviallyEmpty() && !hasName())
  176. return;
  177. SmallString<256> NameData;
  178. StringRef NameRef = NewName.toStringRef(NameData);
  179. assert(NameRef.find_first_of(0) == StringRef::npos &&
  180. "Null bytes are not allowed in names");
  181. // Name isn't changing?
  182. if (getName() == NameRef)
  183. return;
  184. assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
  185. // Get the symbol table to update for this object.
  186. ValueSymbolTable *ST;
  187. if (getSymTab(this, ST))
  188. return; // Cannot set a name on this value (e.g. constant).
  189. if (!ST) { // No symbol table to update? Just do the change.
  190. if (NameRef.empty()) {
  191. // Free the name for this value.
  192. destroyValueName();
  193. return;
  194. }
  195. // NOTE: Could optimize for the case the name is shrinking to not deallocate
  196. // then reallocated.
  197. destroyValueName();
  198. // Create the new name.
  199. setValueName(ValueName::Create(NameRef));
  200. getValueName()->setValue(this);
  201. return;
  202. }
  203. // NOTE: Could optimize for the case the name is shrinking to not deallocate
  204. // then reallocated.
  205. if (hasName()) {
  206. // Remove old name.
  207. ST->removeValueName(getValueName());
  208. destroyValueName();
  209. if (NameRef.empty())
  210. return;
  211. }
  212. // Name is changing to something new.
  213. setValueName(ST->createValueName(NameRef, this));
  214. }
  215. void Value::setName(const Twine &NewName) {
  216. setNameImpl(NewName);
  217. if (Function *F = dyn_cast<Function>(this))
  218. F->recalculateIntrinsicID();
  219. }
  220. void Value::takeName(Value *V) {
  221. ValueSymbolTable *ST = nullptr;
  222. // If this value has a name, drop it.
  223. if (hasName()) {
  224. // Get the symtab this is in.
  225. if (getSymTab(this, ST)) {
  226. // We can't set a name on this value, but we need to clear V's name if
  227. // it has one.
  228. if (V->hasName()) V->setName("");
  229. return; // Cannot set a name on this value (e.g. constant).
  230. }
  231. // Remove old name.
  232. if (ST)
  233. ST->removeValueName(getValueName());
  234. destroyValueName();
  235. }
  236. // Now we know that this has no name.
  237. // If V has no name either, we're done.
  238. if (!V->hasName()) return;
  239. // Get this's symtab if we didn't before.
  240. if (!ST) {
  241. if (getSymTab(this, ST)) {
  242. // Clear V's name.
  243. V->setName("");
  244. return; // Cannot set a name on this value (e.g. constant).
  245. }
  246. }
  247. // Get V's ST, this should always succed, because V has a name.
  248. ValueSymbolTable *VST;
  249. bool Failure = getSymTab(V, VST);
  250. assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
  251. // If these values are both in the same symtab, we can do this very fast.
  252. // This works even if both values have no symtab yet.
  253. if (ST == VST) {
  254. // Take the name!
  255. setValueName(V->getValueName());
  256. V->setValueName(nullptr);
  257. getValueName()->setValue(this);
  258. return;
  259. }
  260. // Otherwise, things are slightly more complex. Remove V's name from VST and
  261. // then reinsert it into ST.
  262. if (VST)
  263. VST->removeValueName(V->getValueName());
  264. setValueName(V->getValueName());
  265. V->setValueName(nullptr);
  266. getValueName()->setValue(this);
  267. if (ST)
  268. ST->reinsertValue(this);
  269. }
  270. #ifndef NDEBUG
  271. static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
  272. Constant *C) {
  273. if (!Cache.insert(Expr).second)
  274. return false;
  275. for (auto &O : Expr->operands()) {
  276. if (O == C)
  277. return true;
  278. auto *CE = dyn_cast<ConstantExpr>(O);
  279. if (!CE)
  280. continue;
  281. if (contains(Cache, CE, C))
  282. return true;
  283. }
  284. return false;
  285. }
  286. static bool contains(Value *Expr, Value *V) {
  287. if (Expr == V)
  288. return true;
  289. auto *C = dyn_cast<Constant>(V);
  290. if (!C)
  291. return false;
  292. auto *CE = dyn_cast<ConstantExpr>(Expr);
  293. if (!CE)
  294. return false;
  295. SmallPtrSet<ConstantExpr *, 4> Cache;
  296. return contains(Cache, CE, C);
  297. }
  298. #endif
  299. void Value::replaceAllUsesWith(Value *New) {
  300. assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
  301. assert(!contains(New, this) &&
  302. "this->replaceAllUsesWith(expr(this)) is NOT valid!");
  303. assert(New->getType() == getType() &&
  304. "replaceAllUses of value with new value of different type!");
  305. // Notify all ValueHandles (if present) that this value is going away.
  306. if (HasValueHandle)
  307. ValueHandleBase::ValueIsRAUWd(this, New);
  308. if (isUsedByMetadata())
  309. ValueAsMetadata::handleRAUW(this, New);
  310. while (!use_empty()) {
  311. Use &U = *UseList;
  312. // Must handle Constants specially, we cannot call replaceUsesOfWith on a
  313. // constant because they are uniqued.
  314. if (auto *C = dyn_cast<Constant>(U.getUser())) {
  315. if (!isa<GlobalValue>(C)) {
  316. C->handleOperandChange(this, New, &U);
  317. continue;
  318. }
  319. }
  320. U.set(New);
  321. }
  322. if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
  323. BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
  324. }
  325. // Like replaceAllUsesWith except it does not handle constants or basic blocks.
  326. // This routine leaves uses within BB.
  327. void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
  328. assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
  329. assert(!contains(New, this) &&
  330. "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
  331. assert(New->getType() == getType() &&
  332. "replaceUses of value with new value of different type!");
  333. assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
  334. use_iterator UI = use_begin(), E = use_end();
  335. for (; UI != E;) {
  336. Use &U = *UI;
  337. ++UI;
  338. auto *Usr = dyn_cast<Instruction>(U.getUser());
  339. if (Usr && Usr->getParent() == BB)
  340. continue;
  341. U.set(New);
  342. }
  343. return;
  344. }
  345. namespace {
  346. // Various metrics for how much to strip off of pointers.
  347. enum PointerStripKind {
  348. PSK_ZeroIndices,
  349. PSK_ZeroIndicesAndAliases,
  350. PSK_InBoundsConstantIndices,
  351. PSK_InBounds
  352. };
  353. template <PointerStripKind StripKind>
  354. static Value *stripPointerCastsAndOffsets(Value *V) {
  355. if (!V->getType()->isPointerTy())
  356. return V;
  357. // Even though we don't look through PHI nodes, we could be called on an
  358. // instruction in an unreachable block, which may be on a cycle.
  359. SmallPtrSet<Value *, 4> Visited;
  360. Visited.insert(V);
  361. do {
  362. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  363. switch (StripKind) {
  364. case PSK_ZeroIndicesAndAliases:
  365. case PSK_ZeroIndices:
  366. if (!GEP->hasAllZeroIndices())
  367. return V;
  368. break;
  369. case PSK_InBoundsConstantIndices:
  370. if (!GEP->hasAllConstantIndices())
  371. return V;
  372. // fallthrough
  373. case PSK_InBounds:
  374. if (!GEP->isInBounds())
  375. return V;
  376. break;
  377. }
  378. V = GEP->getPointerOperand();
  379. } else if (Operator::getOpcode(V) == Instruction::BitCast ||
  380. Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
  381. V = cast<Operator>(V)->getOperand(0);
  382. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  383. if (StripKind == PSK_ZeroIndices || GA->mayBeOverridden())
  384. return V;
  385. V = GA->getAliasee();
  386. } else {
  387. return V;
  388. }
  389. assert(V->getType()->isPointerTy() && "Unexpected operand type!");
  390. } while (Visited.insert(V).second);
  391. return V;
  392. }
  393. } // namespace
  394. Value *Value::stripPointerCasts() {
  395. return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
  396. }
  397. Value *Value::stripPointerCastsNoFollowAliases() {
  398. return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
  399. }
  400. Value *Value::stripInBoundsConstantOffsets() {
  401. return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
  402. }
  403. Value *Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
  404. APInt &Offset) {
  405. if (!getType()->isPointerTy())
  406. return this;
  407. assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
  408. getType())->getAddressSpace()) &&
  409. "The offset must have exactly as many bits as our pointer.");
  410. // Even though we don't look through PHI nodes, we could be called on an
  411. // instruction in an unreachable block, which may be on a cycle.
  412. SmallPtrSet<Value *, 4> Visited;
  413. Visited.insert(this);
  414. Value *V = this;
  415. do {
  416. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  417. if (!GEP->isInBounds())
  418. return V;
  419. APInt GEPOffset(Offset);
  420. if (!GEP->accumulateConstantOffset(DL, GEPOffset))
  421. return V;
  422. Offset = GEPOffset;
  423. V = GEP->getPointerOperand();
  424. } else if (Operator::getOpcode(V) == Instruction::BitCast ||
  425. Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
  426. V = cast<Operator>(V)->getOperand(0);
  427. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  428. V = GA->getAliasee();
  429. } else {
  430. return V;
  431. }
  432. assert(V->getType()->isPointerTy() && "Unexpected operand type!");
  433. } while (Visited.insert(V).second);
  434. return V;
  435. }
  436. Value *Value::stripInBoundsOffsets() {
  437. return stripPointerCastsAndOffsets<PSK_InBounds>(this);
  438. }
  439. Value *Value::DoPHITranslation(const BasicBlock *CurBB,
  440. const BasicBlock *PredBB) {
  441. PHINode *PN = dyn_cast<PHINode>(this);
  442. if (PN && PN->getParent() == CurBB)
  443. return PN->getIncomingValueForBlock(PredBB);
  444. return this;
  445. }
  446. LLVMContext &Value::getContext() const { return VTy->getContext(); }
  447. void Value::reverseUseList() {
  448. if (!UseList || !UseList->Next)
  449. // No need to reverse 0 or 1 uses.
  450. return;
  451. Use *Head = UseList;
  452. Use *Current = UseList->Next;
  453. Head->Next = nullptr;
  454. while (Current) {
  455. Use *Next = Current->Next;
  456. Current->Next = Head;
  457. Head->setPrev(&Current->Next);
  458. Head = Current;
  459. Current = Next;
  460. }
  461. UseList = Head;
  462. Head->setPrev(&UseList);
  463. }
  464. //===----------------------------------------------------------------------===//
  465. // ValueHandleBase Class
  466. //===----------------------------------------------------------------------===//
  467. void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
  468. assert(List && "Handle list is null?");
  469. // Splice ourselves into the list.
  470. Next = *List;
  471. *List = this;
  472. setPrevPtr(List);
  473. if (Next) {
  474. Next->setPrevPtr(&Next);
  475. assert(V == Next->V && "Added to wrong list?");
  476. }
  477. }
  478. void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
  479. assert(List && "Must insert after existing node");
  480. Next = List->Next;
  481. setPrevPtr(&List->Next);
  482. List->Next = this;
  483. if (Next)
  484. Next->setPrevPtr(&Next);
  485. }
  486. void ValueHandleBase::AddToUseList() {
  487. assert(V && "Null pointer doesn't have a use list!");
  488. LLVMContextImpl *pImpl = V->getContext().pImpl;
  489. if (V->HasValueHandle) {
  490. // If this value already has a ValueHandle, then it must be in the
  491. // ValueHandles map already.
  492. ValueHandleBase *&Entry = pImpl->ValueHandles[V];
  493. assert(Entry && "Value doesn't have any handles?");
  494. AddToExistingUseList(&Entry);
  495. return;
  496. }
  497. // Ok, it doesn't have any handles yet, so we must insert it into the
  498. // DenseMap. However, doing this insertion could cause the DenseMap to
  499. // reallocate itself, which would invalidate all of the PrevP pointers that
  500. // point into the old table. Handle this by checking for reallocation and
  501. // updating the stale pointers only if needed.
  502. DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
  503. const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
  504. ValueHandleBase *&Entry = Handles[V];
  505. assert(!Entry && "Value really did already have handles?");
  506. AddToExistingUseList(&Entry);
  507. V->HasValueHandle = true;
  508. // If reallocation didn't happen or if this was the first insertion, don't
  509. // walk the table.
  510. if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
  511. Handles.size() == 1) {
  512. return;
  513. }
  514. // Okay, reallocation did happen. Fix the Prev Pointers.
  515. for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
  516. E = Handles.end(); I != E; ++I) {
  517. assert(I->second && I->first == I->second->V &&
  518. "List invariant broken!");
  519. I->second->setPrevPtr(&I->second);
  520. }
  521. }
  522. void ValueHandleBase::RemoveFromUseList() {
  523. assert(V && (std::current_exception() == nullptr || V->HasValueHandle) && // HLSL Change
  524. "Pointer doesn't have a use list!");
  525. if (!V->HasValueHandle) return; // HLSL Change
  526. // Unlink this from its use list.
  527. ValueHandleBase **PrevPtr = getPrevPtr();
  528. assert(*PrevPtr == this && "List invariant broken");
  529. *PrevPtr = Next;
  530. if (Next) {
  531. assert(Next->getPrevPtr() == &Next && "List invariant broken");
  532. Next->setPrevPtr(PrevPtr);
  533. return;
  534. }
  535. // If the Next pointer was null, then it is possible that this was the last
  536. // ValueHandle watching VP. If so, delete its entry from the ValueHandles
  537. // map.
  538. LLVMContextImpl *pImpl = V->getContext().pImpl;
  539. DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
  540. if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
  541. Handles.erase(V);
  542. V->HasValueHandle = false;
  543. }
  544. }
  545. void ValueHandleBase::ValueIsDeleted(Value *V) {
  546. assert(V->HasValueHandle && "Should only be called if ValueHandles present");
  547. // Get the linked list base, which is guaranteed to exist since the
  548. // HasValueHandle flag is set.
  549. LLVMContextImpl *pImpl = V->getContext().pImpl;
  550. ValueHandleBase *Entry = pImpl->ValueHandles[V];
  551. assert(Entry && "Value bit set but no entries exist");
  552. // We use a local ValueHandleBase as an iterator so that ValueHandles can add
  553. // and remove themselves from the list without breaking our iteration. This
  554. // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
  555. // Note that we deliberately do not the support the case when dropping a value
  556. // handle results in a new value handle being permanently added to the list
  557. // (as might occur in theory for CallbackVH's): the new value handle will not
  558. // be processed and the checking code will mete out righteous punishment if
  559. // the handle is still present once we have finished processing all the other
  560. // value handles (it is fine to momentarily add then remove a value handle).
  561. for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
  562. Iterator.RemoveFromUseList();
  563. Iterator.AddToExistingUseListAfter(Entry);
  564. assert(Entry->Next == &Iterator && "Loop invariant broken.");
  565. switch (Entry->getKind()) {
  566. case Assert:
  567. break;
  568. case Tracking:
  569. // Mark that this value has been deleted by setting it to an invalid Value
  570. // pointer.
  571. Entry->operator=(DenseMapInfo<Value *>::getTombstoneKey());
  572. break;
  573. case Weak:
  574. // Weak just goes to null, which will unlink it from the list.
  575. Entry->operator=(nullptr);
  576. break;
  577. case Callback:
  578. // Forward to the subclass's implementation.
  579. static_cast<CallbackVH*>(Entry)->deleted();
  580. break;
  581. }
  582. }
  583. // All callbacks, weak references, and assertingVHs should be dropped by now.
  584. if (V->HasValueHandle) {
  585. #ifndef NDEBUG // Only in +Asserts mode...
  586. dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
  587. << "\n";
  588. if (pImpl->ValueHandles[V]->getKind() == Assert)
  589. llvm_unreachable("An asserting value handle still pointed to this"
  590. " value!");
  591. #endif
  592. llvm_unreachable("All references to V were not removed?");
  593. }
  594. }
  595. void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
  596. assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
  597. assert(Old != New && "Changing value into itself!");
  598. assert(Old->getType() == New->getType() &&
  599. "replaceAllUses of value with new value of different type!");
  600. // Get the linked list base, which is guaranteed to exist since the
  601. // HasValueHandle flag is set.
  602. LLVMContextImpl *pImpl = Old->getContext().pImpl;
  603. ValueHandleBase *Entry = pImpl->ValueHandles[Old];
  604. assert(Entry && "Value bit set but no entries exist");
  605. // We use a local ValueHandleBase as an iterator so that
  606. // ValueHandles can add and remove themselves from the list without
  607. // breaking our iteration. This is not really an AssertingVH; we
  608. // just have to give ValueHandleBase some kind.
  609. for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
  610. Iterator.RemoveFromUseList();
  611. Iterator.AddToExistingUseListAfter(Entry);
  612. assert(Entry->Next == &Iterator && "Loop invariant broken.");
  613. switch (Entry->getKind()) {
  614. case Assert:
  615. // Asserting handle does not follow RAUW implicitly.
  616. break;
  617. case Tracking:
  618. // Tracking goes to new value like a WeakVH. Note that this may make it
  619. // something incompatible with its templated type. We don't want to have a
  620. // virtual (or inline) interface to handle this though, so instead we make
  621. // the TrackingVH accessors guarantee that a client never sees this value.
  622. // FALLTHROUGH
  623. case Weak:
  624. // Weak goes to the new value, which will unlink it from Old's list.
  625. Entry->operator=(New);
  626. break;
  627. case Callback:
  628. // Forward to the subclass's implementation.
  629. static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
  630. break;
  631. }
  632. }
  633. #ifndef NDEBUG
  634. // If any new tracking or weak value handles were added while processing the
  635. // list, then complain about it now.
  636. if (Old->HasValueHandle)
  637. for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
  638. switch (Entry->getKind()) {
  639. case Tracking:
  640. case Weak:
  641. dbgs() << "After RAUW from " << *Old->getType() << " %"
  642. << Old->getName() << " to " << *New->getType() << " %"
  643. << New->getName() << "\n";
  644. llvm_unreachable("A tracking or weak value handle still pointed to the"
  645. " old value!\n");
  646. default:
  647. break;
  648. }
  649. #endif
  650. }
  651. // Pin the vtable to this file.
  652. void CallbackVH::anchor() {}