xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 9430efa1)
1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===//
2ef860a24SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ef860a24SChandler Carruth //
7ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
8ef860a24SChandler Carruth //
9ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes.
10ef860a24SChandler Carruth //
11ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
12ef860a24SChandler Carruth 
139fb823bbSChandler Carruth #include "llvm/IR/Value.h"
14ef860a24SChandler Carruth #include "LLVMContextImpl.h"
15ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h"
162f2ace98SDmitry Mikulin #include "llvm/ADT/SetVector.h"
174c1a1d3cSReid Kleckner #include "llvm/ADT/SmallString.h"
189fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
202e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
21bbccdf6fSOCHyams #include "llvm/IR/DebugInfo.h"
229fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2396ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h"
2403eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
259fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
269fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
27a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h"
289fb823bbSChandler Carruth #include "llvm/IR/Module.h"
299fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
304220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
319fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h"
324c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
33ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
34ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
35ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
36799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
37ef860a24SChandler Carruth #include <algorithm>
38ecefe5a8SEugene Zelenko 
39ef860a24SChandler Carruth using namespace llvm;
40ef860a24SChandler Carruth 
415698537fSPhilip Reames static cl::opt<unsigned> UseDerefAtPointSemantics(
425698537fSPhilip Reames     "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false),
435698537fSPhilip Reames     cl::desc("Deref attributes and metadata infer facts at definition only"));
445698537fSPhilip Reames 
455698537fSPhilip Reames 
464c975578SSerge Guelton static cl::opt<unsigned> NonGlobalValueMaxNameSize(
474c975578SSerge Guelton     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
484c975578SSerge Guelton     cl::desc("Maximum size for the name of non-global values."));
494c975578SSerge Guelton 
50ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
51ef860a24SChandler Carruth //                                Value Class
52ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
53ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
54ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
5516bf89ecSReid Kleckner   return Ty;
56ef860a24SChandler Carruth }
57ef860a24SChandler Carruth 
58ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
597975b8c3SSerge Pavlov     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0),
607975b8c3SSerge Pavlov       SubclassOptionalData(0), SubclassData(0), NumUserOperands(0),
617975b8c3SSerge Pavlov       IsUsedByMD(false), HasName(false), HasMetadata(false) {
629fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
63ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
64ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
65ef860a24SChandler Carruth   // constructed.
66784929d0SCraig Topper   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
67784929d0SCraig Topper       SubclassID == Instruction::CallBr)
68ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
69ef860a24SChandler Carruth            "invalid CallInst type!");
70ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
719fd33f24SSerge Guelton            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
72ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
73ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
7496ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
751762ad3eSReid Kleckner                 "Value too big");
76ef860a24SChandler Carruth }
77ef860a24SChandler Carruth 
78ef860a24SChandler Carruth Value::~Value() {
79ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
80ef860a24SChandler Carruth   if (HasValueHandle)
81ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
825bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
835bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
84ef860a24SChandler Carruth 
857975b8c3SSerge Pavlov   // Remove associated metadata from context.
867975b8c3SSerge Pavlov   if (HasMetadata)
877975b8c3SSerge Pavlov     clearMetadata();
887975b8c3SSerge Pavlov 
89ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
90ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
91ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
92b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
93b93fb82bSAndrew Kaylor   // the value is still being referenced.
94ef860a24SChandler Carruth   //
957dd28109SEvgenii Stepanov   // Note that use_empty() cannot be called here, as it eventually downcasts
967dd28109SEvgenii Stepanov   // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
977dd28109SEvgenii Stepanov   // been destructed, so accessing it is UB.
987dd28109SEvgenii Stepanov   //
997dd28109SEvgenii Stepanov   if (!materialized_use_empty()) {
100ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
101b93fb82bSAndrew Kaylor     for (auto *U : users())
102b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
103ef860a24SChandler Carruth   }
104ef860a24SChandler Carruth #endif
1057dd28109SEvgenii Stepanov   assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
106ef860a24SChandler Carruth 
107ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
108ef860a24SChandler Carruth   // at this point.
1095bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
110ef860a24SChandler Carruth }
111ef860a24SChandler Carruth 
11296ab8726SReid Kleckner void Value::deleteValue() {
11396ab8726SReid Kleckner   switch (getValueID()) {
11496ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
11596ab8726SReid Kleckner   case Value::Name##Val:                                                       \
11696ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
11796ab8726SReid Kleckner     break;
11896ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
11996ab8726SReid Kleckner   case Value::Name##Val:                                                       \
12096ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
12196ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
12296ab8726SReid Kleckner     break;
12315440191SEli Friedman #define HANDLE_CONSTANT(Name)                                                  \
12415440191SEli Friedman   case Value::Name##Val:                                                       \
12515440191SEli Friedman     llvm_unreachable("constants should be destroyed with destroyConstant");    \
12615440191SEli Friedman     break;
12796ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
12896ab8726SReid Kleckner #include "llvm/IR/Value.def"
12996ab8726SReid Kleckner 
13096ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
13196ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
13296ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
13396ab8726SReid Kleckner     break;
13496ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
13596ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
13696ab8726SReid Kleckner 
13796ab8726SReid Kleckner   default:
13896ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
13996ab8726SReid Kleckner   }
14096ab8726SReid Kleckner }
14196ab8726SReid Kleckner 
1425bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1435bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
14489c8ffd5SChris Lattner   if (Name) {
14589c8ffd5SChris Lattner     MallocAllocator Allocator;
14689c8ffd5SChris Lattner     Name->Destroy(Allocator);
14789c8ffd5SChris Lattner   }
1485bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1495bf8fef5SDuncan P. N. Exon Smith }
1505bf8fef5SDuncan P. N. Exon Smith 
151ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
1524de31bbaSVedant Kumar   return hasNItems(use_begin(), use_end(), N);
153ef860a24SChandler Carruth }
154ef860a24SChandler Carruth 
155ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
1564de31bbaSVedant Kumar   return hasNItemsOrMore(use_begin(), use_end(), N);
157ef860a24SChandler Carruth }
158ef860a24SChandler Carruth 
15995848ea1SRoman Lebedev bool Value::hasOneUser() const {
16095848ea1SRoman Lebedev   if (use_empty())
16195848ea1SRoman Lebedev     return false;
16295848ea1SRoman Lebedev   if (hasOneUse())
16395848ea1SRoman Lebedev     return true;
16495848ea1SRoman Lebedev   return std::equal(++user_begin(), user_end(), user_begin());
16595848ea1SRoman Lebedev }
16695848ea1SRoman Lebedev 
167f16f139dSTyker static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
168f16f139dSTyker 
169f16f139dSTyker Use *Value::getSingleUndroppableUse() {
170f16f139dSTyker   Use *Result = nullptr;
171f16f139dSTyker   for (Use &U : uses()) {
172f16f139dSTyker     if (!U.getUser()->isDroppable()) {
173f16f139dSTyker       if (Result)
174f16f139dSTyker         return nullptr;
175f16f139dSTyker       Result = &U;
176f16f139dSTyker     }
177f16f139dSTyker   }
178f16f139dSTyker   return Result;
179f16f139dSTyker }
180f16f139dSTyker 
181f16f139dSTyker bool Value::hasNUndroppableUses(unsigned int N) const {
182f16f139dSTyker   return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
183f16f139dSTyker }
184f16f139dSTyker 
185f16f139dSTyker bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
186f16f139dSTyker   return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
187f16f139dSTyker }
188f16f139dSTyker 
189f16f139dSTyker void Value::dropDroppableUses(
190f16f139dSTyker     llvm::function_ref<bool(const Use *)> ShouldDrop) {
191f16f139dSTyker   SmallVector<Use *, 8> ToBeEdited;
192f16f139dSTyker   for (Use &U : uses())
193f16f139dSTyker     if (U.getUser()->isDroppable() && ShouldDrop(&U))
194f16f139dSTyker       ToBeEdited.push_back(&U);
195450dc09dSJohannes Doerfert   for (Use *U : ToBeEdited)
196450dc09dSJohannes Doerfert     dropDroppableUse(*U);
197f16f139dSTyker }
198450dc09dSJohannes Doerfert 
199450dc09dSJohannes Doerfert void Value::dropDroppableUsesIn(User &Usr) {
200450dc09dSJohannes Doerfert   assert(Usr.isDroppable() && "Expected a droppable user!");
201450dc09dSJohannes Doerfert   for (Use &UsrOp : Usr.operands()) {
202450dc09dSJohannes Doerfert     if (UsrOp.get() == this)
203450dc09dSJohannes Doerfert       dropDroppableUse(UsrOp);
204f16f139dSTyker   }
205f16f139dSTyker }
206f16f139dSTyker 
207450dc09dSJohannes Doerfert void Value::dropDroppableUse(Use &U) {
208450dc09dSJohannes Doerfert   U.removeFromList();
209908215b3SPhilip Reames   if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) {
210450dc09dSJohannes Doerfert     unsigned OpNo = U.getOperandNo();
211450dc09dSJohannes Doerfert     if (OpNo == 0)
212450dc09dSJohannes Doerfert       U.set(ConstantInt::getTrue(Assume->getContext()));
213450dc09dSJohannes Doerfert     else {
214450dc09dSJohannes Doerfert       U.set(UndefValue::get(U.get()->getType()));
215450dc09dSJohannes Doerfert       CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
2166d365741STyker       BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
217450dc09dSJohannes Doerfert     }
218450dc09dSJohannes Doerfert     return;
219450dc09dSJohannes Doerfert   }
220450dc09dSJohannes Doerfert 
221450dc09dSJohannes Doerfert   llvm_unreachable("unkown droppable use");
222ce8928f2SJohannes Doerfert }
223ce8928f2SJohannes Doerfert 
224ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
2250925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
2260925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
2270925b24dSJakob Stoklund Olesen   // usually one is quite short.
2280925b24dSJakob Stoklund Olesen   //
2290925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
2300925b24dSJakob Stoklund Olesen   // search to the shorter list.
2310925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
232cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
2330925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
2340925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
23542531260SDavid Majnemer     if (is_contained(BI->operands(), this))
236ef860a24SChandler Carruth       return true;
2370925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
23842531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
239ef860a24SChandler Carruth     if (User && User->getParent() == BB)
240ef860a24SChandler Carruth       return true;
241ef860a24SChandler Carruth   }
242ef860a24SChandler Carruth   return false;
243ef860a24SChandler Carruth }
244ef860a24SChandler Carruth 
2455a0872c2SVedant Kumar unsigned Value::getNumUses() const {
2465a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
2475a0872c2SVedant Kumar }
248ef860a24SChandler Carruth 
249ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
250c620761cSCraig Topper   ST = nullptr;
251ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
252ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
253ef860a24SChandler Carruth       if (Function *PP = P->getParent())
254a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
255ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
256ef860a24SChandler Carruth     if (Function *P = BB->getParent())
257a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
258ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
259ef860a24SChandler Carruth     if (Module *P = GV->getParent())
260ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
261ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
262ef860a24SChandler Carruth     if (Function *P = A->getParent())
263a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
2645bf8fef5SDuncan P. N. Exon Smith   } else {
265ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
266ef860a24SChandler Carruth     return true;  // no name is setable for this.
267ef860a24SChandler Carruth   }
268ef860a24SChandler Carruth   return false;
269ef860a24SChandler Carruth }
270ef860a24SChandler Carruth 
2717349ab93SOwen Anderson ValueName *Value::getValueName() const {
2727349ab93SOwen Anderson   if (!HasName) return nullptr;
2737349ab93SOwen Anderson 
2747349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2757349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
2767349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
2777349ab93SOwen Anderson          "No name entry found!");
2787349ab93SOwen Anderson 
2797349ab93SOwen Anderson   return I->second;
2807349ab93SOwen Anderson }
2817349ab93SOwen Anderson 
2827349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2837349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2847349ab93SOwen Anderson 
2857349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2867349ab93SOwen Anderson          "HasName bit out of sync!");
2877349ab93SOwen Anderson 
2887349ab93SOwen Anderson   if (!VN) {
2897349ab93SOwen Anderson     if (HasName)
2907349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2917349ab93SOwen Anderson     HasName = false;
2927349ab93SOwen Anderson     return;
2937349ab93SOwen Anderson   }
2947349ab93SOwen Anderson 
2957349ab93SOwen Anderson   HasName = true;
2967349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2977349ab93SOwen Anderson }
2987349ab93SOwen Anderson 
299ef860a24SChandler Carruth StringRef Value::getName() const {
300ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
301ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
302ef860a24SChandler Carruth   // terminated.
3037349ab93SOwen Anderson   if (!hasName())
3045bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
3055bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
306ef860a24SChandler Carruth }
307ef860a24SChandler Carruth 
308a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
30909b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
31050af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
31109b4a8daSMehdi Amini     return;
31209b4a8daSMehdi Amini 
313ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
314ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
315ef860a24SChandler Carruth     return;
316ef860a24SChandler Carruth 
317ef860a24SChandler Carruth   SmallString<256> NameData;
318ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
31909d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
32009d689f9SRafael Espindola          "Null bytes are not allowed in names");
321ef860a24SChandler Carruth 
322ef860a24SChandler Carruth   // Name isn't changing?
323ef860a24SChandler Carruth   if (getName() == NameRef)
324ef860a24SChandler Carruth     return;
325ef860a24SChandler Carruth 
3264c975578SSerge Guelton   // Cap the size of non-GlobalValue names.
3274c975578SSerge Guelton   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
3284c975578SSerge Guelton     NameRef =
3294c975578SSerge Guelton         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
3304c975578SSerge Guelton 
331ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
332ef860a24SChandler Carruth 
333ef860a24SChandler Carruth   // Get the symbol table to update for this object.
334ef860a24SChandler Carruth   ValueSymbolTable *ST;
335ef860a24SChandler Carruth   if (getSymTab(this, ST))
336ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
339ef860a24SChandler Carruth     if (NameRef.empty()) {
340ef860a24SChandler Carruth       // Free the name for this value.
3415bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
342ef860a24SChandler Carruth       return;
343ef860a24SChandler Carruth     }
344ef860a24SChandler Carruth 
345ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
346ef860a24SChandler Carruth     // then reallocated.
3475bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
348ef860a24SChandler Carruth 
349ef860a24SChandler Carruth     // Create the new name.
35089c8ffd5SChris Lattner     MallocAllocator Allocator;
35189c8ffd5SChris Lattner     setValueName(ValueName::Create(NameRef, Allocator));
3525bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
353ef860a24SChandler Carruth     return;
354ef860a24SChandler Carruth   }
355ef860a24SChandler Carruth 
356ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
357ef860a24SChandler Carruth   // then reallocated.
358ef860a24SChandler Carruth   if (hasName()) {
359ef860a24SChandler Carruth     // Remove old name.
3605bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
3615bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
362ef860a24SChandler Carruth 
363ef860a24SChandler Carruth     if (NameRef.empty())
364ef860a24SChandler Carruth       return;
365ef860a24SChandler Carruth   }
366ef860a24SChandler Carruth 
367ef860a24SChandler Carruth   // Name is changing to something new.
3685bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
369ef860a24SChandler Carruth }
370ef860a24SChandler Carruth 
371a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
372a7c0c18cSPete Cooper   setNameImpl(NewName);
373a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
374a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
375a7c0c18cSPete Cooper }
376a7c0c18cSPete Cooper 
377ef860a24SChandler Carruth void Value::takeName(Value *V) {
378c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
379ef860a24SChandler Carruth   // If this value has a name, drop it.
380ef860a24SChandler Carruth   if (hasName()) {
381ef860a24SChandler Carruth     // Get the symtab this is in.
382ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
383ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
384ef860a24SChandler Carruth       // it has one.
385ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
386ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
387ef860a24SChandler Carruth     }
388ef860a24SChandler Carruth 
389ef860a24SChandler Carruth     // Remove old name.
390ef860a24SChandler Carruth     if (ST)
3915bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3925bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
393ef860a24SChandler Carruth   }
394ef860a24SChandler Carruth 
395ef860a24SChandler Carruth   // Now we know that this has no name.
396ef860a24SChandler Carruth 
397ef860a24SChandler Carruth   // If V has no name either, we're done.
398ef860a24SChandler Carruth   if (!V->hasName()) return;
399ef860a24SChandler Carruth 
400ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
401ef860a24SChandler Carruth   if (!ST) {
402ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
403ef860a24SChandler Carruth       // Clear V's name.
404ef860a24SChandler Carruth       V->setName("");
405ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
406ef860a24SChandler Carruth     }
407ef860a24SChandler Carruth   }
408ef860a24SChandler Carruth 
409ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
410ef860a24SChandler Carruth   ValueSymbolTable *VST;
411ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
412ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
413ef860a24SChandler Carruth 
414ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
415ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
416ef860a24SChandler Carruth   if (ST == VST) {
417ef860a24SChandler Carruth     // Take the name!
4185bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
4195bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
4205bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
421ef860a24SChandler Carruth     return;
422ef860a24SChandler Carruth   }
423ef860a24SChandler Carruth 
424ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
425ef860a24SChandler Carruth   // then reinsert it into ST.
426ef860a24SChandler Carruth 
427ef860a24SChandler Carruth   if (VST)
4285bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
4295bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
4305bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
4315bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
432ef860a24SChandler Carruth 
433ef860a24SChandler Carruth   if (ST)
434ef860a24SChandler Carruth     ST->reinsertValue(this);
435ef860a24SChandler Carruth }
436ef860a24SChandler Carruth 
437905623b6SQuentin Colombet #ifndef NDEBUG
438905623b6SQuentin Colombet std::string Value::getNameOrAsOperand() const {
439905623b6SQuentin Colombet   if (!getName().empty())
440905623b6SQuentin Colombet     return std::string(getName());
441905623b6SQuentin Colombet 
442905623b6SQuentin Colombet   std::string BBName;
443905623b6SQuentin Colombet   raw_string_ostream OS(BBName);
444905623b6SQuentin Colombet   printAsOperand(OS, false);
445905623b6SQuentin Colombet   return OS.str();
446905623b6SQuentin Colombet }
447905623b6SQuentin Colombet #endif
448905623b6SQuentin Colombet 
449eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
450675bdcedSTodd Fiala #ifndef NDEBUG
451257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
452257a3536SRafael Espindola   if (!GV)
453257a3536SRafael Espindola     return;
454257a3536SRafael Espindola   const Module *M = GV->getParent();
455257a3536SRafael Espindola   if (!M)
456257a3536SRafael Espindola     return;
457257a3536SRafael Espindola   assert(M->isMaterialized());
458675bdcedSTodd Fiala #endif
459257a3536SRafael Espindola }
460257a3536SRafael Espindola 
461675bdcedSTodd Fiala #ifndef NDEBUG
46271b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
4637e2b7567SRafael Espindola                      Constant *C) {
46470573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
4657e2b7567SRafael Espindola     return false;
4667e2b7567SRafael Espindola 
4677e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
4687e2b7567SRafael Espindola     if (O == C)
4697e2b7567SRafael Espindola       return true;
4707e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
4717e2b7567SRafael Espindola     if (!CE)
4727e2b7567SRafael Espindola       continue;
4737e2b7567SRafael Espindola     if (contains(Cache, CE, C))
4747e2b7567SRafael Espindola       return true;
4757e2b7567SRafael Espindola   }
4767e2b7567SRafael Espindola   return false;
4777e2b7567SRafael Espindola }
4787e2b7567SRafael Espindola 
4797e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
4807e2b7567SRafael Espindola   if (Expr == V)
4817e2b7567SRafael Espindola     return true;
4827e2b7567SRafael Espindola 
4837e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
4847e2b7567SRafael Espindola   if (!C)
4857e2b7567SRafael Espindola     return false;
4867e2b7567SRafael Espindola 
4877e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
4887e2b7567SRafael Espindola   if (!CE)
4897e2b7567SRafael Espindola     return false;
4907e2b7567SRafael Espindola 
4917e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
4927e2b7567SRafael Espindola   return contains(Cache, CE, C);
4937e2b7567SRafael Espindola }
494ecefe5a8SEugene Zelenko #endif // NDEBUG
495ef860a24SChandler Carruth 
496e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
497ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4987e2b7567SRafael Espindola   assert(!contains(New, this) &&
4997e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
500ef860a24SChandler Carruth   assert(New->getType() == getType() &&
501ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
502ef860a24SChandler Carruth 
503ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
504ef860a24SChandler Carruth   if (HasValueHandle)
505ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
506e69ae76bSJF Bastien   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
5075bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
508ef860a24SChandler Carruth 
50981bbf742STeresa Johnson   while (!materialized_use_empty()) {
510ef860a24SChandler Carruth     Use &U = *UseList;
511ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
512ef860a24SChandler Carruth     // constant because they are uniqued.
5136b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
514ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
5158914d290SMehdi Amini         C->handleOperandChange(this, New);
516ef860a24SChandler Carruth         continue;
517ef860a24SChandler Carruth       }
518ef860a24SChandler Carruth     }
519ef860a24SChandler Carruth 
520ef860a24SChandler Carruth     U.set(New);
521ef860a24SChandler Carruth   }
522ef860a24SChandler Carruth 
523ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
524ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
525ef860a24SChandler Carruth }
526ef860a24SChandler Carruth 
5271ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
528e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::Yes);
5291ed53963SDavide Italiano }
5301ed53963SDavide Italiano 
5311ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
532e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::No);
5331ed53963SDavide Italiano }
5341ed53963SDavide Italiano 
535bbccdf6fSOCHyams /// Replace llvm.dbg.* uses of MetadataAsValue(ValueAsMetadata(V)) outside BB
536bbccdf6fSOCHyams /// with New.
537bbccdf6fSOCHyams static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) {
538bbccdf6fSOCHyams   SmallVector<DbgVariableIntrinsic *> DbgUsers;
539bbccdf6fSOCHyams   findDbgUsers(DbgUsers, V);
540bbccdf6fSOCHyams   for (auto *DVI : DbgUsers) {
541bbccdf6fSOCHyams     if (DVI->getParent() != BB)
542bbccdf6fSOCHyams       DVI->replaceVariableLocationOp(V, New);
543bbccdf6fSOCHyams   }
544bbccdf6fSOCHyams }
545bbccdf6fSOCHyams 
546ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
547ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
548ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
549ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
550ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
551ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
552ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
553ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
554ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
555ec6217c9SGerolf Hoflehner 
556bbccdf6fSOCHyams   replaceDbgUsesOutsideBlock(this, New, BB);
557081e990dSRoman Lebedev   replaceUsesWithIf(New, [BB](Use &U) {
558081e990dSRoman Lebedev     auto *I = dyn_cast<Instruction>(U.getUser());
559081e990dSRoman Lebedev     // Don't replace if it's an instruction in the BB basic block.
560081e990dSRoman Lebedev     return !I || I->getParent() != BB;
561081e990dSRoman Lebedev   });
562ec6217c9SGerolf Hoflehner }
563ec6217c9SGerolf Hoflehner 
564ef860a24SChandler Carruth namespace {
565ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
566ef860a24SChandler Carruth enum PointerStripKind {
567ef860a24SChandler Carruth   PSK_ZeroIndices,
5688a410bceSErich Keane   PSK_ZeroIndicesAndAliases,
5692452d703SPeter Collingbourne   PSK_ZeroIndicesSameRepresentation,
57070e3c9a8SNikita Popov   PSK_ForAliasAnalysis,
571ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
572ef860a24SChandler Carruth   PSK_InBounds
573ef860a24SChandler Carruth };
574ef860a24SChandler Carruth 
57567448a8cSTyker template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
57667448a8cSTyker 
577ef860a24SChandler Carruth template <PointerStripKind StripKind>
578b7338fb1STyker static const Value *stripPointerCastsAndOffsets(
579b7338fb1STyker     const Value *V,
58067448a8cSTyker     function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
581ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
582ef860a24SChandler Carruth     return V;
583ef860a24SChandler Carruth 
584ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
585ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5861dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
587ef860a24SChandler Carruth 
588ef860a24SChandler Carruth   Visited.insert(V);
589ef860a24SChandler Carruth   do {
590b7338fb1STyker     Func(V);
5911dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
592ef860a24SChandler Carruth       switch (StripKind) {
593ef860a24SChandler Carruth       case PSK_ZeroIndices:
5948a410bceSErich Keane       case PSK_ZeroIndicesAndAliases:
5952452d703SPeter Collingbourne       case PSK_ZeroIndicesSameRepresentation:
59670e3c9a8SNikita Popov       case PSK_ForAliasAnalysis:
597ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
598ef860a24SChandler Carruth           return V;
599ef860a24SChandler Carruth         break;
600ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
601ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
602ef860a24SChandler Carruth           return V;
603b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
604ef860a24SChandler Carruth       case PSK_InBounds:
605ef860a24SChandler Carruth         if (!GEP->isInBounds())
606ef860a24SChandler Carruth           return V;
607ef860a24SChandler Carruth         break;
608ef860a24SChandler Carruth       }
609ef860a24SChandler Carruth       V = GEP->getPointerOperand();
61040107ce7SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
61140107ce7SJohannes Doerfert       V = cast<Operator>(V)->getOperand(0);
6122b8d706bSRoman Lebedev       if (!V->getType()->isPointerTy())
6132b8d706bSRoman Lebedev         return V;
6142452d703SPeter Collingbourne     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
615b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
61640107ce7SJohannes Doerfert       // TODO: If we know an address space cast will not change the
61740107ce7SJohannes Doerfert       //       representation we could look through it here as well.
618ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
6198a410bceSErich Keane     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
6208a410bceSErich Keane       V = cast<GlobalAlias>(V)->getAliasee();
62170e3c9a8SNikita Popov     } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
62270e3c9a8SNikita Popov                cast<PHINode>(V)->getNumIncomingValues() == 1) {
62370e3c9a8SNikita Popov       V = cast<PHINode>(V)->getIncomingValue(0);
624ef860a24SChandler Carruth     } else {
62590c09232SChandler Carruth       if (const auto *Call = dyn_cast<CallBase>(V)) {
62690c09232SChandler Carruth         if (const Value *RV = Call->getReturnedArgOperand()) {
6275c12d8feSHal Finkel           V = RV;
6285c12d8feSHal Finkel           continue;
6295c12d8feSHal Finkel         }
6305dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
631610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
632610c966aSPiotr Padlewski         // special case.
63370e3c9a8SNikita Popov         if (StripKind == PSK_ForAliasAnalysis &&
63490c09232SChandler Carruth             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
63590c09232SChandler Carruth              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
63690c09232SChandler Carruth           V = Call->getArgOperand(0);
637610c966aSPiotr Padlewski           continue;
638610c966aSPiotr Padlewski         }
639610c966aSPiotr Padlewski       }
640ef860a24SChandler Carruth       return V;
641ef860a24SChandler Carruth     }
642ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
64370573dcdSDavid Blaikie   } while (Visited.insert(V).second);
644ef860a24SChandler Carruth 
645ef860a24SChandler Carruth   return V;
646ef860a24SChandler Carruth }
647ecefe5a8SEugene Zelenko } // end anonymous namespace
648ef860a24SChandler Carruth 
6491dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
6502452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
651c229a4ffSRafael Espindola }
652c229a4ffSRafael Espindola 
6538a410bceSErich Keane const Value *Value::stripPointerCastsAndAliases() const {
6548a410bceSErich Keane   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
6558a410bceSErich Keane }
6568a410bceSErich Keane 
65740107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const {
6582452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
659ef860a24SChandler Carruth }
660ef860a24SChandler Carruth 
6611dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
662ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
663ef860a24SChandler Carruth }
664ef860a24SChandler Carruth 
66570e3c9a8SNikita Popov const Value *Value::stripPointerCastsForAliasAnalysis() const {
66670e3c9a8SNikita Popov   return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this);
667610c966aSPiotr Padlewski }
668610c966aSPiotr Padlewski 
669e5780776SKuter Dinel const Value *Value::stripAndAccumulateConstantOffsets(
670e5780776SKuter Dinel     const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
671e5780776SKuter Dinel     function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
6723ed286a3SJohannes Doerfert   if (!getType()->isPtrOrPtrVectorTy())
673989e6308SChandler Carruth     return this;
674989e6308SChandler Carruth 
6753ed286a3SJohannes Doerfert   unsigned BitWidth = Offset.getBitWidth();
6763ed286a3SJohannes Doerfert   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
677945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
678989e6308SChandler Carruth 
679989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
680989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
6811dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
682989e6308SChandler Carruth   Visited.insert(this);
6831dd20e65SCraig Topper   const Value *V = this;
684989e6308SChandler Carruth   do {
6851dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
6863ed286a3SJohannes Doerfert       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
6873ed286a3SJohannes Doerfert       if (!AllowNonInbounds && !GEP->isInBounds())
688989e6308SChandler Carruth         return V;
6893ed286a3SJohannes Doerfert 
6903ed286a3SJohannes Doerfert       // If one of the values we have visited is an addrspacecast, then
6913ed286a3SJohannes Doerfert       // the pointer type of this GEP may be different from the type
6923ed286a3SJohannes Doerfert       // of the Ptr parameter which was passed to this function.  This
6933ed286a3SJohannes Doerfert       // means when we construct GEPOffset, we need to use the size
6943ed286a3SJohannes Doerfert       // of GEP's pointer type rather than the size of the original
6953ed286a3SJohannes Doerfert       // pointer type.
6963ed286a3SJohannes Doerfert       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
697e5780776SKuter Dinel       if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
698989e6308SChandler Carruth         return V;
6993ed286a3SJohannes Doerfert 
7003ed286a3SJohannes Doerfert       // Stop traversal if the pointer offset wouldn't fit in the bit-width
7013ed286a3SJohannes Doerfert       // provided by the Offset argument. This can happen due to AddrSpaceCast
7023ed286a3SJohannes Doerfert       // stripping.
7033ed286a3SJohannes Doerfert       if (GEPOffset.getMinSignedBits() > BitWidth)
7043ed286a3SJohannes Doerfert         return V;
7053ed286a3SJohannes Doerfert 
706e5780776SKuter Dinel       // External Analysis can return a result higher/lower than the value
707e5780776SKuter Dinel       // represents. We need to detect overflow/underflow.
708e5780776SKuter Dinel       APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
709e5780776SKuter Dinel       if (!ExternalAnalysis) {
710e5780776SKuter Dinel         Offset += GEPOffsetST;
711e5780776SKuter Dinel       } else {
712e5780776SKuter Dinel         bool Overflow = false;
713e5780776SKuter Dinel         APInt OldOffset = Offset;
714e5780776SKuter Dinel         Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
715e5780776SKuter Dinel         if (Overflow) {
716e5780776SKuter Dinel           Offset = OldOffset;
717e5780776SKuter Dinel           return V;
718e5780776SKuter Dinel         }
719e5780776SKuter Dinel       }
720989e6308SChandler Carruth       V = GEP->getPointerOperand();
7213ed286a3SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7223ed286a3SJohannes Doerfert                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
723989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
7241dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7253ed286a3SJohannes Doerfert       if (!GA->isInterposable())
726989e6308SChandler Carruth         V = GA->getAliasee();
7273ed286a3SJohannes Doerfert     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
7283ed286a3SJohannes Doerfert         if (const Value *RV = Call->getReturnedArgOperand())
7295c12d8feSHal Finkel           V = RV;
7305c12d8feSHal Finkel     }
7313ed286a3SJohannes Doerfert     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
73270573dcdSDavid Blaikie   } while (Visited.insert(V).second);
733989e6308SChandler Carruth 
734989e6308SChandler Carruth   return V;
735989e6308SChandler Carruth }
736989e6308SChandler Carruth 
737b7338fb1STyker const Value *
738b7338fb1STyker Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
739b7338fb1STyker   return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
740ef860a24SChandler Carruth }
741ef860a24SChandler Carruth 
742e2c6621eSPhilip Reames bool Value::canBeFreed() const {
743e2c6621eSPhilip Reames   assert(getType()->isPointerTy());
7444054b832SPhilip Reames 
7454054b832SPhilip Reames   // Cases that can simply never be deallocated
7464054b832SPhilip Reames   // *) Constants aren't allocated per se, thus not deallocated either.
747e2c6621eSPhilip Reames   if (isa<Constant>(this))
7484054b832SPhilip Reames     return false;
7494054b832SPhilip Reames 
750e7ebb872SPhilip Reames   // Handle byval/byref/sret/inalloca/preallocated arguments.  The storage
751e7ebb872SPhilip Reames   // lifetime is guaranteed to be longer than the callee's lifetime.
752ff55d01aSPhilip Reames   if (auto *A = dyn_cast<Argument>(this)) {
753e7ebb872SPhilip Reames     if (A->hasPointeeInMemoryValueAttr())
754e7ebb872SPhilip Reames       return false;
755ff55d01aSPhilip Reames     // A pointer to an object in a function which neither frees, nor can arrange
756ff55d01aSPhilip Reames     // for another thread to free on its behalf, can not be freed in the scope
757ff55d01aSPhilip Reames     // of the function.  Note that this logic is restricted to memory
758ff55d01aSPhilip Reames     // allocations in existance before the call; a nofree function *is* allowed
759ff55d01aSPhilip Reames     // to free memory it allocated.
760ff55d01aSPhilip Reames     const Function *F = A->getParent();
761ff55d01aSPhilip Reames     if (F->doesNotFreeMemory() && F->hasNoSync())
762ff55d01aSPhilip Reames       return false;
763ff55d01aSPhilip Reames   }
764e7ebb872SPhilip Reames 
7654054b832SPhilip Reames   const Function *F = nullptr;
766e2c6621eSPhilip Reames   if (auto *I = dyn_cast<Instruction>(this))
7674054b832SPhilip Reames     F = I->getFunction();
768e2c6621eSPhilip Reames   if (auto *A = dyn_cast<Argument>(this))
7694054b832SPhilip Reames     F = A->getParent();
7704054b832SPhilip Reames 
7714054b832SPhilip Reames   if (!F)
7724054b832SPhilip Reames     return true;
7734054b832SPhilip Reames 
7744054b832SPhilip Reames   // With garbage collection, deallocation typically occurs solely at or after
7754054b832SPhilip Reames   // safepoints.  If we're compiling for a collector which uses the
7764054b832SPhilip Reames   // gc.statepoint infrastructure, safepoints aren't explicitly present
7774054b832SPhilip Reames   // in the IR until after lowering from abstract to physical machine model.
7784054b832SPhilip Reames   // The collector could chose to mix explicit deallocation and gc'd objects
7794054b832SPhilip Reames   // which is why we need the explicit opt in on a per collector basis.
7804054b832SPhilip Reames   if (!F->hasGC())
7814054b832SPhilip Reames     return true;
7824054b832SPhilip Reames 
7834054b832SPhilip Reames   const auto &GCName = F->getGC();
784*9430efa1SMax Kazantsev   if (GCName == "statepoint-example") {
785e2c6621eSPhilip Reames     auto *PT = cast<PointerType>(this->getType());
7864054b832SPhilip Reames     if (PT->getAddressSpace() != 1)
787*9430efa1SMax Kazantsev       // For the sake of this example GC, we arbitrarily pick addrspace(1) as
788*9430efa1SMax Kazantsev       // our GC managed heap.  This must match the same check in
7894054b832SPhilip Reames       // RewriteStatepointsForGC (and probably needs better factored.)
7904054b832SPhilip Reames       return true;
7914054b832SPhilip Reames 
7924054b832SPhilip Reames     // It is cheaper to scan for a declaration than to scan for a use in this
7934054b832SPhilip Reames     // function.  Note that gc.statepoint is a type overloaded function so the
7944054b832SPhilip Reames     // usual trick of requesting declaration of the intrinsic from the module
7954054b832SPhilip Reames     // doesn't work.
7964054b832SPhilip Reames     for (auto &Fn : *F->getParent())
7974054b832SPhilip Reames       if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
7984054b832SPhilip Reames         return true;
7994054b832SPhilip Reames     return false;
8004054b832SPhilip Reames   }
801*9430efa1SMax Kazantsev   return true;
802*9430efa1SMax Kazantsev }
8034054b832SPhilip Reames 
8043603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
8055698537fSPhilip Reames                                                bool &CanBeNull,
8065698537fSPhilip Reames                                                bool &CanBeFreed) const {
807345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
808345f0148SArtur Pilipenko 
8093603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
810345f0148SArtur Pilipenko   CanBeNull = false;
811e2c6621eSPhilip Reames   CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
812345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
813345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
814dc08185cSMatt Arsenault     if (DerefBytes == 0) {
815dc08185cSMatt Arsenault       // Handle byval/byref/inalloca/preallocated arguments
816dc08185cSMatt Arsenault       if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
817dc08185cSMatt Arsenault         if (ArgMemTy->isSized()) {
818dc08185cSMatt Arsenault           // FIXME: Why isn't this the type alloc size?
819dc08185cSMatt Arsenault           DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinSize();
82000953cbeSSanjoy Das         }
821dc08185cSMatt Arsenault       }
822dc08185cSMatt Arsenault     }
823dc08185cSMatt Arsenault 
824345f0148SArtur Pilipenko     if (DerefBytes == 0) {
825345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
826345f0148SArtur Pilipenko       CanBeNull = true;
827345f0148SArtur Pilipenko     }
82890c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
82990c09232SChandler Carruth     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
830345f0148SArtur Pilipenko     if (DerefBytes == 0) {
83190c09232SChandler Carruth       DerefBytes =
83290c09232SChandler Carruth           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
833345f0148SArtur Pilipenko       CanBeNull = true;
834345f0148SArtur Pilipenko     }
835345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
836345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
837345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
838345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
839345f0148SArtur Pilipenko     }
840345f0148SArtur Pilipenko     if (DerefBytes == 0) {
841345f0148SArtur Pilipenko       if (MDNode *MD =
842345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
843345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
844345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
845345f0148SArtur Pilipenko       }
846345f0148SArtur Pilipenko       CanBeNull = true;
847345f0148SArtur Pilipenko     }
8486f13637aSRyan Taylor   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
8496f13637aSRyan Taylor     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
8506f13637aSRyan Taylor       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8516f13637aSRyan Taylor       DerefBytes = CI->getLimitedValue();
8526f13637aSRyan Taylor     }
8536f13637aSRyan Taylor     if (DerefBytes == 0) {
8546f13637aSRyan Taylor       if (MDNode *MD =
8556f13637aSRyan Taylor               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
8566f13637aSRyan Taylor         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8576f13637aSRyan Taylor         DerefBytes = CI->getLimitedValue();
8586f13637aSRyan Taylor       }
8596f13637aSRyan Taylor       CanBeNull = true;
8606f13637aSRyan Taylor     }
86100953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
862030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
863ebec984eSEli Friedman       DerefBytes =
864ebec984eSEli Friedman           DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
86500953cbeSSanjoy Das       CanBeNull = false;
8665698537fSPhilip Reames       CanBeFreed = false;
86700953cbeSSanjoy Das     }
86800953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
86900953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
87000953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
87100953cbeSSanjoy Das       // CanBeNull flag.
872ebec984eSEli Friedman       DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
87300953cbeSSanjoy Das       CanBeNull = false;
87400953cbeSSanjoy Das     }
875345f0148SArtur Pilipenko   }
876345f0148SArtur Pilipenko   return DerefBytes;
877345f0148SArtur Pilipenko }
878345f0148SArtur Pilipenko 
879f26bdb53SEli Friedman Align Value::getPointerAlignment(const DataLayout &DL) const {
880ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
881ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
882308e82ecSMichael Platings     if (isa<Function>(GO)) {
883f26bdb53SEli Friedman       Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
884308e82ecSMichael Platings       switch (DL.getFunctionPtrAlignType()) {
885308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::Independent:
886bae629b9SGuillaume Chatelet         return FunctionPtrAlign;
887308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
888f26bdb53SEli Friedman         return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
889308e82ecSMichael Platings       }
8906200a568SGuillaume Chatelet       llvm_unreachable("Unhandled FunctionPtrAlignType");
891308e82ecSMichael Platings     }
892bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(GO->getAlignment());
893bae629b9SGuillaume Chatelet     if (!Alignment) {
894ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
895ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
896ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
897ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
898ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
899ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
900ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
901368a5e3aSGuillaume Chatelet             return DL.getPreferredAlign(GVar);
902ae51afc5SArtur Pilipenko           else
9039068bccbSGuillaume Chatelet             return DL.getABITypeAlign(ObjectType);
904ae51afc5SArtur Pilipenko         }
905ae51afc5SArtur Pilipenko       }
906ae51afc5SArtur Pilipenko     }
907f26bdb53SEli Friedman     return Alignment.valueOrOne();
908ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
9099068bccbSGuillaume Chatelet     const MaybeAlign Alignment = A->getParamAlign();
910bae629b9SGuillaume Chatelet     if (!Alignment && A->hasStructRetAttr()) {
911ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
912d65a7003SMatt Arsenault       Type *EltTy = A->getParamStructRetType();
913ae51afc5SArtur Pilipenko       if (EltTy->isSized())
9149068bccbSGuillaume Chatelet         return DL.getABITypeAlign(EltTy);
915ae51afc5SArtur Pilipenko     }
916f26bdb53SEli Friedman     return Alignment.valueOrOne();
917c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
918f26bdb53SEli Friedman     return AI->getAlign();
919afd4a37bSHideto Ueno   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
920f26bdb53SEli Friedman     MaybeAlign Alignment = Call->getRetAlign();
921bae629b9SGuillaume Chatelet     if (!Alignment && Call->getCalledFunction())
922f26bdb53SEli Friedman       Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
923f26bdb53SEli Friedman     return Alignment.valueOrOne();
9246200a568SGuillaume Chatelet   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
925ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
926ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
927f26bdb53SEli Friedman       return Align(CI->getLimitedValue());
928ae51afc5SArtur Pilipenko     }
929a6492e22SRoman Lebedev   } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
930a6492e22SRoman Lebedev     if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
931a6492e22SRoman Lebedev             const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
932a6492e22SRoman Lebedev             /*OnlyIfReduced=*/true))) {
933a6492e22SRoman Lebedev       size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
934a6492e22SRoman Lebedev       // While the actual alignment may be large, elsewhere we have
935a6492e22SRoman Lebedev       // an arbitrary upper alignmet limit, so let's clamp to it.
936a6492e22SRoman Lebedev       return Align(TrailingZeros < Value::MaxAlignmentExponent
937a6492e22SRoman Lebedev                        ? uint64_t(1) << TrailingZeros
938a6492e22SRoman Lebedev                        : Value::MaximumAlignment);
939a6492e22SRoman Lebedev     }
9406200a568SGuillaume Chatelet   }
941f26bdb53SEli Friedman   return Align(1);
942ae51afc5SArtur Pilipenko }
943ae51afc5SArtur Pilipenko 
9441dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
9451dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
9461dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
947ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
948ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
949ef860a24SChandler Carruth   return this;
950ef860a24SChandler Carruth }
951ef860a24SChandler Carruth 
952ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
953ef860a24SChandler Carruth 
9543441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
9553441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
9563441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
9573441ffe9SDuncan P. N. Exon Smith     return;
9583441ffe9SDuncan P. N. Exon Smith 
9593441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
9603441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
9613441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
9623441ffe9SDuncan P. N. Exon Smith   while (Current) {
9633441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
9643441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
96591ef7cb5SJay Foad     Head->Prev = &Current->Next;
9663441ffe9SDuncan P. N. Exon Smith     Head = Current;
9673441ffe9SDuncan P. N. Exon Smith     Current = Next;
9683441ffe9SDuncan P. N. Exon Smith   }
9693441ffe9SDuncan P. N. Exon Smith   UseList = Head;
97091ef7cb5SJay Foad   Head->Prev = &UseList;
9713441ffe9SDuncan P. N. Exon Smith }
9723441ffe9SDuncan P. N. Exon Smith 
973ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
974ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
975ad830022SArnold Schwaighofer   if (Arg)
976ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
977ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
978ad830022SArnold Schwaighofer   if (!Alloca)
979ad830022SArnold Schwaighofer     return false;
980ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
981ad830022SArnold Schwaighofer }
982ad830022SArnold Schwaighofer 
983ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
984ef860a24SChandler Carruth //                             ValueHandleBase Class
985ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
986ef860a24SChandler Carruth 
987ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
988ef860a24SChandler Carruth   assert(List && "Handle list is null?");
989ef860a24SChandler Carruth 
990ef860a24SChandler Carruth   // Splice ourselves into the list.
991ef860a24SChandler Carruth   Next = *List;
992ef860a24SChandler Carruth   *List = this;
993ef860a24SChandler Carruth   setPrevPtr(List);
994ef860a24SChandler Carruth   if (Next) {
995ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
9966f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
997ef860a24SChandler Carruth   }
998ef860a24SChandler Carruth }
999ef860a24SChandler Carruth 
1000ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
1001ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
1002ef860a24SChandler Carruth 
1003ef860a24SChandler Carruth   Next = List->Next;
1004ef860a24SChandler Carruth   setPrevPtr(&List->Next);
1005ef860a24SChandler Carruth   List->Next = this;
1006ef860a24SChandler Carruth   if (Next)
1007ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
1008ef860a24SChandler Carruth }
1009ef860a24SChandler Carruth 
1010ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
10116f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
1012ef860a24SChandler Carruth 
10136f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1014ef860a24SChandler Carruth 
10156f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
1016ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
1017ef860a24SChandler Carruth     // ValueHandles map already.
10186f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
10192617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
1020ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
1021ef860a24SChandler Carruth     return;
1022ef860a24SChandler Carruth   }
1023ef860a24SChandler Carruth 
1024ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
1025ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
1026ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
1027ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
1028ef860a24SChandler Carruth   // updating the stale pointers only if needed.
1029ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1030ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
1031ef860a24SChandler Carruth 
10326f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
10332617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
1034ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
10356f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
1036ef860a24SChandler Carruth 
1037ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
1038ef860a24SChandler Carruth   // walk the table.
1039ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
1040ef860a24SChandler Carruth       Handles.size() == 1) {
1041ef860a24SChandler Carruth     return;
1042ef860a24SChandler Carruth   }
1043ef860a24SChandler Carruth 
1044ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
1045ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
1046ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
10476f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
1048ef860a24SChandler Carruth            "List invariant broken!");
1049ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
1050ef860a24SChandler Carruth   }
1051ef860a24SChandler Carruth }
1052ef860a24SChandler Carruth 
1053ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
10546f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
1055ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
1056ef860a24SChandler Carruth 
1057ef860a24SChandler Carruth   // Unlink this from its use list.
1058ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
1059ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
1060ef860a24SChandler Carruth 
1061ef860a24SChandler Carruth   *PrevPtr = Next;
1062ef860a24SChandler Carruth   if (Next) {
1063ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
1064ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
1065ef860a24SChandler Carruth     return;
1066ef860a24SChandler Carruth   }
1067ef860a24SChandler Carruth 
1068ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
1069ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
1070ef860a24SChandler Carruth   // map.
10716f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1072ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1073ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
10746f08789dSSanjoy Das     Handles.erase(getValPtr());
10756f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
1076ef860a24SChandler Carruth   }
1077ef860a24SChandler Carruth }
1078ef860a24SChandler Carruth 
1079ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
1080ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
1081ef860a24SChandler Carruth 
1082ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
1083ef860a24SChandler Carruth   // HasValueHandle flag is set.
1084ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
1085ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
1086ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
1087ef860a24SChandler Carruth 
1088ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
1089ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
1090ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
1091ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
1092ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
1093ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
1094ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
1095ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
1096ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
1097ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1098ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
1099ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
1100ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1101ef860a24SChandler Carruth 
1102ef860a24SChandler Carruth     switch (Entry->getKind()) {
1103ef860a24SChandler Carruth     case Assert:
1104ef860a24SChandler Carruth       break;
1105f1c0eafdSSanjoy Das     case Weak:
1106e6bca0eeSSanjoy Das     case WeakTracking:
1107f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
1108f1c0eafdSSanjoy Das       // from the list.
1109c620761cSCraig Topper       Entry->operator=(nullptr);
1110ef860a24SChandler Carruth       break;
1111ef860a24SChandler Carruth     case Callback:
1112ef860a24SChandler Carruth       // Forward to the subclass's implementation.
1113ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
1114ef860a24SChandler Carruth       break;
1115ef860a24SChandler Carruth     }
1116ef860a24SChandler Carruth   }
1117ef860a24SChandler Carruth 
1118ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
1119ef860a24SChandler Carruth   if (V->HasValueHandle) {
1120ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
1121ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1122ef860a24SChandler Carruth            << "\n";
1123ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
1124ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
1125ef860a24SChandler Carruth                        " value!");
1126ef860a24SChandler Carruth 
1127ef860a24SChandler Carruth #endif
1128ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
1129ef860a24SChandler Carruth   }
1130ef860a24SChandler Carruth }
1131ef860a24SChandler Carruth 
1132ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1133ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1134ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
1135c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
1136c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
1137ef860a24SChandler Carruth 
1138ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
1139ef860a24SChandler Carruth   // HasValueHandle flag is set.
1140ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
1141ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1142ef860a24SChandler Carruth 
1143ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
1144ef860a24SChandler Carruth 
1145ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
1146ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
1147ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
1148ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
1149ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1150ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
1151ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
1152ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1153ef860a24SChandler Carruth 
1154ef860a24SChandler Carruth     switch (Entry->getKind()) {
1155ef860a24SChandler Carruth     case Assert:
1156f1c0eafdSSanjoy Das     case Weak:
1157f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
1158ef860a24SChandler Carruth       break;
1159e6bca0eeSSanjoy Das     case WeakTracking:
11602cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
1161ef860a24SChandler Carruth       Entry->operator=(New);
1162ef860a24SChandler Carruth       break;
1163ef860a24SChandler Carruth     case Callback:
1164ef860a24SChandler Carruth       // Forward to the subclass's implementation.
1165ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1166ef860a24SChandler Carruth       break;
1167ef860a24SChandler Carruth     }
1168ef860a24SChandler Carruth   }
1169ef860a24SChandler Carruth 
1170ef860a24SChandler Carruth #ifndef NDEBUG
11718a623820SSanjoy Das   // If any new weak value handles were added while processing the
1172ef860a24SChandler Carruth   // list, then complain about it now.
1173ef860a24SChandler Carruth   if (Old->HasValueHandle)
1174ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1175ef860a24SChandler Carruth       switch (Entry->getKind()) {
1176e6bca0eeSSanjoy Das       case WeakTracking:
1177ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
1178ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
1179ef860a24SChandler Carruth                << New->getName() << "\n";
11808a623820SSanjoy Das         llvm_unreachable(
1181e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the old value!\n");
1182ef860a24SChandler Carruth       default:
1183ef860a24SChandler Carruth         break;
1184ef860a24SChandler Carruth       }
1185ef860a24SChandler Carruth #endif
1186ef860a24SChandler Carruth }
1187ef860a24SChandler Carruth 
1188d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
1189d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
1190