xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 15440191)
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"
219fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2296ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h"
2303eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
249fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
259fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
26a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h"
279fb823bbSChandler Carruth #include "llvm/IR/Module.h"
289fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
29a7343d65SRamkumar Ramachandra #include "llvm/IR/Statepoint.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 
414c975578SSerge Guelton static cl::opt<unsigned> NonGlobalValueMaxNameSize(
424c975578SSerge Guelton     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
434c975578SSerge Guelton     cl::desc("Maximum size for the name of non-global values."));
444c975578SSerge Guelton 
45ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
46ef860a24SChandler Carruth //                                Value Class
47ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
48ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
49ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
5016bf89ecSReid Kleckner   return Ty;
51ef860a24SChandler Carruth }
52ef860a24SChandler Carruth 
53ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
547349ab93SOwen Anderson     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
557349ab93SOwen Anderson       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
56b4eede2cSPete Cooper       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
579fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
58ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
59ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
60ef860a24SChandler Carruth   // constructed.
61784929d0SCraig Topper   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
62784929d0SCraig Topper       SubclassID == Instruction::CallBr)
63ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
64ef860a24SChandler Carruth            "invalid CallInst type!");
65ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
669fd33f24SSerge Guelton            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
67ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
68ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
6996ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
701762ad3eSReid Kleckner                 "Value too big");
71ef860a24SChandler Carruth }
72ef860a24SChandler Carruth 
73ef860a24SChandler Carruth Value::~Value() {
74ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
75ef860a24SChandler Carruth   if (HasValueHandle)
76ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
775bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
785bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
79ef860a24SChandler Carruth 
80ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
81ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
82ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
83b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
84b93fb82bSAndrew Kaylor   // the value is still being referenced.
85ef860a24SChandler Carruth   //
867dd28109SEvgenii Stepanov   // Note that use_empty() cannot be called here, as it eventually downcasts
877dd28109SEvgenii Stepanov   // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
887dd28109SEvgenii Stepanov   // been destructed, so accessing it is UB.
897dd28109SEvgenii Stepanov   //
907dd28109SEvgenii Stepanov   if (!materialized_use_empty()) {
91ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
92b93fb82bSAndrew Kaylor     for (auto *U : users())
93b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
94ef860a24SChandler Carruth   }
95ef860a24SChandler Carruth #endif
967dd28109SEvgenii Stepanov   assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
97ef860a24SChandler Carruth 
98ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
99ef860a24SChandler Carruth   // at this point.
1005bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
101ef860a24SChandler Carruth }
102ef860a24SChandler Carruth 
10396ab8726SReid Kleckner void Value::deleteValue() {
10496ab8726SReid Kleckner   switch (getValueID()) {
10596ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
10696ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10796ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
10896ab8726SReid Kleckner     break;
10996ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
11096ab8726SReid Kleckner   case Value::Name##Val:                                                       \
11196ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
11296ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
11396ab8726SReid Kleckner     break;
114*15440191SEli Friedman #define HANDLE_CONSTANT(Name)                                                  \
115*15440191SEli Friedman   case Value::Name##Val:                                                       \
116*15440191SEli Friedman     llvm_unreachable("constants should be destroyed with destroyConstant");    \
117*15440191SEli Friedman     break;
11896ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
11996ab8726SReid Kleckner #include "llvm/IR/Value.def"
12096ab8726SReid Kleckner 
12196ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
12296ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
12396ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
12496ab8726SReid Kleckner     break;
12596ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
12696ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
12796ab8726SReid Kleckner 
12896ab8726SReid Kleckner   default:
12996ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
13096ab8726SReid Kleckner   }
13196ab8726SReid Kleckner }
13296ab8726SReid Kleckner 
1335bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1345bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
13589c8ffd5SChris Lattner   if (Name) {
13689c8ffd5SChris Lattner     MallocAllocator Allocator;
13789c8ffd5SChris Lattner     Name->Destroy(Allocator);
13889c8ffd5SChris Lattner   }
1395bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1405bf8fef5SDuncan P. N. Exon Smith }
1415bf8fef5SDuncan P. N. Exon Smith 
142ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
1434de31bbaSVedant Kumar   return hasNItems(use_begin(), use_end(), N);
144ef860a24SChandler Carruth }
145ef860a24SChandler Carruth 
146ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
1474de31bbaSVedant Kumar   return hasNItemsOrMore(use_begin(), use_end(), N);
148ef860a24SChandler Carruth }
149ef860a24SChandler Carruth 
150f16f139dSTyker static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
151f16f139dSTyker 
152f16f139dSTyker Use *Value::getSingleUndroppableUse() {
153f16f139dSTyker   Use *Result = nullptr;
154f16f139dSTyker   for (Use &U : uses()) {
155f16f139dSTyker     if (!U.getUser()->isDroppable()) {
156f16f139dSTyker       if (Result)
157f16f139dSTyker         return nullptr;
158f16f139dSTyker       Result = &U;
159f16f139dSTyker     }
160f16f139dSTyker   }
161f16f139dSTyker   return Result;
162f16f139dSTyker }
163f16f139dSTyker 
164f16f139dSTyker bool Value::hasNUndroppableUses(unsigned int N) const {
165f16f139dSTyker   return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
166f16f139dSTyker }
167f16f139dSTyker 
168f16f139dSTyker bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
169f16f139dSTyker   return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
170f16f139dSTyker }
171f16f139dSTyker 
172f16f139dSTyker void Value::dropDroppableUses(
173f16f139dSTyker     llvm::function_ref<bool(const Use *)> ShouldDrop) {
174f16f139dSTyker   SmallVector<Use *, 8> ToBeEdited;
175f16f139dSTyker   for (Use &U : uses())
176f16f139dSTyker     if (U.getUser()->isDroppable() && ShouldDrop(&U))
177f16f139dSTyker       ToBeEdited.push_back(&U);
178f16f139dSTyker   for (Use *U : ToBeEdited) {
179f16f139dSTyker     U->removeFromList();
180f16f139dSTyker     if (auto *Assume = dyn_cast<IntrinsicInst>(U->getUser())) {
181f16f139dSTyker       assert(Assume->getIntrinsicID() == Intrinsic::assume);
182f16f139dSTyker       unsigned OpNo = U->getOperandNo();
183f16f139dSTyker       if (OpNo == 0)
184f16f139dSTyker         Assume->setOperand(0, ConstantInt::getTrue(Assume->getContext()));
185f16f139dSTyker       else {
186f16f139dSTyker         Assume->setOperand(OpNo, UndefValue::get(U->get()->getType()));
187f16f139dSTyker         CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
188f16f139dSTyker         BOI.Tag = getContext().pImpl->getOrInsertBundleTag("ignore");
189f16f139dSTyker       }
190f16f139dSTyker     } else
191f16f139dSTyker       llvm_unreachable("unkown droppable use");
192f16f139dSTyker   }
193f16f139dSTyker }
194f16f139dSTyker 
195ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1960925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1970925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1980925b24dSJakob Stoklund Olesen   // usually one is quite short.
1990925b24dSJakob Stoklund Olesen   //
2000925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
2010925b24dSJakob Stoklund Olesen   // search to the shorter list.
2020925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
203cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
2040925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
2050925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
20642531260SDavid Majnemer     if (is_contained(BI->operands(), this))
207ef860a24SChandler Carruth       return true;
2080925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
20942531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
210ef860a24SChandler Carruth     if (User && User->getParent() == BB)
211ef860a24SChandler Carruth       return true;
212ef860a24SChandler Carruth   }
213ef860a24SChandler Carruth   return false;
214ef860a24SChandler Carruth }
215ef860a24SChandler Carruth 
2165a0872c2SVedant Kumar unsigned Value::getNumUses() const {
2175a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
2185a0872c2SVedant Kumar }
219ef860a24SChandler Carruth 
220ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
221c620761cSCraig Topper   ST = nullptr;
222ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
223ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
224ef860a24SChandler Carruth       if (Function *PP = P->getParent())
225a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
226ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
227ef860a24SChandler Carruth     if (Function *P = BB->getParent())
228a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
229ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
230ef860a24SChandler Carruth     if (Module *P = GV->getParent())
231ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
232ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
233ef860a24SChandler Carruth     if (Function *P = A->getParent())
234a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
2355bf8fef5SDuncan P. N. Exon Smith   } else {
236ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
237ef860a24SChandler Carruth     return true;  // no name is setable for this.
238ef860a24SChandler Carruth   }
239ef860a24SChandler Carruth   return false;
240ef860a24SChandler Carruth }
241ef860a24SChandler Carruth 
2427349ab93SOwen Anderson ValueName *Value::getValueName() const {
2437349ab93SOwen Anderson   if (!HasName) return nullptr;
2447349ab93SOwen Anderson 
2457349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2467349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
2477349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
2487349ab93SOwen Anderson          "No name entry found!");
2497349ab93SOwen Anderson 
2507349ab93SOwen Anderson   return I->second;
2517349ab93SOwen Anderson }
2527349ab93SOwen Anderson 
2537349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2547349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2557349ab93SOwen Anderson 
2567349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2577349ab93SOwen Anderson          "HasName bit out of sync!");
2587349ab93SOwen Anderson 
2597349ab93SOwen Anderson   if (!VN) {
2607349ab93SOwen Anderson     if (HasName)
2617349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2627349ab93SOwen Anderson     HasName = false;
2637349ab93SOwen Anderson     return;
2647349ab93SOwen Anderson   }
2657349ab93SOwen Anderson 
2667349ab93SOwen Anderson   HasName = true;
2677349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2687349ab93SOwen Anderson }
2697349ab93SOwen Anderson 
270ef860a24SChandler Carruth StringRef Value::getName() const {
271ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
272ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
273ef860a24SChandler Carruth   // terminated.
2747349ab93SOwen Anderson   if (!hasName())
2755bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2765bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
277ef860a24SChandler Carruth }
278ef860a24SChandler Carruth 
279a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
28009b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
28150af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
28209b4a8daSMehdi Amini     return;
28309b4a8daSMehdi Amini 
284ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
285ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
286ef860a24SChandler Carruth     return;
287ef860a24SChandler Carruth 
288ef860a24SChandler Carruth   SmallString<256> NameData;
289ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
29009d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
29109d689f9SRafael Espindola          "Null bytes are not allowed in names");
292ef860a24SChandler Carruth 
293ef860a24SChandler Carruth   // Name isn't changing?
294ef860a24SChandler Carruth   if (getName() == NameRef)
295ef860a24SChandler Carruth     return;
296ef860a24SChandler Carruth 
2974c975578SSerge Guelton   // Cap the size of non-GlobalValue names.
2984c975578SSerge Guelton   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
2994c975578SSerge Guelton     NameRef =
3004c975578SSerge Guelton         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
3014c975578SSerge Guelton 
302ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
303ef860a24SChandler Carruth 
304ef860a24SChandler Carruth   // Get the symbol table to update for this object.
305ef860a24SChandler Carruth   ValueSymbolTable *ST;
306ef860a24SChandler Carruth   if (getSymTab(this, ST))
307ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
308ef860a24SChandler Carruth 
309ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
310ef860a24SChandler Carruth     if (NameRef.empty()) {
311ef860a24SChandler Carruth       // Free the name for this value.
3125bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
313ef860a24SChandler Carruth       return;
314ef860a24SChandler Carruth     }
315ef860a24SChandler Carruth 
316ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
317ef860a24SChandler Carruth     // then reallocated.
3185bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
319ef860a24SChandler Carruth 
320ef860a24SChandler Carruth     // Create the new name.
32189c8ffd5SChris Lattner     MallocAllocator Allocator;
32289c8ffd5SChris Lattner     setValueName(ValueName::Create(NameRef, Allocator));
3235bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
324ef860a24SChandler Carruth     return;
325ef860a24SChandler Carruth   }
326ef860a24SChandler Carruth 
327ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
328ef860a24SChandler Carruth   // then reallocated.
329ef860a24SChandler Carruth   if (hasName()) {
330ef860a24SChandler Carruth     // Remove old name.
3315bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
3325bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
333ef860a24SChandler Carruth 
334ef860a24SChandler Carruth     if (NameRef.empty())
335ef860a24SChandler Carruth       return;
336ef860a24SChandler Carruth   }
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   // Name is changing to something new.
3395bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
340ef860a24SChandler Carruth }
341ef860a24SChandler Carruth 
342a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
343a7c0c18cSPete Cooper   setNameImpl(NewName);
344a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
345a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
346a7c0c18cSPete Cooper }
347a7c0c18cSPete Cooper 
348ef860a24SChandler Carruth void Value::takeName(Value *V) {
349c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
350ef860a24SChandler Carruth   // If this value has a name, drop it.
351ef860a24SChandler Carruth   if (hasName()) {
352ef860a24SChandler Carruth     // Get the symtab this is in.
353ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
354ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
355ef860a24SChandler Carruth       // it has one.
356ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
357ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
358ef860a24SChandler Carruth     }
359ef860a24SChandler Carruth 
360ef860a24SChandler Carruth     // Remove old name.
361ef860a24SChandler Carruth     if (ST)
3625bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3635bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
364ef860a24SChandler Carruth   }
365ef860a24SChandler Carruth 
366ef860a24SChandler Carruth   // Now we know that this has no name.
367ef860a24SChandler Carruth 
368ef860a24SChandler Carruth   // If V has no name either, we're done.
369ef860a24SChandler Carruth   if (!V->hasName()) return;
370ef860a24SChandler Carruth 
371ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
372ef860a24SChandler Carruth   if (!ST) {
373ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
374ef860a24SChandler Carruth       // Clear V's name.
375ef860a24SChandler Carruth       V->setName("");
376ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
377ef860a24SChandler Carruth     }
378ef860a24SChandler Carruth   }
379ef860a24SChandler Carruth 
380ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
381ef860a24SChandler Carruth   ValueSymbolTable *VST;
382ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
383ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
384ef860a24SChandler Carruth 
385ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
386ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
387ef860a24SChandler Carruth   if (ST == VST) {
388ef860a24SChandler Carruth     // Take the name!
3895bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3905bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3915bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
392ef860a24SChandler Carruth     return;
393ef860a24SChandler Carruth   }
394ef860a24SChandler Carruth 
395ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
396ef860a24SChandler Carruth   // then reinsert it into ST.
397ef860a24SChandler Carruth 
398ef860a24SChandler Carruth   if (VST)
3995bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
4005bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
4015bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
4025bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
403ef860a24SChandler Carruth 
404ef860a24SChandler Carruth   if (ST)
405ef860a24SChandler Carruth     ST->reinsertValue(this);
406ef860a24SChandler Carruth }
407ef860a24SChandler Carruth 
408eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
409675bdcedSTodd Fiala #ifndef NDEBUG
410257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
411257a3536SRafael Espindola   if (!GV)
412257a3536SRafael Espindola     return;
413257a3536SRafael Espindola   const Module *M = GV->getParent();
414257a3536SRafael Espindola   if (!M)
415257a3536SRafael Espindola     return;
416257a3536SRafael Espindola   assert(M->isMaterialized());
417675bdcedSTodd Fiala #endif
418257a3536SRafael Espindola }
419257a3536SRafael Espindola 
420675bdcedSTodd Fiala #ifndef NDEBUG
42171b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
4227e2b7567SRafael Espindola                      Constant *C) {
42370573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
4247e2b7567SRafael Espindola     return false;
4257e2b7567SRafael Espindola 
4267e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
4277e2b7567SRafael Espindola     if (O == C)
4287e2b7567SRafael Espindola       return true;
4297e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
4307e2b7567SRafael Espindola     if (!CE)
4317e2b7567SRafael Espindola       continue;
4327e2b7567SRafael Espindola     if (contains(Cache, CE, C))
4337e2b7567SRafael Espindola       return true;
4347e2b7567SRafael Espindola   }
4357e2b7567SRafael Espindola   return false;
4367e2b7567SRafael Espindola }
4377e2b7567SRafael Espindola 
4387e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
4397e2b7567SRafael Espindola   if (Expr == V)
4407e2b7567SRafael Espindola     return true;
4417e2b7567SRafael Espindola 
4427e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
4437e2b7567SRafael Espindola   if (!C)
4447e2b7567SRafael Espindola     return false;
4457e2b7567SRafael Espindola 
4467e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
4477e2b7567SRafael Espindola   if (!CE)
4487e2b7567SRafael Espindola     return false;
4497e2b7567SRafael Espindola 
4507e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
4517e2b7567SRafael Espindola   return contains(Cache, CE, C);
4527e2b7567SRafael Espindola }
453ecefe5a8SEugene Zelenko #endif // NDEBUG
454ef860a24SChandler Carruth 
455e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
456ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4577e2b7567SRafael Espindola   assert(!contains(New, this) &&
4587e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
459ef860a24SChandler Carruth   assert(New->getType() == getType() &&
460ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
461ef860a24SChandler Carruth 
462ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
463ef860a24SChandler Carruth   if (HasValueHandle)
464ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
465e69ae76bSJF Bastien   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
4665bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
467ef860a24SChandler Carruth 
46881bbf742STeresa Johnson   while (!materialized_use_empty()) {
469ef860a24SChandler Carruth     Use &U = *UseList;
470ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
471ef860a24SChandler Carruth     // constant because they are uniqued.
4726b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
473ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4748914d290SMehdi Amini         C->handleOperandChange(this, New);
475ef860a24SChandler Carruth         continue;
476ef860a24SChandler Carruth       }
477ef860a24SChandler Carruth     }
478ef860a24SChandler Carruth 
479ef860a24SChandler Carruth     U.set(New);
480ef860a24SChandler Carruth   }
481ef860a24SChandler Carruth 
482ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
483ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
484ef860a24SChandler Carruth }
485ef860a24SChandler Carruth 
4861ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
487e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::Yes);
4881ed53963SDavide Italiano }
4891ed53963SDavide Italiano 
4901ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
491e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::No);
4921ed53963SDavide Italiano }
4931ed53963SDavide Italiano 
494ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
495ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
496ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
497ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
498ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
499ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
500ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
501ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
502ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
503ec6217c9SGerolf Hoflehner 
504081e990dSRoman Lebedev   replaceUsesWithIf(New, [BB](Use &U) {
505081e990dSRoman Lebedev     auto *I = dyn_cast<Instruction>(U.getUser());
506081e990dSRoman Lebedev     // Don't replace if it's an instruction in the BB basic block.
507081e990dSRoman Lebedev     return !I || I->getParent() != BB;
508081e990dSRoman Lebedev   });
509ec6217c9SGerolf Hoflehner }
510ec6217c9SGerolf Hoflehner 
511ef860a24SChandler Carruth namespace {
512ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
513ef860a24SChandler Carruth enum PointerStripKind {
514ef860a24SChandler Carruth   PSK_ZeroIndices,
5158a410bceSErich Keane   PSK_ZeroIndicesAndAliases,
5162452d703SPeter Collingbourne   PSK_ZeroIndicesSameRepresentation,
5172452d703SPeter Collingbourne   PSK_ZeroIndicesAndInvariantGroups,
518ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
519ef860a24SChandler Carruth   PSK_InBounds
520ef860a24SChandler Carruth };
521ef860a24SChandler Carruth 
52267448a8cSTyker template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
52367448a8cSTyker 
524ef860a24SChandler Carruth template <PointerStripKind StripKind>
525b7338fb1STyker static const Value *stripPointerCastsAndOffsets(
526b7338fb1STyker     const Value *V,
52767448a8cSTyker     function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
528ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
529ef860a24SChandler Carruth     return V;
530ef860a24SChandler Carruth 
531ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
532ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5331dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
534ef860a24SChandler Carruth 
535ef860a24SChandler Carruth   Visited.insert(V);
536ef860a24SChandler Carruth   do {
537b7338fb1STyker     Func(V);
5381dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
539ef860a24SChandler Carruth       switch (StripKind) {
540ef860a24SChandler Carruth       case PSK_ZeroIndices:
5418a410bceSErich Keane       case PSK_ZeroIndicesAndAliases:
5422452d703SPeter Collingbourne       case PSK_ZeroIndicesSameRepresentation:
5432452d703SPeter Collingbourne       case PSK_ZeroIndicesAndInvariantGroups:
544ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
545ef860a24SChandler Carruth           return V;
546ef860a24SChandler Carruth         break;
547ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
548ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
549ef860a24SChandler Carruth           return V;
550b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
551ef860a24SChandler Carruth       case PSK_InBounds:
552ef860a24SChandler Carruth         if (!GEP->isInBounds())
553ef860a24SChandler Carruth           return V;
554ef860a24SChandler Carruth         break;
555ef860a24SChandler Carruth       }
556ef860a24SChandler Carruth       V = GEP->getPointerOperand();
55740107ce7SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
55840107ce7SJohannes Doerfert       V = cast<Operator>(V)->getOperand(0);
5592b8d706bSRoman Lebedev       if (!V->getType()->isPointerTy())
5602b8d706bSRoman Lebedev         return V;
5612452d703SPeter Collingbourne     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
562b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
56340107ce7SJohannes Doerfert       // TODO: If we know an address space cast will not change the
56440107ce7SJohannes Doerfert       //       representation we could look through it here as well.
565ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5668a410bceSErich Keane     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
5678a410bceSErich Keane       V = cast<GlobalAlias>(V)->getAliasee();
568ef860a24SChandler Carruth     } else {
56990c09232SChandler Carruth       if (const auto *Call = dyn_cast<CallBase>(V)) {
57090c09232SChandler Carruth         if (const Value *RV = Call->getReturnedArgOperand()) {
5715c12d8feSHal Finkel           V = RV;
5725c12d8feSHal Finkel           continue;
5735c12d8feSHal Finkel         }
5745dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
575610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
576610c966aSPiotr Padlewski         // special case.
5772452d703SPeter Collingbourne         if (StripKind == PSK_ZeroIndicesAndInvariantGroups &&
57890c09232SChandler Carruth             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
57990c09232SChandler Carruth              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
58090c09232SChandler Carruth           V = Call->getArgOperand(0);
581610c966aSPiotr Padlewski           continue;
582610c966aSPiotr Padlewski         }
583610c966aSPiotr Padlewski       }
584ef860a24SChandler Carruth       return V;
585ef860a24SChandler Carruth     }
586ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
58770573dcdSDavid Blaikie   } while (Visited.insert(V).second);
588ef860a24SChandler Carruth 
589ef860a24SChandler Carruth   return V;
590ef860a24SChandler Carruth }
591ecefe5a8SEugene Zelenko } // end anonymous namespace
592ef860a24SChandler Carruth 
5931dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
5942452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
595c229a4ffSRafael Espindola }
596c229a4ffSRafael Espindola 
5978a410bceSErich Keane const Value *Value::stripPointerCastsAndAliases() const {
5988a410bceSErich Keane   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
5998a410bceSErich Keane }
6008a410bceSErich Keane 
60140107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const {
6022452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
603ef860a24SChandler Carruth }
604ef860a24SChandler Carruth 
6051dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
606ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
607ef860a24SChandler Carruth }
608ef860a24SChandler Carruth 
6095dde8094SPiotr Padlewski const Value *Value::stripPointerCastsAndInvariantGroups() const {
6102452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this);
611610c966aSPiotr Padlewski }
612610c966aSPiotr Padlewski 
613e5780776SKuter Dinel const Value *Value::stripAndAccumulateConstantOffsets(
614e5780776SKuter Dinel     const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
615e5780776SKuter Dinel     function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
6163ed286a3SJohannes Doerfert   if (!getType()->isPtrOrPtrVectorTy())
617989e6308SChandler Carruth     return this;
618989e6308SChandler Carruth 
6193ed286a3SJohannes Doerfert   unsigned BitWidth = Offset.getBitWidth();
6203ed286a3SJohannes Doerfert   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
621945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
622989e6308SChandler Carruth 
623989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
624989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
6251dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
626989e6308SChandler Carruth   Visited.insert(this);
6271dd20e65SCraig Topper   const Value *V = this;
628989e6308SChandler Carruth   do {
6291dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
6303ed286a3SJohannes Doerfert       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
6313ed286a3SJohannes Doerfert       if (!AllowNonInbounds && !GEP->isInBounds())
632989e6308SChandler Carruth         return V;
6333ed286a3SJohannes Doerfert 
6343ed286a3SJohannes Doerfert       // If one of the values we have visited is an addrspacecast, then
6353ed286a3SJohannes Doerfert       // the pointer type of this GEP may be different from the type
6363ed286a3SJohannes Doerfert       // of the Ptr parameter which was passed to this function.  This
6373ed286a3SJohannes Doerfert       // means when we construct GEPOffset, we need to use the size
6383ed286a3SJohannes Doerfert       // of GEP's pointer type rather than the size of the original
6393ed286a3SJohannes Doerfert       // pointer type.
6403ed286a3SJohannes Doerfert       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
641e5780776SKuter Dinel       if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
642989e6308SChandler Carruth         return V;
6433ed286a3SJohannes Doerfert 
6443ed286a3SJohannes Doerfert       // Stop traversal if the pointer offset wouldn't fit in the bit-width
6453ed286a3SJohannes Doerfert       // provided by the Offset argument. This can happen due to AddrSpaceCast
6463ed286a3SJohannes Doerfert       // stripping.
6473ed286a3SJohannes Doerfert       if (GEPOffset.getMinSignedBits() > BitWidth)
6483ed286a3SJohannes Doerfert         return V;
6493ed286a3SJohannes Doerfert 
650e5780776SKuter Dinel       // External Analysis can return a result higher/lower than the value
651e5780776SKuter Dinel       // represents. We need to detect overflow/underflow.
652e5780776SKuter Dinel       APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
653e5780776SKuter Dinel       if (!ExternalAnalysis) {
654e5780776SKuter Dinel         Offset += GEPOffsetST;
655e5780776SKuter Dinel       } else {
656e5780776SKuter Dinel         bool Overflow = false;
657e5780776SKuter Dinel         APInt OldOffset = Offset;
658e5780776SKuter Dinel         Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
659e5780776SKuter Dinel         if (Overflow) {
660e5780776SKuter Dinel           Offset = OldOffset;
661e5780776SKuter Dinel           return V;
662e5780776SKuter Dinel         }
663e5780776SKuter Dinel       }
664989e6308SChandler Carruth       V = GEP->getPointerOperand();
6653ed286a3SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
6663ed286a3SJohannes Doerfert                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
667989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
6681dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
6693ed286a3SJohannes Doerfert       if (!GA->isInterposable())
670989e6308SChandler Carruth         V = GA->getAliasee();
6713ed286a3SJohannes Doerfert     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
6723ed286a3SJohannes Doerfert         if (const Value *RV = Call->getReturnedArgOperand())
6735c12d8feSHal Finkel           V = RV;
6745c12d8feSHal Finkel     }
6753ed286a3SJohannes Doerfert     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
67670573dcdSDavid Blaikie   } while (Visited.insert(V).second);
677989e6308SChandler Carruth 
678989e6308SChandler Carruth   return V;
679989e6308SChandler Carruth }
680989e6308SChandler Carruth 
681b7338fb1STyker const Value *
682b7338fb1STyker Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
683b7338fb1STyker   return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
684ef860a24SChandler Carruth }
685ef860a24SChandler Carruth 
6863603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
68700953cbeSSanjoy Das                                                bool &CanBeNull) const {
688345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
689345f0148SArtur Pilipenko 
6903603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
691345f0148SArtur Pilipenko   CanBeNull = false;
692345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
693345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
6942da4d9d8SBjorn Steinbrink     if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
695c27f81b9SBjorn Steinbrink       Type *PT = cast<PointerType>(A->getType())->getElementType();
6962da4d9d8SBjorn Steinbrink       if (PT->isSized())
697ebec984eSEli Friedman         DerefBytes = DL.getTypeStoreSize(PT).getKnownMinSize();
69800953cbeSSanjoy Das     }
699345f0148SArtur Pilipenko     if (DerefBytes == 0) {
700345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
701345f0148SArtur Pilipenko       CanBeNull = true;
702345f0148SArtur Pilipenko     }
70390c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
70490c09232SChandler Carruth     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
705345f0148SArtur Pilipenko     if (DerefBytes == 0) {
70690c09232SChandler Carruth       DerefBytes =
70790c09232SChandler Carruth           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
708345f0148SArtur Pilipenko       CanBeNull = true;
709345f0148SArtur Pilipenko     }
710345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
711345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
712345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
713345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
714345f0148SArtur Pilipenko     }
715345f0148SArtur Pilipenko     if (DerefBytes == 0) {
716345f0148SArtur Pilipenko       if (MDNode *MD =
717345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
718345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
719345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
720345f0148SArtur Pilipenko       }
721345f0148SArtur Pilipenko       CanBeNull = true;
722345f0148SArtur Pilipenko     }
7236f13637aSRyan Taylor   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
7246f13637aSRyan Taylor     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
7256f13637aSRyan Taylor       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
7266f13637aSRyan Taylor       DerefBytes = CI->getLimitedValue();
7276f13637aSRyan Taylor     }
7286f13637aSRyan Taylor     if (DerefBytes == 0) {
7296f13637aSRyan Taylor       if (MDNode *MD =
7306f13637aSRyan Taylor               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
7316f13637aSRyan Taylor         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
7326f13637aSRyan Taylor         DerefBytes = CI->getLimitedValue();
7336f13637aSRyan Taylor       }
7346f13637aSRyan Taylor       CanBeNull = true;
7356f13637aSRyan Taylor     }
73600953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
737030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
738ebec984eSEli Friedman       DerefBytes =
739ebec984eSEli Friedman           DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
74000953cbeSSanjoy Das       CanBeNull = false;
74100953cbeSSanjoy Das     }
74200953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
74300953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
74400953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
74500953cbeSSanjoy Das       // CanBeNull flag.
746ebec984eSEli Friedman       DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
74700953cbeSSanjoy Das       CanBeNull = false;
74800953cbeSSanjoy Das     }
749345f0148SArtur Pilipenko   }
750345f0148SArtur Pilipenko   return DerefBytes;
751345f0148SArtur Pilipenko }
752345f0148SArtur Pilipenko 
753f26bdb53SEli Friedman Align Value::getPointerAlignment(const DataLayout &DL) const {
754ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
755ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
756308e82ecSMichael Platings     if (isa<Function>(GO)) {
757f26bdb53SEli Friedman       Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
758308e82ecSMichael Platings       switch (DL.getFunctionPtrAlignType()) {
759308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::Independent:
760bae629b9SGuillaume Chatelet         return FunctionPtrAlign;
761308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
762f26bdb53SEli Friedman         return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
763308e82ecSMichael Platings       }
7646200a568SGuillaume Chatelet       llvm_unreachable("Unhandled FunctionPtrAlignType");
765308e82ecSMichael Platings     }
766bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(GO->getAlignment());
767bae629b9SGuillaume Chatelet     if (!Alignment) {
768ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
769ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
770ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
771ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
772ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
773ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
774ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
775368a5e3aSGuillaume Chatelet             return DL.getPreferredAlign(GVar);
776ae51afc5SArtur Pilipenko           else
7779068bccbSGuillaume Chatelet             return DL.getABITypeAlign(ObjectType);
778ae51afc5SArtur Pilipenko         }
779ae51afc5SArtur Pilipenko       }
780ae51afc5SArtur Pilipenko     }
781f26bdb53SEli Friedman     return Alignment.valueOrOne();
782ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
7839068bccbSGuillaume Chatelet     const MaybeAlign Alignment = A->getParamAlign();
784bae629b9SGuillaume Chatelet     if (!Alignment && A->hasStructRetAttr()) {
785ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
786ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
787ae51afc5SArtur Pilipenko       if (EltTy->isSized())
7889068bccbSGuillaume Chatelet         return DL.getABITypeAlign(EltTy);
789ae51afc5SArtur Pilipenko     }
790f26bdb53SEli Friedman     return Alignment.valueOrOne();
791c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
792f26bdb53SEli Friedman     return AI->getAlign();
793afd4a37bSHideto Ueno   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
794f26bdb53SEli Friedman     MaybeAlign Alignment = Call->getRetAlign();
795bae629b9SGuillaume Chatelet     if (!Alignment && Call->getCalledFunction())
796f26bdb53SEli Friedman       Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
797f26bdb53SEli Friedman     return Alignment.valueOrOne();
7986200a568SGuillaume Chatelet   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
799ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
800ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
801f26bdb53SEli Friedman       return Align(CI->getLimitedValue());
802ae51afc5SArtur Pilipenko     }
803a6492e22SRoman Lebedev   } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
804a6492e22SRoman Lebedev     if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
805a6492e22SRoman Lebedev             const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
806a6492e22SRoman Lebedev             /*OnlyIfReduced=*/true))) {
807a6492e22SRoman Lebedev       size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
808a6492e22SRoman Lebedev       // While the actual alignment may be large, elsewhere we have
809a6492e22SRoman Lebedev       // an arbitrary upper alignmet limit, so let's clamp to it.
810a6492e22SRoman Lebedev       return Align(TrailingZeros < Value::MaxAlignmentExponent
811a6492e22SRoman Lebedev                        ? uint64_t(1) << TrailingZeros
812a6492e22SRoman Lebedev                        : Value::MaximumAlignment);
813a6492e22SRoman Lebedev     }
8146200a568SGuillaume Chatelet   }
815f26bdb53SEli Friedman   return Align(1);
816ae51afc5SArtur Pilipenko }
817ae51afc5SArtur Pilipenko 
8181dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
8191dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
8201dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
821ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
822ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
823ef860a24SChandler Carruth   return this;
824ef860a24SChandler Carruth }
825ef860a24SChandler Carruth 
826ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
827ef860a24SChandler Carruth 
8283441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
8293441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
8303441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
8313441ffe9SDuncan P. N. Exon Smith     return;
8323441ffe9SDuncan P. N. Exon Smith 
8333441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
8343441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
8353441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
8363441ffe9SDuncan P. N. Exon Smith   while (Current) {
8373441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
8383441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
83991ef7cb5SJay Foad     Head->Prev = &Current->Next;
8403441ffe9SDuncan P. N. Exon Smith     Head = Current;
8413441ffe9SDuncan P. N. Exon Smith     Current = Next;
8423441ffe9SDuncan P. N. Exon Smith   }
8433441ffe9SDuncan P. N. Exon Smith   UseList = Head;
84491ef7cb5SJay Foad   Head->Prev = &UseList;
8453441ffe9SDuncan P. N. Exon Smith }
8463441ffe9SDuncan P. N. Exon Smith 
847ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
848ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
849ad830022SArnold Schwaighofer   if (Arg)
850ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
851ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
852ad830022SArnold Schwaighofer   if (!Alloca)
853ad830022SArnold Schwaighofer     return false;
854ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
855ad830022SArnold Schwaighofer }
856ad830022SArnold Schwaighofer 
857ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
858ef860a24SChandler Carruth //                             ValueHandleBase Class
859ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
860ef860a24SChandler Carruth 
861ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
862ef860a24SChandler Carruth   assert(List && "Handle list is null?");
863ef860a24SChandler Carruth 
864ef860a24SChandler Carruth   // Splice ourselves into the list.
865ef860a24SChandler Carruth   Next = *List;
866ef860a24SChandler Carruth   *List = this;
867ef860a24SChandler Carruth   setPrevPtr(List);
868ef860a24SChandler Carruth   if (Next) {
869ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
8706f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
871ef860a24SChandler Carruth   }
872ef860a24SChandler Carruth }
873ef860a24SChandler Carruth 
874ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
875ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
876ef860a24SChandler Carruth 
877ef860a24SChandler Carruth   Next = List->Next;
878ef860a24SChandler Carruth   setPrevPtr(&List->Next);
879ef860a24SChandler Carruth   List->Next = this;
880ef860a24SChandler Carruth   if (Next)
881ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
882ef860a24SChandler Carruth }
883ef860a24SChandler Carruth 
884ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
8856f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
886ef860a24SChandler Carruth 
8876f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
888ef860a24SChandler Carruth 
8896f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
890ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
891ef860a24SChandler Carruth     // ValueHandles map already.
8926f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
8932617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
894ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
895ef860a24SChandler Carruth     return;
896ef860a24SChandler Carruth   }
897ef860a24SChandler Carruth 
898ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
899ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
900ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
901ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
902ef860a24SChandler Carruth   // updating the stale pointers only if needed.
903ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
904ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
905ef860a24SChandler Carruth 
9066f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
9072617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
908ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
9096f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
910ef860a24SChandler Carruth 
911ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
912ef860a24SChandler Carruth   // walk the table.
913ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
914ef860a24SChandler Carruth       Handles.size() == 1) {
915ef860a24SChandler Carruth     return;
916ef860a24SChandler Carruth   }
917ef860a24SChandler Carruth 
918ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
919ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
920ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
9216f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
922ef860a24SChandler Carruth            "List invariant broken!");
923ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
924ef860a24SChandler Carruth   }
925ef860a24SChandler Carruth }
926ef860a24SChandler Carruth 
927ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
9286f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
929ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
930ef860a24SChandler Carruth 
931ef860a24SChandler Carruth   // Unlink this from its use list.
932ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
933ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
934ef860a24SChandler Carruth 
935ef860a24SChandler Carruth   *PrevPtr = Next;
936ef860a24SChandler Carruth   if (Next) {
937ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
938ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
939ef860a24SChandler Carruth     return;
940ef860a24SChandler Carruth   }
941ef860a24SChandler Carruth 
942ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
943ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
944ef860a24SChandler Carruth   // map.
9456f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
946ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
947ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
9486f08789dSSanjoy Das     Handles.erase(getValPtr());
9496f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
950ef860a24SChandler Carruth   }
951ef860a24SChandler Carruth }
952ef860a24SChandler Carruth 
953ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
954ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
955ef860a24SChandler Carruth 
956ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
957ef860a24SChandler Carruth   // HasValueHandle flag is set.
958ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
959ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
960ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
961ef860a24SChandler Carruth 
962ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
963ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
964ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
965ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
966ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
967ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
968ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
969ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
970ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
971ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
972ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
973ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
974ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
975ef860a24SChandler Carruth 
976ef860a24SChandler Carruth     switch (Entry->getKind()) {
977ef860a24SChandler Carruth     case Assert:
978ef860a24SChandler Carruth       break;
979f1c0eafdSSanjoy Das     case Weak:
980e6bca0eeSSanjoy Das     case WeakTracking:
981f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
982f1c0eafdSSanjoy Das       // from the list.
983c620761cSCraig Topper       Entry->operator=(nullptr);
984ef860a24SChandler Carruth       break;
985ef860a24SChandler Carruth     case Callback:
986ef860a24SChandler Carruth       // Forward to the subclass's implementation.
987ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
988ef860a24SChandler Carruth       break;
989ef860a24SChandler Carruth     }
990ef860a24SChandler Carruth   }
991ef860a24SChandler Carruth 
992ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
993ef860a24SChandler Carruth   if (V->HasValueHandle) {
994ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
995ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
996ef860a24SChandler Carruth            << "\n";
997ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
998ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
999ef860a24SChandler Carruth                        " value!");
1000ef860a24SChandler Carruth 
1001ef860a24SChandler Carruth #endif
1002ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
1003ef860a24SChandler Carruth   }
1004ef860a24SChandler Carruth }
1005ef860a24SChandler Carruth 
1006ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1007ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1008ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
1009c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
1010c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
1011ef860a24SChandler Carruth 
1012ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
1013ef860a24SChandler Carruth   // HasValueHandle flag is set.
1014ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
1015ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1016ef860a24SChandler Carruth 
1017ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
1018ef860a24SChandler Carruth 
1019ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
1020ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
1021ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
1022ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
1023ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1024ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
1025ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
1026ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1027ef860a24SChandler Carruth 
1028ef860a24SChandler Carruth     switch (Entry->getKind()) {
1029ef860a24SChandler Carruth     case Assert:
1030f1c0eafdSSanjoy Das     case Weak:
1031f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
1032ef860a24SChandler Carruth       break;
1033e6bca0eeSSanjoy Das     case WeakTracking:
10342cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
1035ef860a24SChandler Carruth       Entry->operator=(New);
1036ef860a24SChandler Carruth       break;
1037ef860a24SChandler Carruth     case Callback:
1038ef860a24SChandler Carruth       // Forward to the subclass's implementation.
1039ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1040ef860a24SChandler Carruth       break;
1041ef860a24SChandler Carruth     }
1042ef860a24SChandler Carruth   }
1043ef860a24SChandler Carruth 
1044ef860a24SChandler Carruth #ifndef NDEBUG
10458a623820SSanjoy Das   // If any new weak value handles were added while processing the
1046ef860a24SChandler Carruth   // list, then complain about it now.
1047ef860a24SChandler Carruth   if (Old->HasValueHandle)
1048ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1049ef860a24SChandler Carruth       switch (Entry->getKind()) {
1050e6bca0eeSSanjoy Das       case WeakTracking:
1051ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
1052ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
1053ef860a24SChandler Carruth                << New->getName() << "\n";
10548a623820SSanjoy Das         llvm_unreachable(
1055e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the old value!\n");
1056ef860a24SChandler Carruth       default:
1057ef860a24SChandler Carruth         break;
1058ef860a24SChandler Carruth       }
1059ef860a24SChandler Carruth #endif
1060ef860a24SChandler Carruth }
1061ef860a24SChandler Carruth 
1062d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
1063d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
1064