xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 6f13637a)
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"
16ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h"
172f2ace98SDmitry Mikulin #include "llvm/ADT/SetVector.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"
32ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
33ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
34ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
35799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
36ef860a24SChandler Carruth #include <algorithm>
37ecefe5a8SEugene Zelenko 
38ef860a24SChandler Carruth using namespace llvm;
39ef860a24SChandler Carruth 
404c975578SSerge Guelton static cl::opt<unsigned> NonGlobalValueMaxNameSize(
414c975578SSerge Guelton     "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
424c975578SSerge Guelton     cl::desc("Maximum size for the name of non-global values."));
434c975578SSerge Guelton 
44ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
45ef860a24SChandler Carruth //                                Value Class
46ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
47ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
48ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
4916bf89ecSReid Kleckner   return Ty;
50ef860a24SChandler Carruth }
51ef860a24SChandler Carruth 
52ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
537349ab93SOwen Anderson     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid),
547349ab93SOwen Anderson       HasValueHandle(0), SubclassOptionalData(0), SubclassData(0),
55b4eede2cSPete Cooper       NumUserOperands(0), IsUsedByMD(false), HasName(false) {
569fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
57ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
58ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
59ef860a24SChandler Carruth   // constructed.
60784929d0SCraig Topper   if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke ||
61784929d0SCraig Topper       SubclassID == Instruction::CallBr)
62ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
63ef860a24SChandler Carruth            "invalid CallInst type!");
64ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
659fd33f24SSerge Guelton            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
66ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
67ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
6896ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
691762ad3eSReid Kleckner                 "Value too big");
70ef860a24SChandler Carruth }
71ef860a24SChandler Carruth 
72ef860a24SChandler Carruth Value::~Value() {
73ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
74ef860a24SChandler Carruth   if (HasValueHandle)
75ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
765bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
775bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
78ef860a24SChandler Carruth 
79ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
80ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
81ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
82b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
83b93fb82bSAndrew Kaylor   // the value is still being referenced.
84ef860a24SChandler Carruth   //
85ef860a24SChandler Carruth   if (!use_empty()) {
86ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
87b93fb82bSAndrew Kaylor     for (auto *U : users())
88b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
89ef860a24SChandler Carruth   }
90ef860a24SChandler Carruth #endif
91ef860a24SChandler Carruth   assert(use_empty() && "Uses remain when a value is destroyed!");
92ef860a24SChandler Carruth 
93ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
94ef860a24SChandler Carruth   // at this point.
955bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
96ef860a24SChandler Carruth }
97ef860a24SChandler Carruth 
9896ab8726SReid Kleckner void Value::deleteValue() {
9996ab8726SReid Kleckner   switch (getValueID()) {
10096ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
10196ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10296ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
10396ab8726SReid Kleckner     break;
10496ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
10596ab8726SReid Kleckner   case Value::Name##Val:                                                       \
10696ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
10796ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
10896ab8726SReid Kleckner     break;
10996ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
11096ab8726SReid Kleckner #include "llvm/IR/Value.def"
11196ab8726SReid Kleckner 
11296ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
11396ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
11496ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
11596ab8726SReid Kleckner     break;
11696ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
11796ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
11896ab8726SReid Kleckner 
11996ab8726SReid Kleckner   default:
12096ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
12196ab8726SReid Kleckner   }
12296ab8726SReid Kleckner }
12396ab8726SReid Kleckner 
1245bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1255bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
1265bf8fef5SDuncan P. N. Exon Smith   if (Name)
1275bf8fef5SDuncan P. N. Exon Smith     Name->Destroy();
1285bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1295bf8fef5SDuncan P. N. Exon Smith }
1305bf8fef5SDuncan P. N. Exon Smith 
131ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
1324de31bbaSVedant Kumar   return hasNItems(use_begin(), use_end(), N);
133ef860a24SChandler Carruth }
134ef860a24SChandler Carruth 
135ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
1364de31bbaSVedant Kumar   return hasNItemsOrMore(use_begin(), use_end(), N);
137ef860a24SChandler Carruth }
138ef860a24SChandler Carruth 
139ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
1400925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
1410925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
1420925b24dSJakob Stoklund Olesen   // usually one is quite short.
1430925b24dSJakob Stoklund Olesen   //
1440925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
1450925b24dSJakob Stoklund Olesen   // search to the shorter list.
1460925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
147cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
1480925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
1490925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
15042531260SDavid Majnemer     if (is_contained(BI->operands(), this))
151ef860a24SChandler Carruth       return true;
1520925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
15342531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
154ef860a24SChandler Carruth     if (User && User->getParent() == BB)
155ef860a24SChandler Carruth       return true;
156ef860a24SChandler Carruth   }
157ef860a24SChandler Carruth   return false;
158ef860a24SChandler Carruth }
159ef860a24SChandler Carruth 
1605a0872c2SVedant Kumar unsigned Value::getNumUses() const {
1615a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
1625a0872c2SVedant Kumar }
163ef860a24SChandler Carruth 
164ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
165c620761cSCraig Topper   ST = nullptr;
166ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
167ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
168ef860a24SChandler Carruth       if (Function *PP = P->getParent())
169a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
170ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
171ef860a24SChandler Carruth     if (Function *P = BB->getParent())
172a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
173ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
174ef860a24SChandler Carruth     if (Module *P = GV->getParent())
175ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
176ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
177ef860a24SChandler Carruth     if (Function *P = A->getParent())
178a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
1795bf8fef5SDuncan P. N. Exon Smith   } else {
180ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
181ef860a24SChandler Carruth     return true;  // no name is setable for this.
182ef860a24SChandler Carruth   }
183ef860a24SChandler Carruth   return false;
184ef860a24SChandler Carruth }
185ef860a24SChandler Carruth 
1867349ab93SOwen Anderson ValueName *Value::getValueName() const {
1877349ab93SOwen Anderson   if (!HasName) return nullptr;
1887349ab93SOwen Anderson 
1897349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
1907349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
1917349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
1927349ab93SOwen Anderson          "No name entry found!");
1937349ab93SOwen Anderson 
1947349ab93SOwen Anderson   return I->second;
1957349ab93SOwen Anderson }
1967349ab93SOwen Anderson 
1977349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
1987349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
1997349ab93SOwen Anderson 
2007349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2017349ab93SOwen Anderson          "HasName bit out of sync!");
2027349ab93SOwen Anderson 
2037349ab93SOwen Anderson   if (!VN) {
2047349ab93SOwen Anderson     if (HasName)
2057349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
2067349ab93SOwen Anderson     HasName = false;
2077349ab93SOwen Anderson     return;
2087349ab93SOwen Anderson   }
2097349ab93SOwen Anderson 
2107349ab93SOwen Anderson   HasName = true;
2117349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
2127349ab93SOwen Anderson }
2137349ab93SOwen Anderson 
214ef860a24SChandler Carruth StringRef Value::getName() const {
215ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
216ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
217ef860a24SChandler Carruth   // terminated.
2187349ab93SOwen Anderson   if (!hasName())
2195bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
2205bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
221ef860a24SChandler Carruth }
222ef860a24SChandler Carruth 
223a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
22409b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
22550af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
22609b4a8daSMehdi Amini     return;
22709b4a8daSMehdi Amini 
228ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
229ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
230ef860a24SChandler Carruth     return;
231ef860a24SChandler Carruth 
232ef860a24SChandler Carruth   SmallString<256> NameData;
233ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
23409d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
23509d689f9SRafael Espindola          "Null bytes are not allowed in names");
236ef860a24SChandler Carruth 
237ef860a24SChandler Carruth   // Name isn't changing?
238ef860a24SChandler Carruth   if (getName() == NameRef)
239ef860a24SChandler Carruth     return;
240ef860a24SChandler Carruth 
2414c975578SSerge Guelton   // Cap the size of non-GlobalValue names.
2424c975578SSerge Guelton   if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this))
2434c975578SSerge Guelton     NameRef =
2444c975578SSerge Guelton         NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize));
2454c975578SSerge Guelton 
246ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
247ef860a24SChandler Carruth 
248ef860a24SChandler Carruth   // Get the symbol table to update for this object.
249ef860a24SChandler Carruth   ValueSymbolTable *ST;
250ef860a24SChandler Carruth   if (getSymTab(this, ST))
251ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
252ef860a24SChandler Carruth 
253ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
254ef860a24SChandler Carruth     if (NameRef.empty()) {
255ef860a24SChandler Carruth       // Free the name for this value.
2565bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
257ef860a24SChandler Carruth       return;
258ef860a24SChandler Carruth     }
259ef860a24SChandler Carruth 
260ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
261ef860a24SChandler Carruth     // then reallocated.
2625bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
263ef860a24SChandler Carruth 
264ef860a24SChandler Carruth     // Create the new name.
2655bf8fef5SDuncan P. N. Exon Smith     setValueName(ValueName::Create(NameRef));
2665bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
267ef860a24SChandler Carruth     return;
268ef860a24SChandler Carruth   }
269ef860a24SChandler Carruth 
270ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
271ef860a24SChandler Carruth   // then reallocated.
272ef860a24SChandler Carruth   if (hasName()) {
273ef860a24SChandler Carruth     // Remove old name.
2745bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
2755bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
276ef860a24SChandler Carruth 
277ef860a24SChandler Carruth     if (NameRef.empty())
278ef860a24SChandler Carruth       return;
279ef860a24SChandler Carruth   }
280ef860a24SChandler Carruth 
281ef860a24SChandler Carruth   // Name is changing to something new.
2825bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
283ef860a24SChandler Carruth }
284ef860a24SChandler Carruth 
285a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
286a7c0c18cSPete Cooper   setNameImpl(NewName);
287a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
288a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
289a7c0c18cSPete Cooper }
290a7c0c18cSPete Cooper 
291ef860a24SChandler Carruth void Value::takeName(Value *V) {
292c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
293ef860a24SChandler Carruth   // If this value has a name, drop it.
294ef860a24SChandler Carruth   if (hasName()) {
295ef860a24SChandler Carruth     // Get the symtab this is in.
296ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
297ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
298ef860a24SChandler Carruth       // it has one.
299ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
300ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
301ef860a24SChandler Carruth     }
302ef860a24SChandler Carruth 
303ef860a24SChandler Carruth     // Remove old name.
304ef860a24SChandler Carruth     if (ST)
3055bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3065bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
307ef860a24SChandler Carruth   }
308ef860a24SChandler Carruth 
309ef860a24SChandler Carruth   // Now we know that this has no name.
310ef860a24SChandler Carruth 
311ef860a24SChandler Carruth   // If V has no name either, we're done.
312ef860a24SChandler Carruth   if (!V->hasName()) return;
313ef860a24SChandler Carruth 
314ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
315ef860a24SChandler Carruth   if (!ST) {
316ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
317ef860a24SChandler Carruth       // Clear V's name.
318ef860a24SChandler Carruth       V->setName("");
319ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
320ef860a24SChandler Carruth     }
321ef860a24SChandler Carruth   }
322ef860a24SChandler Carruth 
323ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
324ef860a24SChandler Carruth   ValueSymbolTable *VST;
325ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
326ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
327ef860a24SChandler Carruth 
328ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
329ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
330ef860a24SChandler Carruth   if (ST == VST) {
331ef860a24SChandler Carruth     // Take the name!
3325bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
3335bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
3345bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
335ef860a24SChandler Carruth     return;
336ef860a24SChandler Carruth   }
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
339ef860a24SChandler Carruth   // then reinsert it into ST.
340ef860a24SChandler Carruth 
341ef860a24SChandler Carruth   if (VST)
3425bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
3435bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
3445bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
3455bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
346ef860a24SChandler Carruth 
347ef860a24SChandler Carruth   if (ST)
348ef860a24SChandler Carruth     ST->reinsertValue(this);
349ef860a24SChandler Carruth }
350ef860a24SChandler Carruth 
351eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
352675bdcedSTodd Fiala #ifndef NDEBUG
353257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
354257a3536SRafael Espindola   if (!GV)
355257a3536SRafael Espindola     return;
356257a3536SRafael Espindola   const Module *M = GV->getParent();
357257a3536SRafael Espindola   if (!M)
358257a3536SRafael Espindola     return;
359257a3536SRafael Espindola   assert(M->isMaterialized());
360675bdcedSTodd Fiala #endif
361257a3536SRafael Espindola }
362257a3536SRafael Espindola 
363675bdcedSTodd Fiala #ifndef NDEBUG
36471b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
3657e2b7567SRafael Espindola                      Constant *C) {
36670573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
3677e2b7567SRafael Espindola     return false;
3687e2b7567SRafael Espindola 
3697e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
3707e2b7567SRafael Espindola     if (O == C)
3717e2b7567SRafael Espindola       return true;
3727e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
3737e2b7567SRafael Espindola     if (!CE)
3747e2b7567SRafael Espindola       continue;
3757e2b7567SRafael Espindola     if (contains(Cache, CE, C))
3767e2b7567SRafael Espindola       return true;
3777e2b7567SRafael Espindola   }
3787e2b7567SRafael Espindola   return false;
3797e2b7567SRafael Espindola }
3807e2b7567SRafael Espindola 
3817e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
3827e2b7567SRafael Espindola   if (Expr == V)
3837e2b7567SRafael Espindola     return true;
3847e2b7567SRafael Espindola 
3857e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
3867e2b7567SRafael Espindola   if (!C)
3877e2b7567SRafael Espindola     return false;
3887e2b7567SRafael Espindola 
3897e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
3907e2b7567SRafael Espindola   if (!CE)
3917e2b7567SRafael Espindola     return false;
3927e2b7567SRafael Espindola 
3937e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
3947e2b7567SRafael Espindola   return contains(Cache, CE, C);
3957e2b7567SRafael Espindola }
396ecefe5a8SEugene Zelenko #endif // NDEBUG
397ef860a24SChandler Carruth 
398e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
399ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
4007e2b7567SRafael Espindola   assert(!contains(New, this) &&
4017e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
402ef860a24SChandler Carruth   assert(New->getType() == getType() &&
403ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
404ef860a24SChandler Carruth 
405ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
406ef860a24SChandler Carruth   if (HasValueHandle)
407ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
408e69ae76bSJF Bastien   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
4095bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
410ef860a24SChandler Carruth 
41181bbf742STeresa Johnson   while (!materialized_use_empty()) {
412ef860a24SChandler Carruth     Use &U = *UseList;
413ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
414ef860a24SChandler Carruth     // constant because they are uniqued.
4156b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
416ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
4178914d290SMehdi Amini         C->handleOperandChange(this, New);
418ef860a24SChandler Carruth         continue;
419ef860a24SChandler Carruth       }
420ef860a24SChandler Carruth     }
421ef860a24SChandler Carruth 
422ef860a24SChandler Carruth     U.set(New);
423ef860a24SChandler Carruth   }
424ef860a24SChandler Carruth 
425ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
426ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
427ef860a24SChandler Carruth }
428ef860a24SChandler Carruth 
4291ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
430e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::Yes);
4311ed53963SDavide Italiano }
4321ed53963SDavide Italiano 
4331ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
434e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::No);
4351ed53963SDavide Italiano }
4361ed53963SDavide Italiano 
437ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
438ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
439ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
440ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
441ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
442ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
443ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
444ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
445ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
446ec6217c9SGerolf Hoflehner 
447ec6217c9SGerolf Hoflehner   use_iterator UI = use_begin(), E = use_end();
448ec6217c9SGerolf Hoflehner   for (; UI != E;) {
449ec6217c9SGerolf Hoflehner     Use &U = *UI;
450ec6217c9SGerolf Hoflehner     ++UI;
451ec6217c9SGerolf Hoflehner     auto *Usr = dyn_cast<Instruction>(U.getUser());
452ec6217c9SGerolf Hoflehner     if (Usr && Usr->getParent() == BB)
453ec6217c9SGerolf Hoflehner       continue;
454ec6217c9SGerolf Hoflehner     U.set(New);
455ec6217c9SGerolf Hoflehner   }
456ec6217c9SGerolf Hoflehner }
457ec6217c9SGerolf Hoflehner 
458ef860a24SChandler Carruth namespace {
459ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
460ef860a24SChandler Carruth enum PointerStripKind {
461ef860a24SChandler Carruth   PSK_ZeroIndices,
462c229a4ffSRafael Espindola   PSK_ZeroIndicesAndAliases,
46340107ce7SJohannes Doerfert   PSK_ZeroIndicesAndAliasesSameRepresentation,
4645dde8094SPiotr Padlewski   PSK_ZeroIndicesAndAliasesAndInvariantGroups,
465ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
466ef860a24SChandler Carruth   PSK_InBounds
467ef860a24SChandler Carruth };
468ef860a24SChandler Carruth 
469ef860a24SChandler Carruth template <PointerStripKind StripKind>
4701dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) {
471ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
472ef860a24SChandler Carruth     return V;
473ef860a24SChandler Carruth 
474ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
475ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
4761dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
477ef860a24SChandler Carruth 
478ef860a24SChandler Carruth   Visited.insert(V);
479ef860a24SChandler Carruth   do {
4801dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
481ef860a24SChandler Carruth       switch (StripKind) {
482c229a4ffSRafael Espindola       case PSK_ZeroIndicesAndAliases:
48340107ce7SJohannes Doerfert       case PSK_ZeroIndicesAndAliasesSameRepresentation:
4845dde8094SPiotr Padlewski       case PSK_ZeroIndicesAndAliasesAndInvariantGroups:
485ef860a24SChandler Carruth       case PSK_ZeroIndices:
486ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
487ef860a24SChandler Carruth           return V;
488ef860a24SChandler Carruth         break;
489ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
490ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
491ef860a24SChandler Carruth           return V;
492b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
493ef860a24SChandler Carruth       case PSK_InBounds:
494ef860a24SChandler Carruth         if (!GEP->isInBounds())
495ef860a24SChandler Carruth           return V;
496ef860a24SChandler Carruth         break;
497ef860a24SChandler Carruth       }
498ef860a24SChandler Carruth       V = GEP->getPointerOperand();
49940107ce7SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
50040107ce7SJohannes Doerfert       V = cast<Operator>(V)->getOperand(0);
50140107ce7SJohannes Doerfert     } else if (StripKind != PSK_ZeroIndicesAndAliasesSameRepresentation &&
502b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
50340107ce7SJohannes Doerfert       // TODO: If we know an address space cast will not change the
50440107ce7SJohannes Doerfert       //       representation we could look through it here as well.
505ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5061dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
5075ce32728SSanjoy Das       if (StripKind == PSK_ZeroIndices || GA->isInterposable())
508ef860a24SChandler Carruth         return V;
509ef860a24SChandler Carruth       V = GA->getAliasee();
510ef860a24SChandler Carruth     } else {
51190c09232SChandler Carruth       if (const auto *Call = dyn_cast<CallBase>(V)) {
51290c09232SChandler Carruth         if (const Value *RV = Call->getReturnedArgOperand()) {
5135c12d8feSHal Finkel           V = RV;
5145c12d8feSHal Finkel           continue;
5155c12d8feSHal Finkel         }
5165dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
517610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
518610c966aSPiotr Padlewski         // special case.
5195dde8094SPiotr Padlewski         if (StripKind == PSK_ZeroIndicesAndAliasesAndInvariantGroups &&
52090c09232SChandler Carruth             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
52190c09232SChandler Carruth              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
52290c09232SChandler Carruth           V = Call->getArgOperand(0);
523610c966aSPiotr Padlewski           continue;
524610c966aSPiotr Padlewski         }
525610c966aSPiotr Padlewski       }
526ef860a24SChandler Carruth       return V;
527ef860a24SChandler Carruth     }
528ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
52970573dcdSDavid Blaikie   } while (Visited.insert(V).second);
530ef860a24SChandler Carruth 
531ef860a24SChandler Carruth   return V;
532ef860a24SChandler Carruth }
533ecefe5a8SEugene Zelenko } // end anonymous namespace
534ef860a24SChandler Carruth 
5351dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
536c229a4ffSRafael Espindola   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
537c229a4ffSRafael Espindola }
538c229a4ffSRafael Espindola 
53940107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const {
54040107ce7SJohannes Doerfert   return stripPointerCastsAndOffsets<
54140107ce7SJohannes Doerfert       PSK_ZeroIndicesAndAliasesSameRepresentation>(this);
54240107ce7SJohannes Doerfert }
54340107ce7SJohannes Doerfert 
5441dd20e65SCraig Topper const Value *Value::stripPointerCastsNoFollowAliases() const {
545ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
546ef860a24SChandler Carruth }
547ef860a24SChandler Carruth 
5481dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
549ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
550ef860a24SChandler Carruth }
551ef860a24SChandler Carruth 
5525dde8094SPiotr Padlewski const Value *Value::stripPointerCastsAndInvariantGroups() const {
5535dde8094SPiotr Padlewski   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliasesAndInvariantGroups>(
554610c966aSPiotr Padlewski       this);
555610c966aSPiotr Padlewski }
556610c966aSPiotr Padlewski 
5571dd20e65SCraig Topper const Value *
5583ed286a3SJohannes Doerfert Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
5593ed286a3SJohannes Doerfert                                          bool AllowNonInbounds) const {
5603ed286a3SJohannes Doerfert   if (!getType()->isPtrOrPtrVectorTy())
561989e6308SChandler Carruth     return this;
562989e6308SChandler Carruth 
5633ed286a3SJohannes Doerfert   unsigned BitWidth = Offset.getBitWidth();
5643ed286a3SJohannes Doerfert   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
565945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
566989e6308SChandler Carruth 
567989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
568989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
5691dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
570989e6308SChandler Carruth   Visited.insert(this);
5711dd20e65SCraig Topper   const Value *V = this;
572989e6308SChandler Carruth   do {
5731dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
5743ed286a3SJohannes Doerfert       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
5753ed286a3SJohannes Doerfert       if (!AllowNonInbounds && !GEP->isInBounds())
576989e6308SChandler Carruth         return V;
5773ed286a3SJohannes Doerfert 
5783ed286a3SJohannes Doerfert       // If one of the values we have visited is an addrspacecast, then
5793ed286a3SJohannes Doerfert       // the pointer type of this GEP may be different from the type
5803ed286a3SJohannes Doerfert       // of the Ptr parameter which was passed to this function.  This
5813ed286a3SJohannes Doerfert       // means when we construct GEPOffset, we need to use the size
5823ed286a3SJohannes Doerfert       // of GEP's pointer type rather than the size of the original
5833ed286a3SJohannes Doerfert       // pointer type.
5843ed286a3SJohannes Doerfert       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
585ba689b33SChandler Carruth       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
586989e6308SChandler Carruth         return V;
5873ed286a3SJohannes Doerfert 
5883ed286a3SJohannes Doerfert       // Stop traversal if the pointer offset wouldn't fit in the bit-width
5893ed286a3SJohannes Doerfert       // provided by the Offset argument. This can happen due to AddrSpaceCast
5903ed286a3SJohannes Doerfert       // stripping.
5913ed286a3SJohannes Doerfert       if (GEPOffset.getMinSignedBits() > BitWidth)
5923ed286a3SJohannes Doerfert         return V;
5933ed286a3SJohannes Doerfert 
5943ed286a3SJohannes Doerfert       Offset += GEPOffset.sextOrTrunc(BitWidth);
595989e6308SChandler Carruth       V = GEP->getPointerOperand();
5963ed286a3SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
5973ed286a3SJohannes Doerfert                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
598989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
5991dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
6003ed286a3SJohannes Doerfert       if (!GA->isInterposable())
601989e6308SChandler Carruth         V = GA->getAliasee();
6023ed286a3SJohannes Doerfert     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
6033ed286a3SJohannes Doerfert         if (const Value *RV = Call->getReturnedArgOperand())
6045c12d8feSHal Finkel           V = RV;
6055c12d8feSHal Finkel     }
6063ed286a3SJohannes Doerfert     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
60770573dcdSDavid Blaikie   } while (Visited.insert(V).second);
608989e6308SChandler Carruth 
609989e6308SChandler Carruth   return V;
610989e6308SChandler Carruth }
611989e6308SChandler Carruth 
6121dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const {
613ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBounds>(this);
614ef860a24SChandler Carruth }
615ef860a24SChandler Carruth 
6163603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
61700953cbeSSanjoy Das                                                bool &CanBeNull) const {
618345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
619345f0148SArtur Pilipenko 
6203603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
621345f0148SArtur Pilipenko   CanBeNull = false;
622345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
623345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
6242da4d9d8SBjorn Steinbrink     if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) {
625c27f81b9SBjorn Steinbrink       Type *PT = cast<PointerType>(A->getType())->getElementType();
6262da4d9d8SBjorn Steinbrink       if (PT->isSized())
627c27f81b9SBjorn Steinbrink         DerefBytes = DL.getTypeStoreSize(PT);
62800953cbeSSanjoy Das     }
629345f0148SArtur Pilipenko     if (DerefBytes == 0) {
630345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
631345f0148SArtur Pilipenko       CanBeNull = true;
632345f0148SArtur Pilipenko     }
63390c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
63490c09232SChandler Carruth     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
635345f0148SArtur Pilipenko     if (DerefBytes == 0) {
63690c09232SChandler Carruth       DerefBytes =
63790c09232SChandler Carruth           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
638345f0148SArtur Pilipenko       CanBeNull = true;
639345f0148SArtur Pilipenko     }
640345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
641345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
642345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
643345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
644345f0148SArtur Pilipenko     }
645345f0148SArtur Pilipenko     if (DerefBytes == 0) {
646345f0148SArtur Pilipenko       if (MDNode *MD =
647345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
648345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
649345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
650345f0148SArtur Pilipenko       }
651345f0148SArtur Pilipenko       CanBeNull = true;
652345f0148SArtur Pilipenko     }
653*6f13637aSRyan Taylor   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
654*6f13637aSRyan Taylor     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
655*6f13637aSRyan Taylor       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
656*6f13637aSRyan Taylor       DerefBytes = CI->getLimitedValue();
657*6f13637aSRyan Taylor     }
658*6f13637aSRyan Taylor     if (DerefBytes == 0) {
659*6f13637aSRyan Taylor       if (MDNode *MD =
660*6f13637aSRyan Taylor               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
661*6f13637aSRyan Taylor         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
662*6f13637aSRyan Taylor         DerefBytes = CI->getLimitedValue();
663*6f13637aSRyan Taylor       }
664*6f13637aSRyan Taylor       CanBeNull = true;
665*6f13637aSRyan Taylor     }
66600953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
667030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
668030123e8SBjorn Steinbrink       DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType());
66900953cbeSSanjoy Das       CanBeNull = false;
67000953cbeSSanjoy Das     }
67100953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
67200953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
67300953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
67400953cbeSSanjoy Das       // CanBeNull flag.
67500953cbeSSanjoy Das       DerefBytes = DL.getTypeStoreSize(GV->getValueType());
67600953cbeSSanjoy Das       CanBeNull = false;
67700953cbeSSanjoy Das     }
678345f0148SArtur Pilipenko   }
679345f0148SArtur Pilipenko   return DerefBytes;
680345f0148SArtur Pilipenko }
681345f0148SArtur Pilipenko 
682ae51afc5SArtur Pilipenko unsigned Value::getPointerAlignment(const DataLayout &DL) const {
683ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
684ae51afc5SArtur Pilipenko 
685ae51afc5SArtur Pilipenko   unsigned Align = 0;
686ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
687308e82ecSMichael Platings     if (isa<Function>(GO)) {
688308e82ecSMichael Platings       switch (DL.getFunctionPtrAlignType()) {
689308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::Independent:
690308e82ecSMichael Platings         return DL.getFunctionPtrAlign();
691308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
692308e82ecSMichael Platings         return std::max(DL.getFunctionPtrAlign(), GO->getAlignment());
693308e82ecSMichael Platings       }
694308e82ecSMichael Platings     }
695ae51afc5SArtur Pilipenko     Align = GO->getAlignment();
696ae51afc5SArtur Pilipenko     if (Align == 0) {
697ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
698ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
699ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
700ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
701ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
702ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
703ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
704ae51afc5SArtur Pilipenko             Align = DL.getPreferredAlignment(GVar);
705ae51afc5SArtur Pilipenko           else
706ae51afc5SArtur Pilipenko             Align = DL.getABITypeAlignment(ObjectType);
707ae51afc5SArtur Pilipenko         }
708ae51afc5SArtur Pilipenko       }
709ae51afc5SArtur Pilipenko     }
710ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
711ae51afc5SArtur Pilipenko     Align = A->getParamAlignment();
712ae51afc5SArtur Pilipenko 
713ae51afc5SArtur Pilipenko     if (!Align && A->hasStructRetAttr()) {
714ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
715ae51afc5SArtur Pilipenko       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
716ae51afc5SArtur Pilipenko       if (EltTy->isSized())
717ae51afc5SArtur Pilipenko         Align = DL.getABITypeAlignment(EltTy);
718ae51afc5SArtur Pilipenko     }
719c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
720ae51afc5SArtur Pilipenko     Align = AI->getAlignment();
721c97eac65SArtur Pilipenko     if (Align == 0) {
722c97eac65SArtur Pilipenko       Type *AllocatedType = AI->getAllocatedType();
723c97eac65SArtur Pilipenko       if (AllocatedType->isSized())
724c97eac65SArtur Pilipenko         Align = DL.getPrefTypeAlignment(AllocatedType);
725c97eac65SArtur Pilipenko     }
72690c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this))
72790c09232SChandler Carruth     Align = Call->getAttributes().getRetAlignment();
728ae51afc5SArtur Pilipenko   else if (const LoadInst *LI = dyn_cast<LoadInst>(this))
729ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
730ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
731ae51afc5SArtur Pilipenko       Align = CI->getLimitedValue();
732ae51afc5SArtur Pilipenko     }
733ae51afc5SArtur Pilipenko 
734ae51afc5SArtur Pilipenko   return Align;
735ae51afc5SArtur Pilipenko }
736ae51afc5SArtur Pilipenko 
7371dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
7381dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
7391dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
740ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
741ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
742ef860a24SChandler Carruth   return this;
743ef860a24SChandler Carruth }
744ef860a24SChandler Carruth 
745ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
746ef860a24SChandler Carruth 
7473441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
7483441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
7493441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
7503441ffe9SDuncan P. N. Exon Smith     return;
7513441ffe9SDuncan P. N. Exon Smith 
7523441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
7533441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
7543441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
7553441ffe9SDuncan P. N. Exon Smith   while (Current) {
7563441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
7573441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
7583441ffe9SDuncan P. N. Exon Smith     Head->setPrev(&Current->Next);
7593441ffe9SDuncan P. N. Exon Smith     Head = Current;
7603441ffe9SDuncan P. N. Exon Smith     Current = Next;
7613441ffe9SDuncan P. N. Exon Smith   }
7623441ffe9SDuncan P. N. Exon Smith   UseList = Head;
7633441ffe9SDuncan P. N. Exon Smith   Head->setPrev(&UseList);
7643441ffe9SDuncan P. N. Exon Smith }
7653441ffe9SDuncan P. N. Exon Smith 
766ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
767ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
768ad830022SArnold Schwaighofer   if (Arg)
769ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
770ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
771ad830022SArnold Schwaighofer   if (!Alloca)
772ad830022SArnold Schwaighofer     return false;
773ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
774ad830022SArnold Schwaighofer }
775ad830022SArnold Schwaighofer 
776ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
777ef860a24SChandler Carruth //                             ValueHandleBase Class
778ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
779ef860a24SChandler Carruth 
780ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
781ef860a24SChandler Carruth   assert(List && "Handle list is null?");
782ef860a24SChandler Carruth 
783ef860a24SChandler Carruth   // Splice ourselves into the list.
784ef860a24SChandler Carruth   Next = *List;
785ef860a24SChandler Carruth   *List = this;
786ef860a24SChandler Carruth   setPrevPtr(List);
787ef860a24SChandler Carruth   if (Next) {
788ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
7896f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
790ef860a24SChandler Carruth   }
791ef860a24SChandler Carruth }
792ef860a24SChandler Carruth 
793ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
794ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
795ef860a24SChandler Carruth 
796ef860a24SChandler Carruth   Next = List->Next;
797ef860a24SChandler Carruth   setPrevPtr(&List->Next);
798ef860a24SChandler Carruth   List->Next = this;
799ef860a24SChandler Carruth   if (Next)
800ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
801ef860a24SChandler Carruth }
802ef860a24SChandler Carruth 
803ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
8046f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
805ef860a24SChandler Carruth 
8066f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
807ef860a24SChandler Carruth 
8086f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
809ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
810ef860a24SChandler Carruth     // ValueHandles map already.
8116f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
8122617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
813ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
814ef860a24SChandler Carruth     return;
815ef860a24SChandler Carruth   }
816ef860a24SChandler Carruth 
817ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
818ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
819ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
820ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
821ef860a24SChandler Carruth   // updating the stale pointers only if needed.
822ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
823ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
824ef860a24SChandler Carruth 
8256f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
8262617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
827ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
8286f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
829ef860a24SChandler Carruth 
830ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
831ef860a24SChandler Carruth   // walk the table.
832ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
833ef860a24SChandler Carruth       Handles.size() == 1) {
834ef860a24SChandler Carruth     return;
835ef860a24SChandler Carruth   }
836ef860a24SChandler Carruth 
837ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
838ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
839ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
8406f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
841ef860a24SChandler Carruth            "List invariant broken!");
842ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
843ef860a24SChandler Carruth   }
844ef860a24SChandler Carruth }
845ef860a24SChandler Carruth 
846ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
8476f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
848ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
849ef860a24SChandler Carruth 
850ef860a24SChandler Carruth   // Unlink this from its use list.
851ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
852ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
853ef860a24SChandler Carruth 
854ef860a24SChandler Carruth   *PrevPtr = Next;
855ef860a24SChandler Carruth   if (Next) {
856ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
857ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
858ef860a24SChandler Carruth     return;
859ef860a24SChandler Carruth   }
860ef860a24SChandler Carruth 
861ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
862ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
863ef860a24SChandler Carruth   // map.
8646f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
865ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
866ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
8676f08789dSSanjoy Das     Handles.erase(getValPtr());
8686f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
869ef860a24SChandler Carruth   }
870ef860a24SChandler Carruth }
871ef860a24SChandler Carruth 
872ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
873ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
874ef860a24SChandler Carruth 
875ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
876ef860a24SChandler Carruth   // HasValueHandle flag is set.
877ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
878ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
879ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
880ef860a24SChandler Carruth 
881ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
882ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
883ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
884ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
885ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
886ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
887ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
888ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
889ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
890ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
891ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
892ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
893ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
894ef860a24SChandler Carruth 
895ef860a24SChandler Carruth     switch (Entry->getKind()) {
896ef860a24SChandler Carruth     case Assert:
897ef860a24SChandler Carruth       break;
898f1c0eafdSSanjoy Das     case Weak:
899e6bca0eeSSanjoy Das     case WeakTracking:
900f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
901f1c0eafdSSanjoy Das       // from the list.
902c620761cSCraig Topper       Entry->operator=(nullptr);
903ef860a24SChandler Carruth       break;
904ef860a24SChandler Carruth     case Callback:
905ef860a24SChandler Carruth       // Forward to the subclass's implementation.
906ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
907ef860a24SChandler Carruth       break;
908ef860a24SChandler Carruth     }
909ef860a24SChandler Carruth   }
910ef860a24SChandler Carruth 
911ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
912ef860a24SChandler Carruth   if (V->HasValueHandle) {
913ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
914ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
915ef860a24SChandler Carruth            << "\n";
916ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
917ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
918ef860a24SChandler Carruth                        " value!");
919ef860a24SChandler Carruth 
920ef860a24SChandler Carruth #endif
921ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
922ef860a24SChandler Carruth   }
923ef860a24SChandler Carruth }
924ef860a24SChandler Carruth 
925ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
926ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
927ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
928c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
929c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
930ef860a24SChandler Carruth 
931ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
932ef860a24SChandler Carruth   // HasValueHandle flag is set.
933ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
934ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
935ef860a24SChandler Carruth 
936ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
937ef860a24SChandler Carruth 
938ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
939ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
940ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
941ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
942ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
943ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
944ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
945ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
946ef860a24SChandler Carruth 
947ef860a24SChandler Carruth     switch (Entry->getKind()) {
948ef860a24SChandler Carruth     case Assert:
949f1c0eafdSSanjoy Das     case Weak:
950f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
951ef860a24SChandler Carruth       break;
952e6bca0eeSSanjoy Das     case WeakTracking:
9532cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
954ef860a24SChandler Carruth       Entry->operator=(New);
955ef860a24SChandler Carruth       break;
956ef860a24SChandler Carruth     case Callback:
957ef860a24SChandler Carruth       // Forward to the subclass's implementation.
958ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
959ef860a24SChandler Carruth       break;
960ef860a24SChandler Carruth     }
961ef860a24SChandler Carruth   }
962ef860a24SChandler Carruth 
963ef860a24SChandler Carruth #ifndef NDEBUG
9648a623820SSanjoy Das   // If any new weak value handles were added while processing the
965ef860a24SChandler Carruth   // list, then complain about it now.
966ef860a24SChandler Carruth   if (Old->HasValueHandle)
967ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
968ef860a24SChandler Carruth       switch (Entry->getKind()) {
969e6bca0eeSSanjoy Das       case WeakTracking:
970ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
971ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
972ef860a24SChandler Carruth                << New->getName() << "\n";
9738a623820SSanjoy Das         llvm_unreachable(
974e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the old value!\n");
975ef860a24SChandler Carruth       default:
976ef860a24SChandler Carruth         break;
977ef860a24SChandler Carruth       }
978ef860a24SChandler Carruth #endif
979ef860a24SChandler Carruth }
980ef860a24SChandler Carruth 
981d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
982d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
983