xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 96ab8726)
1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===//
2ef860a24SChandler Carruth //
3ef860a24SChandler Carruth //                     The LLVM Compiler Infrastructure
4ef860a24SChandler Carruth //
5ef860a24SChandler Carruth // This file is distributed under the University of Illinois Open Source
6ef860a24SChandler Carruth // License. See LICENSE.TXT for details.
7ef860a24SChandler Carruth //
8ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
9ef860a24SChandler Carruth //
10ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes.
11ef860a24SChandler Carruth //
12ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
13ef860a24SChandler Carruth 
149fb823bbSChandler Carruth #include "llvm/IR/Value.h"
15ef860a24SChandler Carruth #include "LLVMContextImpl.h"
16ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h"
17ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h"
18b0407ba0SHal Finkel #include "llvm/IR/CallSite.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
209fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
212e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
229fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
23*96ab8726SReid 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"
30a7343d65SRamkumar Ramachandra #include "llvm/IR/Statepoint.h"
314220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
329fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.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 
41ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
42ef860a24SChandler Carruth //                                Value Class
43ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
44ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
45ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
4616bf89ecSReid Kleckner   return Ty;
47ef860a24SChandler Carruth }
48ef860a24SChandler Carruth 
49ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
507349ab93SOwen Anderson     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
517349ab93SOwen Anderson       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
52b4eede2cSPete Cooper       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
53ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
54ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
55ef860a24SChandler Carruth   // constructed.
56ef860a24SChandler Carruth   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke)
57ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
58ef860a24SChandler Carruth            "invalid CallInst type!");
59ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
60ef860a24SChandler Carruth            (SubclassID < ConstantFirstVal || SubclassID > ConstantLastVal))
61ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
62ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
63*96ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
641762ad3eSReid Kleckner                 "Value too big");
65ef860a24SChandler Carruth }
66ef860a24SChandler Carruth 
67ef860a24SChandler Carruth Value::~Value() {
68ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
69ef860a24SChandler Carruth   if (HasValueHandle)
70ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
715bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
725bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
73ef860a24SChandler Carruth 
74ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
75ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
76ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
77b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
78b93fb82bSAndrew Kaylor   // the value is still being referenced.
79ef860a24SChandler Carruth   //
80ef860a24SChandler Carruth   if (!use_empty()) {
81ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
82b93fb82bSAndrew Kaylor     for (auto *U : users())
83b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
84ef860a24SChandler Carruth   }
85ef860a24SChandler Carruth #endif
86ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
87ef860a24SChandler Carruth 
88ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
89ef860a24SChandler Carruth   // at this point.
905bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
91ef860a24SChandler Carruth }
92ef860a24SChandler Carruth 
93*96ab8726SReid Kleckner void Value::deleteValue() {
94*96ab8726SReid Kleckner   switch (getValueID()) {
95*96ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
96*96ab8726SReid Kleckner   case Value::Name##Val:                                                       \
97*96ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
98*96ab8726SReid Kleckner     break;
99*96ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
100*96ab8726SReid Kleckner   case Value::Name##Val:                                                       \
101*96ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
102*96ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
103*96ab8726SReid Kleckner     break;
104*96ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
105*96ab8726SReid Kleckner #include "llvm/IR/Value.def"
106*96ab8726SReid Kleckner 
107*96ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
108*96ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
109*96ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
110*96ab8726SReid Kleckner     break;
111*96ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
112*96ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
113*96ab8726SReid Kleckner 
114*96ab8726SReid Kleckner   default:
115*96ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
116*96ab8726SReid Kleckner   }
117*96ab8726SReid Kleckner }
118*96ab8726SReid Kleckner 
1195bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1205bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
1215bf8fef5SDuncan P. N. Exon Smith   if (Name)
1225bf8fef5SDuncan P. N. Exon Smith     Name->Destroy();
1235bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1245bf8fef5SDuncan P. N. Exon Smith }
1255bf8fef5SDuncan P. N. Exon Smith 
126ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
127ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
128ef860a24SChandler Carruth 
129ef860a24SChandler Carruth   for (; N; --N, ++UI)
130ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
131ef860a24SChandler Carruth   return UI == E;
132ef860a24SChandler Carruth }
133ef860a24SChandler Carruth 
134ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
135ef860a24SChandler Carruth   const_use_iterator UI = use_begin(), E = use_end();
136ef860a24SChandler Carruth 
137ef860a24SChandler Carruth   for (; N; --N, ++UI)
138ef860a24SChandler Carruth     if (UI == E) return false;  // Too few.
139ef860a24SChandler Carruth 
140ef860a24SChandler Carruth   return true;
141ef860a24SChandler Carruth }
142ef860a24SChandler Carruth 
143ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1440925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1450925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1460925b24dSJakob Stoklund Olesen   // usually one is quite short.
1470925b24dSJakob Stoklund Olesen   //
1480925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1490925b24dSJakob Stoklund Olesen   // search to the shorter list.
1500925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
151cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1520925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1530925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
15442531260SDavid Majnemer     if (is_contained(BI->operands(), this))
155ef860a24SChandler Carruth       return true;
1560925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
15742531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
158ef860a24SChandler Carruth     if (User && User->getParent() == BB)
159ef860a24SChandler Carruth       return true;
160ef860a24SChandler Carruth   }
161ef860a24SChandler Carruth   return false;
162ef860a24SChandler Carruth }
163ef860a24SChandler Carruth 
164ef860a24SChandler Carruth unsigned Value::getNumUses() const {
165ef860a24SChandler Carruth   return (unsigned)std::distance(use_begin(), use_end());
166ef860a24SChandler Carruth }
167ef860a24SChandler Carruth 
168ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
169c620761cSCraig Topper   ST = nullptr;
170ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
171ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
172ef860a24SChandler Carruth       if (Function *PP = P->getParent())
173a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
174ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
175ef860a24SChandler Carruth     if (Function *P = BB->getParent())
176a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
177ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
178ef860a24SChandler Carruth     if (Module *P = GV->getParent())
179ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
180ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
181ef860a24SChandler Carruth     if (Function *P = A->getParent())
182a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
1835bf8fef5SDuncan P. N. Exon Smith   } else {
184ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
185ef860a24SChandler Carruth     return true;  // no name is setable for this.
186ef860a24SChandler Carruth   }
187ef860a24SChandler Carruth   return false;
188ef860a24SChandler Carruth }
189ef860a24SChandler Carruth 
1907349ab93SOwen Anderson ValueName *Value::getValueName() const {
1917349ab93SOwen Anderson   if (!HasName) return nullptr;
1927349ab93SOwen Anderson 
1937349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
1947349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
1957349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
1967349ab93SOwen Anderson          "No name entry found!");
1977349ab93SOwen Anderson 
1987349ab93SOwen Anderson   return I->second;
1997349ab93SOwen Anderson }
2007349ab93SOwen Anderson 
2017349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2027349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2037349ab93SOwen Anderson 
2047349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2057349ab93SOwen Anderson          "HasName bit out of sync!");
2067349ab93SOwen Anderson 
2077349ab93SOwen Anderson   if (!VN) {
2087349ab93SOwen Anderson     if (HasName)
2097349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2107349ab93SOwen Anderson     HasName = false;
2117349ab93SOwen Anderson     return;
2127349ab93SOwen Anderson   }
2137349ab93SOwen Anderson 
2147349ab93SOwen Anderson   HasName = true;
2157349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2167349ab93SOwen Anderson }
2177349ab93SOwen Anderson 
218ef860a24SChandler Carruth StringRef Value::getName() const {
219ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
220ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
221ef860a24SChandler Carruth   // terminated.
2227349ab93SOwen Anderson   if (!hasName())
2235bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2245bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
225ef860a24SChandler Carruth }
226ef860a24SChandler Carruth 
227a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
22809b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
22950af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
23009b4a8daSMehdi Amini     return;
23109b4a8daSMehdi Amini 
232ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
233ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
234ef860a24SChandler Carruth     return;
235ef860a24SChandler Carruth 
236ef860a24SChandler Carruth   SmallString<256> NameData;
237ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
23809d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
23909d689f9SRafael Espindola          "Null bytes are not allowed in names");
240ef860a24SChandler Carruth 
241ef860a24SChandler Carruth   // Name isn't changing?
242ef860a24SChandler Carruth   if (getName() == NameRef)
243ef860a24SChandler Carruth     return;
244ef860a24SChandler Carruth 
245ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
246ef860a24SChandler Carruth 
247ef860a24SChandler Carruth   // Get the symbol table to update for this object.
248ef860a24SChandler Carruth   ValueSymbolTable *ST;
249ef860a24SChandler Carruth   if (getSymTab(this, ST))
250ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
251ef860a24SChandler Carruth 
252ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
253ef860a24SChandler Carruth     if (NameRef.empty()) {
254ef860a24SChandler Carruth       // Free the name for this value.
2555bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
256ef860a24SChandler Carruth       return;
257ef860a24SChandler Carruth     }
258ef860a24SChandler Carruth 
259ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
260ef860a24SChandler Carruth     // then reallocated.
2615bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
262ef860a24SChandler Carruth 
263ef860a24SChandler Carruth     // Create the new name.
2645bf8fef5SDuncan P. N. Exon Smith     setValueName(ValueName::Create(NameRef));
2655bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
266ef860a24SChandler Carruth     return;
267ef860a24SChandler Carruth   }
268ef860a24SChandler Carruth 
269ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
270ef860a24SChandler Carruth   // then reallocated.
271ef860a24SChandler Carruth   if (hasName()) {
272ef860a24SChandler Carruth     // Remove old name.
2735bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
2745bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
275ef860a24SChandler Carruth 
276ef860a24SChandler Carruth     if (NameRef.empty())
277ef860a24SChandler Carruth       return;
278ef860a24SChandler Carruth   }
279ef860a24SChandler Carruth 
280ef860a24SChandler Carruth   // Name is changing to something new.
2815bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
282ef860a24SChandler Carruth }
283ef860a24SChandler Carruth 
284a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
285a7c0c18cSPete Cooper   setNameImpl(NewName);
286a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
287a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
288a7c0c18cSPete Cooper }
289a7c0c18cSPete Cooper 
290ef860a24SChandler Carruth void Value::takeName(Value *V) {
291c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
292ef860a24SChandler Carruth   // If this value has a name, drop it.
293ef860a24SChandler Carruth   if (hasName()) {
294ef860a24SChandler Carruth     // Get the symtab this is in.
295ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
296ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
297ef860a24SChandler Carruth       // it has one.
298ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
299ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
300ef860a24SChandler Carruth     }
301ef860a24SChandler Carruth 
302ef860a24SChandler Carruth     // Remove old name.
303ef860a24SChandler Carruth     if (ST)
3045bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3055bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
306ef860a24SChandler Carruth   }
307ef860a24SChandler Carruth 
308ef860a24SChandler Carruth   // Now we know that this has no name.
309ef860a24SChandler Carruth 
310ef860a24SChandler Carruth   // If V has no name either, we're done.
311ef860a24SChandler Carruth   if (!V->hasName()) return;
312ef860a24SChandler Carruth 
313ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
314ef860a24SChandler Carruth   if (!ST) {
315ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
316ef860a24SChandler Carruth       // Clear V's name.
317ef860a24SChandler Carruth       V->setName("");
318ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
319ef860a24SChandler Carruth     }
320ef860a24SChandler Carruth   }
321ef860a24SChandler Carruth 
322ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
323ef860a24SChandler Carruth   ValueSymbolTable *VST;
324ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
325ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
326ef860a24SChandler Carruth 
327ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
328ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
329ef860a24SChandler Carruth   if (ST == VST) {
330ef860a24SChandler Carruth     // Take the name!
3315bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3325bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3335bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
334ef860a24SChandler Carruth     return;
335ef860a24SChandler Carruth   }
336ef860a24SChandler Carruth 
337ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
338ef860a24SChandler Carruth   // then reinsert it into ST.
339ef860a24SChandler Carruth 
340ef860a24SChandler Carruth   if (VST)
3415bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
3425bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
3435bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
3445bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
345ef860a24SChandler Carruth 
346ef860a24SChandler Carruth   if (ST)
347ef860a24SChandler Carruth     ST->reinsertValue(this);
348ef860a24SChandler Carruth }
349ef860a24SChandler Carruth 
350eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
351675bdcedSTodd Fiala #ifndef NDEBUG
352257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
353257a3536SRafael Espindola   if (!GV)
354257a3536SRafael Espindola     return;
355257a3536SRafael Espindola   const Module *M = GV->getParent();
356257a3536SRafael Espindola   if (!M)
357257a3536SRafael Espindola     return;
358257a3536SRafael Espindola   assert(M->isMaterialized());
359675bdcedSTodd Fiala #endif
360257a3536SRafael Espindola }
361257a3536SRafael Espindola 
362675bdcedSTodd Fiala #ifndef NDEBUG
36371b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
3647e2b7567SRafael Espindola                      Constant *C) {
36570573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
3667e2b7567SRafael Espindola     return false;
3677e2b7567SRafael Espindola 
3687e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
3697e2b7567SRafael Espindola     if (O == C)
3707e2b7567SRafael Espindola       return true;
3717e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3727e2b7567SRafael Espindola     if (!CE)
3737e2b7567SRafael Espindola       continue;
3747e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3757e2b7567SRafael Espindola       return true;
3767e2b7567SRafael Espindola   }
3777e2b7567SRafael Espindola   return false;
3787e2b7567SRafael Espindola }
3797e2b7567SRafael Espindola 
3807e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3817e2b7567SRafael Espindola   if (Expr == V)
3827e2b7567SRafael Espindola     return true;
3837e2b7567SRafael Espindola 
3847e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3857e2b7567SRafael Espindola   if (!C)
3867e2b7567SRafael Espindola     return false;
3877e2b7567SRafael Espindola 
3887e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
3897e2b7567SRafael Espindola   if (!CE)
3907e2b7567SRafael Espindola     return false;
3917e2b7567SRafael Espindola 
3927e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
3937e2b7567SRafael Espindola   return contains(Cache, CE, C);
3947e2b7567SRafael Espindola }
395ecefe5a8SEugene Zelenko #endif // NDEBUG
396ef860a24SChandler Carruth 
3971ed53963SDavide Italiano void Value::doRAUW(Value *New, bool NoMetadata) {
398ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
3997e2b7567SRafael Espindola   assert(!contains(New, this) &&
4007e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
401ef860a24SChandler Carruth   assert(New->getType() == getType() &&
402ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
403ef860a24SChandler Carruth 
404ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
405ef860a24SChandler Carruth   if (HasValueHandle)
406ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
4071ed53963SDavide Italiano   if (!NoMetadata && isUsedByMetadata())
4085bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
409ef860a24SChandler Carruth 
410ef860a24SChandler Carruth   while (!use_empty()) {
411ef860a24SChandler Carruth     Use &U = *UseList;
412ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
413ef860a24SChandler Carruth     // constant because they are uniqued.
4146b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
415ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4168914d290SMehdi Amini         C->handleOperandChange(this, New);
417ef860a24SChandler Carruth         continue;
418ef860a24SChandler Carruth       }
419ef860a24SChandler Carruth     }
420ef860a24SChandler Carruth 
421ef860a24SChandler Carruth     U.set(New);
422ef860a24SChandler Carruth   }
423ef860a24SChandler Carruth 
424ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
425ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
426ef860a24SChandler Carruth }
427ef860a24SChandler Carruth 
4281ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
4291ed53963SDavide Italiano   doRAUW(New, false /* NoMetadata */);
4301ed53963SDavide Italiano }
4311ed53963SDavide Italiano 
4321ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
4331ed53963SDavide Italiano   doRAUW(New, true /* NoMetadata */);
4341ed53963SDavide Italiano }
4351ed53963SDavide Italiano 
436ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
437ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
438ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
439ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
440ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
441ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
442ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
443ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
444ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
445ec6217c9SGerolf Hoflehner 
446ec6217c9SGerolf Hoflehner   use_iterator UI = use_begin(), E = use_end();
447ec6217c9SGerolf Hoflehner   for (; UI != E;) {
448ec6217c9SGerolf Hoflehner     Use &U = *UI;
449ec6217c9SGerolf Hoflehner     ++UI;
450ec6217c9SGerolf Hoflehner     auto *Usr = dyn_cast<Instruction>(U.getUser());
451ec6217c9SGerolf Hoflehner     if (Usr && Usr->getParent() == BB)
452ec6217c9SGerolf Hoflehner       continue;
453ec6217c9SGerolf Hoflehner     U.set(New);
454ec6217c9SGerolf Hoflehner   }
455ec6217c9SGerolf Hoflehner }
456ec6217c9SGerolf Hoflehner 
457ef860a24SChandler Carruth namespace {
458ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
459ef860a24SChandler Carruth enum PointerStripKind {
460ef860a24SChandler Carruth   PSK_ZeroIndices,
461c229a4ffSRafael Espindola   PSK_ZeroIndicesAndAliases,
462610c966aSPiotr Padlewski   PSK_ZeroIndicesAndAliasesAndBarriers,
463ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
464ef860a24SChandler Carruth   PSK_InBounds
465ef860a24SChandler Carruth };
466ef860a24SChandler Carruth 
467ef860a24SChandler Carruth template <PointerStripKind StripKind>
4681dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) {
469ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
470ef860a24SChandler Carruth     return V;
471ef860a24SChandler Carruth 
472ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
473ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
4741dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
475ef860a24SChandler Carruth 
476ef860a24SChandler Carruth   Visited.insert(V);
477ef860a24SChandler Carruth   do {
4781dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
479ef860a24SChandler Carruth       switch (StripKind) {
480c229a4ffSRafael Espindola       case PSK_ZeroIndicesAndAliases:
481610c966aSPiotr Padlewski       case PSK_ZeroIndicesAndAliasesAndBarriers:
482ef860a24SChandler Carruth       case PSK_ZeroIndices:
483ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
484ef860a24SChandler Carruth           return V;
485ef860a24SChandler Carruth         break;
486ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
487ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
488ef860a24SChandler Carruth           return V;
489b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
490ef860a24SChandler Carruth       case PSK_InBounds:
491ef860a24SChandler Carruth         if (!GEP->isInBounds())
492ef860a24SChandler Carruth           return V;
493ef860a24SChandler Carruth         break;
494ef860a24SChandler Carruth       }
495ef860a24SChandler Carruth       V = GEP->getPointerOperand();
496b03bd4d9SMatt Arsenault     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
497b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
498ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
4991dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
5005ce32728SSanjoy Das       if (StripKind == PSK_ZeroIndices || GA->isInterposable())
501ef860a24SChandler Carruth         return V;
502ef860a24SChandler Carruth       V = GA->getAliasee();
503ef860a24SChandler Carruth     } else {
504610c966aSPiotr Padlewski       if (auto CS = ImmutableCallSite(V)) {
5051dd20e65SCraig Topper         if (const Value *RV = CS.getReturnedArgOperand()) {
5065c12d8feSHal Finkel           V = RV;
5075c12d8feSHal Finkel           continue;
5085c12d8feSHal Finkel         }
509610c966aSPiotr Padlewski         // The result of invariant.group.barrier must alias it's argument,
510610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
511610c966aSPiotr Padlewski         // special case.
512610c966aSPiotr Padlewski         if (StripKind == PSK_ZeroIndicesAndAliasesAndBarriers &&
513610c966aSPiotr Padlewski             CS.getIntrinsicID() == Intrinsic::invariant_group_barrier) {
514610c966aSPiotr Padlewski           V = CS.getArgOperand(0);
515610c966aSPiotr Padlewski           continue;
516610c966aSPiotr Padlewski         }
517610c966aSPiotr Padlewski       }
518ef860a24SChandler Carruth       return V;
519ef860a24SChandler Carruth     }
520ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
52170573dcdSDavid Blaikie   } while (Visited.insert(V).second);
522ef860a24SChandler Carruth 
523ef860a24SChandler Carruth   return V;
524ef860a24SChandler Carruth }
525ecefe5a8SEugene Zelenko } // end anonymous namespace
526ef860a24SChandler Carruth 
5271dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
528c229a4ffSRafael Espindola   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
529c229a4ffSRafael Espindola }
530c229a4ffSRafael Espindola 
5311dd20e65SCraig Topper const Value *Value::stripPointerCastsNoFollowAliases() const {
532ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
533ef860a24SChandler Carruth }
534ef860a24SChandler Carruth 
5351dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
536ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
537ef860a24SChandler Carruth }
538ef860a24SChandler Carruth 
539610c966aSPiotr Padlewski const Value *Value::stripPointerCastsAndBarriers() const {
540610c966aSPiotr Padlewski   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliasesAndBarriers>(
541610c966aSPiotr Padlewski       this);
542610c966aSPiotr Padlewski }
543610c966aSPiotr Padlewski 
5441dd20e65SCraig Topper const Value *
5451dd20e65SCraig Topper Value::stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
5461dd20e65SCraig Topper                                                  APInt &Offset) const {
547989e6308SChandler Carruth   if (!getType()->isPointerTy())
548989e6308SChandler Carruth     return this;
549989e6308SChandler Carruth 
550989e6308SChandler Carruth   assert(Offset.getBitWidth() == DL.getPointerSizeInBits(cast<PointerType>(
551989e6308SChandler Carruth                                      getType())->getAddressSpace()) &&
552989e6308SChandler Carruth          "The offset must have exactly as many bits as our pointer.");
553989e6308SChandler Carruth 
554989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
555989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5561dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
557989e6308SChandler Carruth   Visited.insert(this);
5581dd20e65SCraig Topper   const Value *V = this;
559989e6308SChandler Carruth   do {
5601dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
561989e6308SChandler Carruth       if (!GEP->isInBounds())
562989e6308SChandler Carruth         return V;
563ba689b33SChandler Carruth       APInt GEPOffset(Offset);
564ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
565989e6308SChandler Carruth         return V;
566ba689b33SChandler Carruth       Offset = GEPOffset;
567989e6308SChandler Carruth       V = GEP->getPointerOperand();
568d63df510SPhilip Reames     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
569989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5701dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
571989e6308SChandler Carruth       V = GA->getAliasee();
572989e6308SChandler Carruth     } else {
5731dd20e65SCraig Topper       if (auto CS = ImmutableCallSite(V))
5741dd20e65SCraig Topper         if (const Value *RV = CS.getReturnedArgOperand()) {
5755c12d8feSHal Finkel           V = RV;
5765c12d8feSHal Finkel           continue;
5775c12d8feSHal Finkel         }
5785c12d8feSHal Finkel 
579989e6308SChandler Carruth       return V;
580989e6308SChandler Carruth     }
581989e6308SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
58270573dcdSDavid Blaikie   } while (Visited.insert(V).second);
583989e6308SChandler Carruth 
584989e6308SChandler Carruth   return V;
585989e6308SChandler Carruth }
586989e6308SChandler Carruth 
5871dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const {
588ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
589ef860a24SChandler Carruth }
590ef860a24SChandler Carruth 
59100953cbeSSanjoy Das unsigned Value::getPointerDereferenceableBytes(const DataLayout &DL,
59200953cbeSSanjoy Das                                                bool &CanBeNull) const {
593345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
594345f0148SArtur Pilipenko 
595345f0148SArtur Pilipenko   unsigned DerefBytes = 0;
596345f0148SArtur Pilipenko   CanBeNull = false;
597345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
598345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
59900953cbeSSanjoy Das     if (DerefBytes == 0 && A->hasByValAttr() && A->getType()->isSized()) {
60000953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(A->getType());
60100953cbeSSanjoy Das       CanBeNull = false;
60200953cbeSSanjoy Das     }
603345f0148SArtur Pilipenko     if (DerefBytes == 0) {
604345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
605345f0148SArtur Pilipenko       CanBeNull = true;
606345f0148SArtur Pilipenko     }
607345f0148SArtur Pilipenko   } else if (auto CS = ImmutableCallSite(this)) {
6086652a52eSReid Kleckner     DerefBytes = CS.getDereferenceableBytes(AttributeList::ReturnIndex);
609345f0148SArtur Pilipenko     if (DerefBytes == 0) {
6106652a52eSReid Kleckner       DerefBytes = CS.getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
611345f0148SArtur Pilipenko       CanBeNull = true;
612345f0148SArtur Pilipenko     }
613345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
614345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
615345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
616345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
617345f0148SArtur Pilipenko     }
618345f0148SArtur Pilipenko     if (DerefBytes == 0) {
619345f0148SArtur Pilipenko       if (MDNode *MD =
620345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
621345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
622345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
623345f0148SArtur Pilipenko       }
624345f0148SArtur Pilipenko       CanBeNull = true;
625345f0148SArtur Pilipenko     }
62600953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
62700953cbeSSanjoy Das     if (AI->getAllocatedType()->isSized()) {
62800953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
62900953cbeSSanjoy Das       CanBeNull = false;
63000953cbeSSanjoy Das     }
63100953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
63200953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
63300953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
63400953cbeSSanjoy Das       // CanBeNull flag.
63500953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(GV->getValueType());
63600953cbeSSanjoy Das       CanBeNull = false;
63700953cbeSSanjoy Das     }
638345f0148SArtur Pilipenko   }
639345f0148SArtur Pilipenko   return DerefBytes;
640345f0148SArtur Pilipenko }
641345f0148SArtur Pilipenko 
642ae51afc5SArtur Pilipenko unsigned Value::getPointerAlignment(const DataLayout &DL) const {
643ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
644ae51afc5SArtur Pilipenko 
645ae51afc5SArtur Pilipenko   unsigned Align = 0;
646ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
647ae51afc5SArtur Pilipenko     Align = GO->getAlignment();
648ae51afc5SArtur Pilipenko     if (Align == 0) {
649ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
650ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
651ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
652ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
653ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
654ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
655ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
656ae51afc5SArtur Pilipenko             Align = DL.getPreferredAlignment(GVar);
657ae51afc5SArtur Pilipenko           else
658ae51afc5SArtur Pilipenko             Align = DL.getABITypeAlignment(ObjectType);
659ae51afc5SArtur Pilipenko         }
660ae51afc5SArtur Pilipenko       }
661ae51afc5SArtur Pilipenko     }
662ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
663ae51afc5SArtur Pilipenko     Align = A->getParamAlignment();
664ae51afc5SArtur Pilipenko 
665ae51afc5SArtur Pilipenko     if (!Align && A->hasStructRetAttr()) {
666ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
667ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
668ae51afc5SArtur Pilipenko       if (EltTy->isSized())
669ae51afc5SArtur Pilipenko         Align = DL.getABITypeAlignment(EltTy);
670ae51afc5SArtur Pilipenko     }
671c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
672ae51afc5SArtur Pilipenko     Align = AI->getAlignment();
673c97eac65SArtur Pilipenko     if (Align == 0) {
674c97eac65SArtur Pilipenko       Type *AllocatedType = AI->getAllocatedType();
675c97eac65SArtur Pilipenko       if (AllocatedType->isSized())
676c97eac65SArtur Pilipenko         Align = DL.getPrefTypeAlignment(AllocatedType);
677c97eac65SArtur Pilipenko     }
678c97eac65SArtur Pilipenko   } else if (auto CS = ImmutableCallSite(this))
679859f8b54SReid Kleckner     Align = CS.getAttributes().getRetAlignment();
680ae51afc5SArtur Pilipenko   else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
681ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
682ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
683ae51afc5SArtur Pilipenko       Align = CI->getLimitedValue();
684ae51afc5SArtur Pilipenko     }
685ae51afc5SArtur Pilipenko 
686ae51afc5SArtur Pilipenko   return Align;
687ae51afc5SArtur Pilipenko }
688ae51afc5SArtur Pilipenko 
6891dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
6901dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
6911dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
692ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
693ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
694ef860a24SChandler Carruth   return this;
695ef860a24SChandler Carruth }
696ef860a24SChandler Carruth 
697ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
698ef860a24SChandler Carruth 
6993441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
7003441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
7013441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
7023441ffe9SDuncan P. N. Exon Smith     return;
7033441ffe9SDuncan P. N. Exon Smith 
7043441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
7053441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
7063441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
7073441ffe9SDuncan P. N. Exon Smith   while (Current) {
7083441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
7093441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
7103441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
7113441ffe9SDuncan P. N. Exon Smith     Head = Current;
7123441ffe9SDuncan P. N. Exon Smith     Current = Next;
7133441ffe9SDuncan P. N. Exon Smith   }
7143441ffe9SDuncan P. N. Exon Smith   UseList = Head;
7153441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
7163441ffe9SDuncan P. N. Exon Smith }
7173441ffe9SDuncan P. N. Exon Smith 
718ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
719ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
720ad830022SArnold Schwaighofer   if (Arg)
721ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
722ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
723ad830022SArnold Schwaighofer   if (!Alloca)
724ad830022SArnold Schwaighofer     return false;
725ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
726ad830022SArnold Schwaighofer }
727ad830022SArnold Schwaighofer 
728ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
729ef860a24SChandler Carruth //                             ValueHandleBase Class
730ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
731ef860a24SChandler Carruth 
732ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
733ef860a24SChandler Carruth   assert(List && "Handle list is null?");
734ef860a24SChandler Carruth 
735ef860a24SChandler Carruth   // Splice ourselves into the list.
736ef860a24SChandler Carruth   Next = *List;
737ef860a24SChandler Carruth   *List = this;
738ef860a24SChandler Carruth   setPrevPtr(List);
739ef860a24SChandler Carruth   if (Next) {
740ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
7416f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
742ef860a24SChandler Carruth   }
743ef860a24SChandler Carruth }
744ef860a24SChandler Carruth 
745ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
746ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
747ef860a24SChandler Carruth 
748ef860a24SChandler Carruth   Next = List->Next;
749ef860a24SChandler Carruth   setPrevPtr(&List->Next);
750ef860a24SChandler Carruth   List->Next = this;
751ef860a24SChandler Carruth   if (Next)
752ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
753ef860a24SChandler Carruth }
754ef860a24SChandler Carruth 
755ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
7566f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
757ef860a24SChandler Carruth 
7586f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
759ef860a24SChandler Carruth 
7606f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
761ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
762ef860a24SChandler Carruth     // ValueHandles map already.
7636f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
7642617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
765ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
766ef860a24SChandler Carruth     return;
767ef860a24SChandler Carruth   }
768ef860a24SChandler Carruth 
769ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
770ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
771ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
772ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
773ef860a24SChandler Carruth   // updating the stale pointers only if needed.
774ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
775ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
776ef860a24SChandler Carruth 
7776f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
7782617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
779ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
7806f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
781ef860a24SChandler Carruth 
782ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
783ef860a24SChandler Carruth   // walk the table.
784ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
785ef860a24SChandler Carruth       Handles.size() == 1) {
786ef860a24SChandler Carruth     return;
787ef860a24SChandler Carruth   }
788ef860a24SChandler Carruth 
789ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
790ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
791ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
7926f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
793ef860a24SChandler Carruth            "List invariant broken!");
794ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
795ef860a24SChandler Carruth   }
796ef860a24SChandler Carruth }
797ef860a24SChandler Carruth 
798ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
7996f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
800ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
801ef860a24SChandler Carruth 
802ef860a24SChandler Carruth   // Unlink this from its use list.
803ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
804ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
805ef860a24SChandler Carruth 
806ef860a24SChandler Carruth   *PrevPtr = Next;
807ef860a24SChandler Carruth   if (Next) {
808ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
809ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
810ef860a24SChandler Carruth     return;
811ef860a24SChandler Carruth   }
812ef860a24SChandler Carruth 
813ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
814ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
815ef860a24SChandler Carruth   // map.
8166f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
817ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
818ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
8196f08789dSSanjoy Das     Handles.erase(getValPtr());
8206f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
821ef860a24SChandler Carruth   }
822ef860a24SChandler Carruth }
823ef860a24SChandler Carruth 
824ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
825ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
826ef860a24SChandler Carruth 
827ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
828ef860a24SChandler Carruth   // HasValueHandle flag is set.
829ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
830ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
831ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
832ef860a24SChandler Carruth 
833ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
834ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
835ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
836ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
837ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
838ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
839ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
840ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
841ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
842ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
843ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
844ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
845ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
846ef860a24SChandler Carruth 
847ef860a24SChandler Carruth     switch (Entry->getKind()) {
848ef860a24SChandler Carruth     case Assert:
849ef860a24SChandler Carruth       break;
850f1c0eafdSSanjoy Das     case Weak:
851e6bca0eeSSanjoy Das     case WeakTracking:
852f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
853f1c0eafdSSanjoy Das       // from the list.
854c620761cSCraig Topper       Entry->operator=(nullptr);
855ef860a24SChandler Carruth       break;
856ef860a24SChandler Carruth     case Callback:
857ef860a24SChandler Carruth       // Forward to the subclass's implementation.
858ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
859ef860a24SChandler Carruth       break;
860ef860a24SChandler Carruth     }
861ef860a24SChandler Carruth   }
862ef860a24SChandler Carruth 
863ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
864ef860a24SChandler Carruth   if (V->HasValueHandle) {
865ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
866ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
867ef860a24SChandler Carruth            << "\n";
868ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
869ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
870ef860a24SChandler Carruth                        " value!");
871ef860a24SChandler Carruth 
872ef860a24SChandler Carruth #endif
873ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
874ef860a24SChandler Carruth   }
875ef860a24SChandler Carruth }
876ef860a24SChandler Carruth 
877ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
878ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
879ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
880c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
881c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
882ef860a24SChandler Carruth 
883ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
884ef860a24SChandler Carruth   // HasValueHandle flag is set.
885ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
886ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
887ef860a24SChandler Carruth 
888ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
889ef860a24SChandler Carruth 
890ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
891ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
892ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
893ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
894ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
895ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
896ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
897ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
898ef860a24SChandler Carruth 
899ef860a24SChandler Carruth     switch (Entry->getKind()) {
900ef860a24SChandler Carruth     case Assert:
901f1c0eafdSSanjoy Das     case Weak:
902f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
903ef860a24SChandler Carruth       break;
904e6bca0eeSSanjoy Das     case WeakTracking:
9052cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
906ef860a24SChandler Carruth       Entry->operator=(New);
907ef860a24SChandler Carruth       break;
908ef860a24SChandler Carruth     case Callback:
909ef860a24SChandler Carruth       // Forward to the subclass's implementation.
910ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
911ef860a24SChandler Carruth       break;
912ef860a24SChandler Carruth     }
913ef860a24SChandler Carruth   }
914ef860a24SChandler Carruth 
915ef860a24SChandler Carruth #ifndef NDEBUG
9168a623820SSanjoy Das   // If any new weak value handles were added while processing the
917ef860a24SChandler Carruth   // list, then complain about it now.
918ef860a24SChandler Carruth   if (Old->HasValueHandle)
919ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
920ef860a24SChandler Carruth       switch (Entry->getKind()) {
921e6bca0eeSSanjoy Das       case WeakTracking:
922ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
923ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
924ef860a24SChandler Carruth                << New->getName() << "\n";
9258a623820SSanjoy Das         llvm_unreachable(
926e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the  old value!\n");
927ef860a24SChandler Carruth       default:
928ef860a24SChandler Carruth         break;
929ef860a24SChandler Carruth       }
930ef860a24SChandler Carruth #endif
931ef860a24SChandler Carruth }
932ef860a24SChandler Carruth 
933d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
934d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
935