Value.cpp 24 KB

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