Value.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. //===-- Value.cpp - Implement the Value class -----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Value, ValueHandle, and User classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Value.h"
  13. #include "LLVMContextImpl.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/IR/Constant.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/DataLayout.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/DerivedUser.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. static cl::opt<unsigned> NonGlobalValueMaxNameSize(
  38. "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
  39. cl::desc("Maximum size for the name of non-global values."));
  40. //===----------------------------------------------------------------------===//
  41. // Value Class
  42. //===----------------------------------------------------------------------===//
  43. static inline Type *checkType(Type *Ty) {
  44. assert(Ty && "Value defined with a null type: Error!");
  45. return Ty;
  46. }
  47. Value::Value(Type *ty, unsigned scid)
  48. : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
  49. HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
  50. NumUserOperands(0), IsUsedByMD(false), HasName(false) {
  51. static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
  52. // FIXME: Why isn't this in the subclass gunk??
  53. // Note, we cannot call isa<CallInst> before the CallInst has been
  54. // constructed.
  55. if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
  56. SubclassID == Instruction::CallBr)
  57. assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
  58. "invalid CallInst type!");
  59. else if (SubclassID != BasicBlockVal &&
  60. (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
  61. assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
  62. "Cannot create non-first-class values except for constants!");
  63. static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
  64. "Value too big");
  65. }
  66. Value::~Value() {
  67. // Notify all ValueHandles (if present) that this value is going away.
  68. if (HasValueHandle)
  69. ValueHandleBase::ValueIsDeleted(this);
  70. if (isUsedByMetadata())
  71. ValueAsMetadata::handleDeletion(this);
  72. #ifndef NDEBUG // Only in -g mode...
  73. // Check to make sure that there are no uses of this value that are still
  74. // around when the value is destroyed. If there are, then we have a dangling
  75. // reference and something is wrong. This code is here to print out where
  76. // the value is still being referenced.
  77. //
  78. if (!use_empty()) {
  79. dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
  80. for (auto *U : users())
  81. dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
  82. }
  83. #endif
  84. assert(use_empty() && "Uses remain when a value is destroyed!");
  85. // If this value is named, destroy the name. This should not be in a symtab
  86. // at this point.
  87. destroyValueName();
  88. }
  89. void Value::deleteValue() {
  90. switch (getValueID()) {
  91. #define HANDLE_VALUE(Name) \
  92. case Value::Name##Val: \
  93. delete static_cast<Name *>(this); \
  94. break;
  95. #define HANDLE_MEMORY_VALUE(Name) \
  96. case Value::Name##Val: \
  97. static_cast<DerivedUser *>(this)->DeleteValue( \
  98. static_cast<DerivedUser *>(this)); \
  99. break;
  100. #define HANDLE_INSTRUCTION(Name) /* nothing */
  101. #include "llvm/IR/Value.def"
  102. #define HANDLE_INST(N, OPC, CLASS) \
  103. case Value::InstructionVal + Instruction::OPC: \
  104. delete static_cast<CLASS *>(this); \
  105. break;
  106. #define HANDLE_USER_INST(N, OPC, CLASS)
  107. #include "llvm/IR/Instruction.def"
  108. default:
  109. llvm_unreachable("attempting to delete unknown value kind");
  110. }
  111. }
  112. void Value::destroyValueName() {
  113. ValueName *Name = getValueName();
  114. if (Name)
  115. Name->Destroy();
  116. setValueName(nullptr);
  117. }
  118. bool Value::hasNUses(unsigned N) const {
  119. return hasNItems(use_begin(), use_end(), N);
  120. }
  121. bool Value::hasNUsesOrMore(unsigned N) const {
  122. return hasNItemsOrMore(use_begin(), use_end(), N);
  123. }
  124. bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
  125. // This can be computed either by scanning the instructions in BB, or by
  126. // scanning the use list of this Value. Both lists can be very long, but
  127. // usually one is quite short.
  128. //
  129. // Scan both lists simultaneously until one is exhausted. This limits the
  130. // search to the shorter list.
  131. BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
  132. const_user_iterator UI = user_begin(), UE = user_end();
  133. for (; BI != BE && UI != UE; ++BI, ++UI) {
  134. // Scan basic block: Check if this Value is used by the instruction at BI.
  135. if (is_contained(BI->operands(), this))
  136. return true;
  137. // Scan use list: Check if the use at UI is in BB.
  138. const auto *User = dyn_cast<Instruction>(*UI);
  139. if (User && User->getParent() == BB)
  140. return true;
  141. }
  142. return false;
  143. }
  144. unsigned Value::getNumUses() const {
  145. return (unsigned)std::distance(use_begin(), use_end());
  146. }
  147. static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
  148. ST = nullptr;
  149. if (Instruction *I = dyn_cast<Instruction>(V)) {
  150. if (BasicBlock *P = I->getParent())
  151. if (Function *PP = P->getParent())
  152. ST = PP->getValueSymbolTable();
  153. } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
  154. if (Function *P = BB->getParent())
  155. ST = P->getValueSymbolTable();
  156. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  157. if (Module *P = GV->getParent())
  158. ST = &P->getValueSymbolTable();
  159. } else if (Argument *A = dyn_cast<Argument>(V)) {
  160. if (Function *P = A->getParent())
  161. ST = P->getValueSymbolTable();
  162. } else {
  163. assert(isa<Constant>(V) && "Unknown value type!");
  164. return true; // no name is setable for this.
  165. }
  166. return false;
  167. }
  168. ValueName *Value::getValueName() const {
  169. if (!HasName) return nullptr;
  170. LLVMContext &Ctx = getContext();
  171. auto I = Ctx.pImpl->ValueNames.find(this);
  172. assert(I != Ctx.pImpl->ValueNames.end() &&
  173. "No name entry found!");
  174. return I->second;
  175. }
  176. void Value::setValueName(ValueName *VN) {
  177. LLVMContext &Ctx = getContext();
  178. assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
  179. "HasName bit out of sync!");
  180. if (!VN) {
  181. if (HasName)
  182. Ctx.pImpl->ValueNames.erase(this);
  183. HasName = false;
  184. return;
  185. }
  186. HasName = true;
  187. Ctx.pImpl->ValueNames[this] = VN;
  188. }
  189. StringRef Value::getName() const {
  190. // Make sure the empty string is still a C string. For historical reasons,
  191. // some clients want to call .data() on the result and expect it to be null
  192. // terminated.
  193. if (!hasName())
  194. return StringRef("", 0);
  195. return getValueName()->getKey();
  196. }
  197. void Value::setNameImpl(const Twine &NewName) {
  198. // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
  199. if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
  200. return;
  201. // Fast path for common IRBuilder case of setName("") when there is no name.
  202. if (NewName.isTriviallyEmpty() && !hasName())
  203. return;
  204. SmallString<256> NameData;
  205. StringRef NameRef = NewName.toStringRef(NameData);
  206. assert(NameRef.find_first_of(0) == StringRef::npos &&
  207. "Null bytes are not allowed in names");
  208. // Name isn't changing?
  209. if (getName() == NameRef)
  210. return;
  211. // Cap the size of non-GlobalValue names.
  212. if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
  213. NameRef =
  214. NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
  215. assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
  216. // Get the symbol table to update for this object.
  217. ValueSymbolTable *ST;
  218. if (getSymTab(this, ST))
  219. return; // Cannot set a name on this value (e.g. constant).
  220. if (!ST) { // No symbol table to update? Just do the change.
  221. if (NameRef.empty()) {
  222. // Free the name for this value.
  223. destroyValueName();
  224. return;
  225. }
  226. // NOTE: Could optimize for the case the name is shrinking to not deallocate
  227. // then reallocated.
  228. destroyValueName();
  229. // Create the new name.
  230. setValueName(ValueName::Create(NameRef));
  231. getValueName()->setValue(this);
  232. return;
  233. }
  234. // NOTE: Could optimize for the case the name is shrinking to not deallocate
  235. // then reallocated.
  236. if (hasName()) {
  237. // Remove old name.
  238. ST->removeValueName(getValueName());
  239. destroyValueName();
  240. if (NameRef.empty())
  241. return;
  242. }
  243. // Name is changing to something new.
  244. setValueName(ST->createValueName(NameRef, this));
  245. }
  246. void Value::setName(const Twine &NewName) {
  247. setNameImpl(NewName);
  248. if (Function *F = dyn_cast<Function>(this))
  249. F->recalculateIntrinsicID();
  250. }
  251. void Value::takeName(Value *V) {
  252. ValueSymbolTable *ST = nullptr;
  253. // If this value has a name, drop it.
  254. if (hasName()) {
  255. // Get the symtab this is in.
  256. if (getSymTab(this, ST)) {
  257. // We can't set a name on this value, but we need to clear V's name if
  258. // it has one.
  259. if (V->hasName()) V->setName("");
  260. return; // Cannot set a name on this value (e.g. constant).
  261. }
  262. // Remove old name.
  263. if (ST)
  264. ST->removeValueName(getValueName());
  265. destroyValueName();
  266. }
  267. // Now we know that this has no name.
  268. // If V has no name either, we're done.
  269. if (!V->hasName()) return;
  270. // Get this's symtab if we didn't before.
  271. if (!ST) {
  272. if (getSymTab(this, ST)) {
  273. // Clear V's name.
  274. V->setName("");
  275. return; // Cannot set a name on this value (e.g. constant).
  276. }
  277. }
  278. // Get V's ST, this should always succed, because V has a name.
  279. ValueSymbolTable *VST;
  280. bool Failure = getSymTab(V, VST);
  281. assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
  282. // If these values are both in the same symtab, we can do this very fast.
  283. // This works even if both values have no symtab yet.
  284. if (ST == VST) {
  285. // Take the name!
  286. setValueName(V->getValueName());
  287. V->setValueName(nullptr);
  288. getValueName()->setValue(this);
  289. return;
  290. }
  291. // Otherwise, things are slightly more complex. Remove V's name from VST and
  292. // then reinsert it into ST.
  293. if (VST)
  294. VST->removeValueName(V->getValueName());
  295. setValueName(V->getValueName());
  296. V->setValueName(nullptr);
  297. getValueName()->setValue(this);
  298. if (ST)
  299. ST->reinsertValue(this);
  300. }
  301. void Value::assertModuleIsMaterializedImpl() const {
  302. #ifndef NDEBUG
  303. const GlobalValue *GV = dyn_cast<GlobalValue>(this);
  304. if (!GV)
  305. return;
  306. const Module *M = GV->getParent();
  307. if (!M)
  308. return;
  309. assert(M->isMaterialized());
  310. #endif
  311. }
  312. #ifndef NDEBUG
  313. static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
  314. Constant *C) {
  315. if (!Cache.insert(Expr).second)
  316. return false;
  317. for (auto &O : Expr->operands()) {
  318. if (O == C)
  319. return true;
  320. auto *CE = dyn_cast<ConstantExpr>(O);
  321. if (!CE)
  322. continue;
  323. if (contains(Cache, CE, C))
  324. return true;
  325. }
  326. return false;
  327. }
  328. static bool contains(Value *Expr, Value *V) {
  329. if (Expr == V)
  330. return true;
  331. auto *C = dyn_cast<Constant>(V);
  332. if (!C)
  333. return false;
  334. auto *CE = dyn_cast<ConstantExpr>(Expr);
  335. if (!CE)
  336. return false;
  337. SmallPtrSet<ConstantExpr *, 4> Cache;
  338. return contains(Cache, CE, C);
  339. }
  340. #endif // NDEBUG
  341. void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
  342. assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
  343. assert(!contains(New, this) &&
  344. "this->replaceAllUsesWith(expr(this)) is NOT valid!");
  345. assert(New->getType() == getType() &&
  346. "replaceAllUses of value with new value of different type!");
  347. // Notify all ValueHandles (if present) that this value is going away.
  348. if (HasValueHandle)
  349. ValueHandleBase::ValueIsRAUWd(this, New);
  350. if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
  351. ValueAsMetadata::handleRAUW(this, New);
  352. while (!materialized_use_empty()) {
  353. Use &U = *UseList;
  354. // Must handle Constants specially, we cannot call replaceUsesOfWith on a
  355. // constant because they are uniqued.
  356. if (auto *C = dyn_cast<Constant>(U.getUser())) {
  357. if (!isa<GlobalValue>(C)) {
  358. C->handleOperandChange(this, New);
  359. continue;
  360. }
  361. }
  362. U.set(New);
  363. }
  364. if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
  365. BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
  366. }
  367. void Value::replaceAllUsesWith(Value *New) {
  368. doRAUW(New, ReplaceMetadataUses::Yes);
  369. }
  370. void Value::replaceNonMetadataUsesWith(Value *New) {
  371. doRAUW(New, ReplaceMetadataUses::No);
  372. }
  373. // Like replaceAllUsesWith except it does not handle constants or basic blocks.
  374. // This routine leaves uses within BB.
  375. void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
  376. assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
  377. assert(!contains(New, this) &&
  378. "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
  379. assert(New->getType() == getType() &&
  380. "replaceUses of value with new value of different type!");
  381. assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
  382. replaceUsesWithIf(New, [BB](Use &U) {
  383. auto *I = dyn_cast<Instruction>(U.getUser());
  384. // Don't replace if it's an instruction in the BB basic block.
  385. return !I || I->getParent() != BB;
  386. });
  387. }
  388. namespace {
  389. // Various metrics for how much to strip off of pointers.
  390. enum PointerStripKind {
  391. PSK_ZeroIndices,
  392. PSK_ZeroIndicesSameRepresentation,
  393. PSK_ZeroIndicesAndInvariantGroups,
  394. PSK_InBoundsConstantIndices,
  395. PSK_InBounds
  396. };
  397. template <PointerStripKind StripKind>
  398. static const Value *stripPointerCastsAndOffsets(const Value *V) {
  399. if (!V->getType()->isPointerTy())
  400. return V;
  401. // Even though we don't look through PHI nodes, we could be called on an
  402. // instruction in an unreachable block, which may be on a cycle.
  403. SmallPtrSet<const Value *, 4> Visited;
  404. Visited.insert(V);
  405. do {
  406. if (auto *GEP = dyn_cast<GEPOperator>(V)) {
  407. switch (StripKind) {
  408. case PSK_ZeroIndices:
  409. case PSK_ZeroIndicesSameRepresentation:
  410. case PSK_ZeroIndicesAndInvariantGroups:
  411. if (!GEP->hasAllZeroIndices())
  412. return V;
  413. break;
  414. case PSK_InBoundsConstantIndices:
  415. if (!GEP->hasAllConstantIndices())
  416. return V;
  417. LLVM_FALLTHROUGH;
  418. case PSK_InBounds:
  419. if (!GEP->isInBounds())
  420. return V;
  421. break;
  422. }
  423. V = GEP->getPointerOperand();
  424. } else if (Operator::getOpcode(V) == Instruction::BitCast) {
  425. V = cast<Operator>(V)->getOperand(0);
  426. } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
  427. Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
  428. // TODO: If we know an address space cast will not change the
  429. // representation we could look through it here as well.
  430. V = cast<Operator>(V)->getOperand(0);
  431. } else {
  432. if (const auto *Call = dyn_cast<CallBase>(V)) {
  433. if (const Value *RV = Call->getReturnedArgOperand()) {
  434. V = RV;
  435. continue;
  436. }
  437. // The result of launder.invariant.group must alias it's argument,
  438. // but it can't be marked with returned attribute, that's why it needs
  439. // special case.
  440. if (StripKind == PSK_ZeroIndicesAndInvariantGroups &&
  441. (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
  442. Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
  443. V = Call->getArgOperand(0);
  444. continue;
  445. }
  446. }
  447. return V;
  448. }
  449. assert(V->getType()->isPointerTy() && "Unexpected operand type!");
  450. } while (Visited.insert(V).second);
  451. return V;
  452. }
  453. } // end anonymous namespace
  454. const Value *Value::stripPointerCasts() const {
  455. return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
  456. }
  457. const Value *Value::stripPointerCastsSameRepresentation() const {
  458. return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
  459. }
  460. const Value *Value::stripInBoundsConstantOffsets() const {
  461. return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
  462. }
  463. const Value *Value::stripPointerCastsAndInvariantGroups() const {
  464. return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this);
  465. }
  466. const Value *
  467. Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
  468. bool AllowNonInbounds) const {
  469. if (!getType()->isPtrOrPtrVectorTy())
  470. return this;
  471. unsigned BitWidth = Offset.getBitWidth();
  472. assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
  473. "The offset bit width does not match the DL specification.");
  474. // Even though we don't look through PHI nodes, we could be called on an
  475. // instruction in an unreachable block, which may be on a cycle.
  476. SmallPtrSet<const Value *, 4> Visited;
  477. Visited.insert(this);
  478. const Value *V = this;
  479. do {
  480. if (auto *GEP = dyn_cast<GEPOperator>(V)) {
  481. // If in-bounds was requested, we do not strip non-in-bounds GEPs.
  482. if (!AllowNonInbounds && !GEP->isInBounds())
  483. return V;
  484. // If one of the values we have visited is an addrspacecast, then
  485. // the pointer type of this GEP may be different from the type
  486. // of the Ptr parameter which was passed to this function. This
  487. // means when we construct GEPOffset, we need to use the size
  488. // of GEP's pointer type rather than the size of the original
  489. // pointer type.
  490. APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
  491. if (!GEP->accumulateConstantOffset(DL, GEPOffset))
  492. return V;
  493. // Stop traversal if the pointer offset wouldn't fit in the bit-width
  494. // provided by the Offset argument. This can happen due to AddrSpaceCast
  495. // stripping.
  496. if (GEPOffset.getMinSignedBits() > BitWidth)
  497. return V;
  498. Offset += GEPOffset.sextOrTrunc(BitWidth);
  499. V = GEP->getPointerOperand();
  500. } else if (Operator::getOpcode(V) == Instruction::BitCast ||
  501. Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
  502. V = cast<Operator>(V)->getOperand(0);
  503. } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
  504. if (!GA->isInterposable())
  505. V = GA->getAliasee();
  506. } else if (const auto *Call = dyn_cast<CallBase>(V)) {
  507. if (const Value *RV = Call->getReturnedArgOperand())
  508. V = RV;
  509. }
  510. assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
  511. } while (Visited.insert(V).second);
  512. return V;
  513. }
  514. const Value *Value::stripInBoundsOffsets() const {
  515. return stripPointerCastsAndOffsets<PSK_InBounds>(this);
  516. }
  517. uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
  518. bool &CanBeNull) const {
  519. assert(getType()->isPointerTy() && "must be pointer");
  520. uint64_t DerefBytes = 0;
  521. CanBeNull = false;
  522. if (const Argument *A = dyn_cast<Argument>(this)) {
  523. DerefBytes = A->getDereferenceableBytes();
  524. if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
  525. Type *PT = cast<PointerType>(A->getType())->getElementType();
  526. if (PT->isSized())
  527. DerefBytes = DL.getTypeStoreSize(PT);
  528. }
  529. if (DerefBytes == 0) {
  530. DerefBytes = A->getDereferenceableOrNullBytes();
  531. CanBeNull = true;
  532. }
  533. } else if (const auto *Call = dyn_cast<CallBase>(this)) {
  534. DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
  535. if (DerefBytes == 0) {
  536. DerefBytes =
  537. Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
  538. CanBeNull = true;
  539. }
  540. } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
  541. if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
  542. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  543. DerefBytes = CI->getLimitedValue();
  544. }
  545. if (DerefBytes == 0) {
  546. if (MDNode *MD =
  547. LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
  548. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  549. DerefBytes = CI->getLimitedValue();
  550. }
  551. CanBeNull = true;
  552. }
  553. } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
  554. if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
  555. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  556. DerefBytes = CI->getLimitedValue();
  557. }
  558. if (DerefBytes == 0) {
  559. if (MDNode *MD =
  560. IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
  561. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  562. DerefBytes = CI->getLimitedValue();
  563. }
  564. CanBeNull = true;
  565. }
  566. } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
  567. if (!AI->isArrayAllocation()) {
  568. DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
  569. CanBeNull = false;
  570. }
  571. } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
  572. if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
  573. // TODO: Don't outright reject hasExternalWeakLinkage but set the
  574. // CanBeNull flag.
  575. DerefBytes = DL.getTypeStoreSize(GV->getValueType());
  576. CanBeNull = false;
  577. }
  578. }
  579. return DerefBytes;
  580. }
  581. unsigned Value::getPointerAlignment(const DataLayout &DL) const {
  582. assert(getType()->isPointerTy() && "must be pointer");
  583. unsigned Align = 0;
  584. if (auto *GO = dyn_cast<GlobalObject>(this)) {
  585. if (isa<Function>(GO)) {
  586. MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign();
  587. unsigned Align = FunctionPtrAlign ? FunctionPtrAlign->value() : 0;
  588. switch (DL.getFunctionPtrAlignType()) {
  589. case DataLayout::FunctionPtrAlignType::Independent:
  590. return Align;
  591. case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
  592. return std::max(Align, GO->getAlignment());
  593. }
  594. }
  595. Align = GO->getAlignment();
  596. if (Align == 0) {
  597. if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
  598. Type *ObjectType = GVar->getValueType();
  599. if (ObjectType->isSized()) {
  600. // If the object is defined in the current Module, we'll be giving
  601. // it the preferred alignment. Otherwise, we have to assume that it
  602. // may only have the minimum ABI alignment.
  603. if (GVar->isStrongDefinitionForLinker())
  604. Align = DL.getPreferredAlignment(GVar);
  605. else
  606. Align = DL.getABITypeAlignment(ObjectType);
  607. }
  608. }
  609. }
  610. } else if (const Argument *A = dyn_cast<Argument>(this)) {
  611. Align = A->getParamAlignment();
  612. if (!Align && A->hasStructRetAttr()) {
  613. // An sret parameter has at least the ABI alignment of the return type.
  614. Type *EltTy = cast<PointerType>(A->getType())->getElementType();
  615. if (EltTy->isSized())
  616. Align = DL.getABITypeAlignment(EltTy);
  617. }
  618. } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
  619. Align = AI->getAlignment();
  620. if (Align == 0) {
  621. Type *AllocatedType = AI->getAllocatedType();
  622. if (AllocatedType->isSized())
  623. Align = DL.getPrefTypeAlignment(AllocatedType);
  624. }
  625. } else if (const auto *Call = dyn_cast<CallBase>(this)) {
  626. Align = Call->getRetAlignment();
  627. if (Align == 0 && Call->getCalledFunction())
  628. Align = Call->getCalledFunction()->getAttributes().getRetAlignment();
  629. } else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
  630. if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
  631. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
  632. Align = CI->getLimitedValue();
  633. }
  634. return Align;
  635. }
  636. const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
  637. const BasicBlock *PredBB) const {
  638. auto *PN = dyn_cast<PHINode>(this);
  639. if (PN && PN->getParent() == CurBB)
  640. return PN->getIncomingValueForBlock(PredBB);
  641. return this;
  642. }
  643. LLVMContext &Value::getContext() const { return VTy->getContext(); }
  644. void Value::reverseUseList() {
  645. if (!UseList || !UseList->Next)
  646. // No need to reverse 0 or 1 uses.
  647. return;
  648. Use *Head = UseList;
  649. Use *Current = UseList->Next;
  650. Head->Next = nullptr;
  651. while (Current) {
  652. Use *Next = Current->Next;
  653. Current->Next = Head;
  654. Head->setPrev(&Current->Next);
  655. Head = Current;
  656. Current = Next;
  657. }
  658. UseList = Head;
  659. Head->setPrev(&UseList);
  660. }
  661. bool Value::isSwiftError() const {
  662. auto *Arg = dyn_cast<Argument>(this);
  663. if (Arg)
  664. return Arg->hasSwiftErrorAttr();
  665. auto *Alloca = dyn_cast<AllocaInst>(this);
  666. if (!Alloca)
  667. return false;
  668. return Alloca->isSwiftError();
  669. }
  670. //===----------------------------------------------------------------------===//
  671. // ValueHandleBase Class
  672. //===----------------------------------------------------------------------===//
  673. void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
  674. assert(List && "Handle list is null?");
  675. // Splice ourselves into the list.
  676. Next = *List;
  677. *List = this;
  678. setPrevPtr(List);
  679. if (Next) {
  680. Next->setPrevPtr(&Next);
  681. assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
  682. }
  683. }
  684. void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
  685. assert(List && "Must insert after existing node");
  686. Next = List->Next;
  687. setPrevPtr(&List->Next);
  688. List->Next = this;
  689. if (Next)
  690. Next->setPrevPtr(&Next);
  691. }
  692. void ValueHandleBase::AddToUseList() {
  693. assert(getValPtr() && "Null pointer doesn't have a use list!");
  694. LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
  695. if (getValPtr()->HasValueHandle) {
  696. // If this value already has a ValueHandle, then it must be in the
  697. // ValueHandles map already.
  698. ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
  699. assert(Entry && "Value doesn't have any handles?");
  700. AddToExistingUseList(&Entry);
  701. return;
  702. }
  703. // Ok, it doesn't have any handles yet, so we must insert it into the
  704. // DenseMap. However, doing this insertion could cause the DenseMap to
  705. // reallocate itself, which would invalidate all of the PrevP pointers that
  706. // point into the old table. Handle this by checking for reallocation and
  707. // updating the stale pointers only if needed.
  708. DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
  709. const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
  710. ValueHandleBase *&Entry = Handles[getValPtr()];
  711. assert(!Entry && "Value really did already have handles?");
  712. AddToExistingUseList(&Entry);
  713. getValPtr()->HasValueHandle = true;
  714. // If reallocation didn't happen or if this was the first insertion, don't
  715. // walk the table.
  716. if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
  717. Handles.size() == 1) {
  718. return;
  719. }
  720. // Okay, reallocation did happen. Fix the Prev Pointers.
  721. for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
  722. E = Handles.end(); I != E; ++I) {
  723. assert(I->second && I->first == I->second->getValPtr() &&
  724. "List invariant broken!");
  725. I->second->setPrevPtr(&I->second);
  726. }
  727. }
  728. void ValueHandleBase::RemoveFromUseList() {
  729. assert(getValPtr() && getValPtr()->HasValueHandle &&
  730. "Pointer doesn't have a use list!");
  731. // Unlink this from its use list.
  732. ValueHandleBase **PrevPtr = getPrevPtr();
  733. assert(*PrevPtr == this && "List invariant broken");
  734. *PrevPtr = Next;
  735. if (Next) {
  736. assert(Next->getPrevPtr() == &Next && "List invariant broken");
  737. Next->setPrevPtr(PrevPtr);
  738. return;
  739. }
  740. // If the Next pointer was null, then it is possible that this was the last
  741. // ValueHandle watching VP. If so, delete its entry from the ValueHandles
  742. // map.
  743. LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
  744. DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
  745. if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
  746. Handles.erase(getValPtr());
  747. getValPtr()->HasValueHandle = false;
  748. }
  749. }
  750. void ValueHandleBase::ValueIsDeleted(Value *V) {
  751. assert(V->HasValueHandle && "Should only be called if ValueHandles present");
  752. // Get the linked list base, which is guaranteed to exist since the
  753. // HasValueHandle flag is set.
  754. LLVMContextImpl *pImpl = V->getContext().pImpl;
  755. ValueHandleBase *Entry = pImpl->ValueHandles[V];
  756. assert(Entry && "Value bit set but no entries exist");
  757. // We use a local ValueHandleBase as an iterator so that ValueHandles can add
  758. // and remove themselves from the list without breaking our iteration. This
  759. // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
  760. // Note that we deliberately do not the support the case when dropping a value
  761. // handle results in a new value handle being permanently added to the list
  762. // (as might occur in theory for CallbackVH's): the new value handle will not
  763. // be processed and the checking code will mete out righteous punishment if
  764. // the handle is still present once we have finished processing all the other
  765. // value handles (it is fine to momentarily add then remove a value handle).
  766. for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
  767. Iterator.RemoveFromUseList();
  768. Iterator.AddToExistingUseListAfter(Entry);
  769. assert(Entry->Next == &Iterator && "Loop invariant broken.");
  770. switch (Entry->getKind()) {
  771. case Assert:
  772. break;
  773. case Weak:
  774. case WeakTracking:
  775. // WeakTracking and Weak just go to null, which unlinks them
  776. // from the list.
  777. Entry->operator=(nullptr);
  778. break;
  779. case Callback:
  780. // Forward to the subclass's implementation.
  781. static_cast<CallbackVH*>(Entry)->deleted();
  782. break;
  783. }
  784. }
  785. // All callbacks, weak references, and assertingVHs should be dropped by now.
  786. if (V->HasValueHandle) {
  787. #ifndef NDEBUG // Only in +Asserts mode...
  788. dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
  789. << "\n";
  790. if (pImpl->ValueHandles[V]->getKind() == Assert)
  791. llvm_unreachable("An asserting value handle still pointed to this"
  792. " value!");
  793. #endif
  794. llvm_unreachable("All references to V were not removed?");
  795. }
  796. }
  797. void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
  798. assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
  799. assert(Old != New && "Changing value into itself!");
  800. assert(Old->getType() == New->getType() &&
  801. "replaceAllUses of value with new value of different type!");
  802. // Get the linked list base, which is guaranteed to exist since the
  803. // HasValueHandle flag is set.
  804. LLVMContextImpl *pImpl = Old->getContext().pImpl;
  805. ValueHandleBase *Entry = pImpl->ValueHandles[Old];
  806. assert(Entry && "Value bit set but no entries exist");
  807. // We use a local ValueHandleBase as an iterator so that
  808. // ValueHandles can add and remove themselves from the list without
  809. // breaking our iteration. This is not really an AssertingVH; we
  810. // just have to give ValueHandleBase some kind.
  811. for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
  812. Iterator.RemoveFromUseList();
  813. Iterator.AddToExistingUseListAfter(Entry);
  814. assert(Entry->Next == &Iterator && "Loop invariant broken.");
  815. switch (Entry->getKind()) {
  816. case Assert:
  817. case Weak:
  818. // Asserting and Weak handles do not follow RAUW implicitly.
  819. break;
  820. case WeakTracking:
  821. // Weak goes to the new value, which will unlink it from Old's list.
  822. Entry->operator=(New);
  823. break;
  824. case Callback:
  825. // Forward to the subclass's implementation.
  826. static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
  827. break;
  828. }
  829. }
  830. #ifndef NDEBUG
  831. // If any new weak value handles were added while processing the
  832. // list, then complain about it now.
  833. if (Old->HasValueHandle)
  834. for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
  835. switch (Entry->getKind()) {
  836. case WeakTracking:
  837. dbgs() << "After RAUW from " << *Old->getType() << " %"
  838. << Old->getName() << " to " << *New->getType() << " %"
  839. << New->getName() << "\n";
  840. llvm_unreachable(
  841. "A weak tracking value handle still pointed to the old value!\n");
  842. default:
  843. break;
  844. }
  845. #endif
  846. }
  847. // Pin the vtable to this file.
  848. void CallbackVH::anchor() {}