xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision 75384ecd)
1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===//
2ef860a24SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ef860a24SChandler Carruth //
7ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
8ef860a24SChandler Carruth //
9ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes.
10ef860a24SChandler Carruth //
11ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
12ef860a24SChandler Carruth 
139fb823bbSChandler Carruth #include "llvm/IR/Value.h"
14ef860a24SChandler Carruth #include "LLVMContextImpl.h"
15ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h"
162f2ace98SDmitry Mikulin #include "llvm/ADT/SetVector.h"
174c1a1d3cSReid Kleckner #include "llvm/ADT/SmallString.h"
189fb823bbSChandler Carruth #include "llvm/IR/Constant.h"
199fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
202e42c34dSHal Finkel #include "llvm/IR/DataLayout.h"
21bbccdf6fSOCHyams #include "llvm/IR/DebugInfo.h"
229fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
2396ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h"
2403eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
259fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h"
269fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
27a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h"
289fb823bbSChandler Carruth #include "llvm/IR/Module.h"
299fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
304220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h"
319fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h"
324c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
33ef860a24SChandler Carruth #include "llvm/Support/Debug.h"
34ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h"
35ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h"
36799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h"
37ef860a24SChandler Carruth #include <algorithm>
38ecefe5a8SEugene Zelenko 
39ef860a24SChandler Carruth using namespace llvm;
40ef860a24SChandler Carruth 
415698537fSPhilip Reames static cl::opt<unsigned> UseDerefAtPointSemantics(
425698537fSPhilip Reames     "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false),
435698537fSPhilip Reames     cl::desc("Deref attributes and metadata infer facts at definition only"));
445698537fSPhilip Reames 
45ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
46ef860a24SChandler Carruth //                                Value Class
47ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
48ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) {
49ef860a24SChandler Carruth   assert(Ty && "Value defined with a null type: Error!");
5016bf89ecSReid Kleckner   return Ty;
51ef860a24SChandler Carruth }
52ef860a24SChandler Carruth 
53ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid)
547975b8c3SSerge Pavlov     : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), HasValueHandle(0),
557975b8c3SSerge Pavlov       SubclassOptionalData(0), SubclassData(0), NumUserOperands(0),
567975b8c3SSerge Pavlov       IsUsedByMD(false), HasName(false), HasMetadata(false) {
579fd33f24SSerge Guelton   static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
58ef860a24SChandler Carruth   // FIXME: Why isn't this in the subclass gunk??
59ef860a24SChandler Carruth   // Note, we cannot call isa<CallInst> before the CallInst has been
60ef860a24SChandler Carruth   // constructed.
61ffaca140SSami Tolvanen   unsigned OpCode = 0;
62ffaca140SSami Tolvanen   if (SubclassID >= InstructionVal)
63ffaca140SSami Tolvanen     OpCode = SubclassID - InstructionVal;
64ffaca140SSami Tolvanen   if (OpCode == Instruction::Call || OpCode == Instruction::Invoke ||
65ffaca140SSami Tolvanen       OpCode == Instruction::CallBr)
66ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
67ffaca140SSami Tolvanen            "invalid CallBase type!");
68ef860a24SChandler Carruth   else if (SubclassID != BasicBlockVal &&
699fd33f24SSerge Guelton            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
70ef860a24SChandler Carruth     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
71ef860a24SChandler Carruth            "Cannot create non-first-class values except for constants!");
7296ab8726SReid Kleckner   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
731762ad3eSReid Kleckner                 "Value too big");
74ef860a24SChandler Carruth }
75ef860a24SChandler Carruth 
76ef860a24SChandler Carruth Value::~Value() {
77ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
78ef860a24SChandler Carruth   if (HasValueHandle)
79ef860a24SChandler Carruth     ValueHandleBase::ValueIsDeleted(this);
805bf8fef5SDuncan P. N. Exon Smith   if (isUsedByMetadata())
815bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleDeletion(this);
82ef860a24SChandler Carruth 
837975b8c3SSerge Pavlov   // Remove associated metadata from context.
847975b8c3SSerge Pavlov   if (HasMetadata)
857975b8c3SSerge Pavlov     clearMetadata();
867975b8c3SSerge Pavlov 
87ef860a24SChandler Carruth #ifndef NDEBUG      // Only in -g mode...
88ef860a24SChandler Carruth   // Check to make sure that there are no uses of this value that are still
89ef860a24SChandler Carruth   // around when the value is destroyed.  If there are, then we have a dangling
90b93fb82bSAndrew Kaylor   // reference and something is wrong.  This code is here to print out where
91b93fb82bSAndrew Kaylor   // the value is still being referenced.
92ef860a24SChandler Carruth   //
937dd28109SEvgenii Stepanov   // Note that use_empty() cannot be called here, as it eventually downcasts
947dd28109SEvgenii Stepanov   // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
957dd28109SEvgenii Stepanov   // been destructed, so accessing it is UB.
967dd28109SEvgenii Stepanov   //
977dd28109SEvgenii Stepanov   if (!materialized_use_empty()) {
98ef860a24SChandler Carruth     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
99b93fb82bSAndrew Kaylor     for (auto *U : users())
100b93fb82bSAndrew Kaylor       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
101ef860a24SChandler Carruth   }
102ef860a24SChandler Carruth #endif
1037dd28109SEvgenii Stepanov   assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
104ef860a24SChandler Carruth 
105ef860a24SChandler Carruth   // If this value is named, destroy the name.  This should not be in a symtab
106ef860a24SChandler Carruth   // at this point.
1075bf8fef5SDuncan P. N. Exon Smith   destroyValueName();
108ef860a24SChandler Carruth }
109ef860a24SChandler Carruth 
11096ab8726SReid Kleckner void Value::deleteValue() {
11196ab8726SReid Kleckner   switch (getValueID()) {
11296ab8726SReid Kleckner #define HANDLE_VALUE(Name)                                                     \
11396ab8726SReid Kleckner   case Value::Name##Val:                                                       \
11496ab8726SReid Kleckner     delete static_cast<Name *>(this);                                          \
11596ab8726SReid Kleckner     break;
11696ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name)                                              \
11796ab8726SReid Kleckner   case Value::Name##Val:                                                       \
11896ab8726SReid Kleckner     static_cast<DerivedUser *>(this)->DeleteValue(                             \
11996ab8726SReid Kleckner         static_cast<DerivedUser *>(this));                                     \
12096ab8726SReid Kleckner     break;
12115440191SEli Friedman #define HANDLE_CONSTANT(Name)                                                  \
12215440191SEli Friedman   case Value::Name##Val:                                                       \
12315440191SEli Friedman     llvm_unreachable("constants should be destroyed with destroyConstant");    \
12415440191SEli Friedman     break;
12596ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name)  /* nothing */
12696ab8726SReid Kleckner #include "llvm/IR/Value.def"
12796ab8726SReid Kleckner 
12896ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS)                                             \
12996ab8726SReid Kleckner   case Value::InstructionVal + Instruction::OPC:                               \
13096ab8726SReid Kleckner     delete static_cast<CLASS *>(this);                                         \
13196ab8726SReid Kleckner     break;
13296ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS)
13396ab8726SReid Kleckner #include "llvm/IR/Instruction.def"
13496ab8726SReid Kleckner 
13596ab8726SReid Kleckner   default:
13696ab8726SReid Kleckner     llvm_unreachable("attempting to delete unknown value kind");
13796ab8726SReid Kleckner   }
13896ab8726SReid Kleckner }
13996ab8726SReid Kleckner 
1405bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() {
1415bf8fef5SDuncan P. N. Exon Smith   ValueName *Name = getValueName();
14289c8ffd5SChris Lattner   if (Name) {
14389c8ffd5SChris Lattner     MallocAllocator Allocator;
14489c8ffd5SChris Lattner     Name->Destroy(Allocator);
14589c8ffd5SChris Lattner   }
1465bf8fef5SDuncan P. N. Exon Smith   setValueName(nullptr);
1475bf8fef5SDuncan P. N. Exon Smith }
1485bf8fef5SDuncan P. N. Exon Smith 
149ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const {
1504de31bbaSVedant Kumar   return hasNItems(use_begin(), use_end(), N);
151ef860a24SChandler Carruth }
152ef860a24SChandler Carruth 
153ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const {
1544de31bbaSVedant Kumar   return hasNItemsOrMore(use_begin(), use_end(), N);
155ef860a24SChandler Carruth }
156ef860a24SChandler Carruth 
15795848ea1SRoman Lebedev bool Value::hasOneUser() const {
15895848ea1SRoman Lebedev   if (use_empty())
15995848ea1SRoman Lebedev     return false;
16095848ea1SRoman Lebedev   if (hasOneUse())
16195848ea1SRoman Lebedev     return true;
16295848ea1SRoman Lebedev   return std::equal(++user_begin(), user_end(), user_begin());
16395848ea1SRoman Lebedev }
16495848ea1SRoman Lebedev 
165f16f139dSTyker static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
166f16f139dSTyker 
16732734304SAnna Thomas Use *Value::getSingleUndroppableUse() {
16832734304SAnna Thomas   Use *Result = nullptr;
16932734304SAnna Thomas   for (Use &U : uses()) {
17032734304SAnna Thomas     if (!U.getUser()->isDroppable()) {
17132734304SAnna Thomas       if (Result)
17232734304SAnna Thomas         return nullptr;
17332734304SAnna Thomas       Result = &U;
17432734304SAnna Thomas     }
17532734304SAnna Thomas   }
17632734304SAnna Thomas   return Result;
17732734304SAnna Thomas }
17832734304SAnna Thomas 
17969921f6fSAnna Thomas User *Value::getUniqueUndroppableUser() {
18069921f6fSAnna Thomas   User *Result = nullptr;
18169921f6fSAnna Thomas   for (auto *U : users()) {
18269921f6fSAnna Thomas     if (!U->isDroppable()) {
18369921f6fSAnna Thomas       if (Result && Result != U)
18469921f6fSAnna Thomas         return nullptr;
18569921f6fSAnna Thomas       Result = U;
18669921f6fSAnna Thomas     }
18769921f6fSAnna Thomas   }
18869921f6fSAnna Thomas   return Result;
18969921f6fSAnna Thomas }
19069921f6fSAnna Thomas 
191f16f139dSTyker bool Value::hasNUndroppableUses(unsigned int N) const {
192f16f139dSTyker   return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
193f16f139dSTyker }
194f16f139dSTyker 
195f16f139dSTyker bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
196f16f139dSTyker   return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
197f16f139dSTyker }
198f16f139dSTyker 
199f16f139dSTyker void Value::dropDroppableUses(
200f16f139dSTyker     llvm::function_ref<bool(const Use *)> ShouldDrop) {
201f16f139dSTyker   SmallVector<Use *, 8> ToBeEdited;
202f16f139dSTyker   for (Use &U : uses())
203f16f139dSTyker     if (U.getUser()->isDroppable() && ShouldDrop(&U))
204f16f139dSTyker       ToBeEdited.push_back(&U);
205450dc09dSJohannes Doerfert   for (Use *U : ToBeEdited)
206450dc09dSJohannes Doerfert     dropDroppableUse(*U);
207f16f139dSTyker }
208450dc09dSJohannes Doerfert 
209450dc09dSJohannes Doerfert void Value::dropDroppableUsesIn(User &Usr) {
210450dc09dSJohannes Doerfert   assert(Usr.isDroppable() && "Expected a droppable user!");
211450dc09dSJohannes Doerfert   for (Use &UsrOp : Usr.operands()) {
212450dc09dSJohannes Doerfert     if (UsrOp.get() == this)
213450dc09dSJohannes Doerfert       dropDroppableUse(UsrOp);
214f16f139dSTyker   }
215f16f139dSTyker }
216f16f139dSTyker 
217450dc09dSJohannes Doerfert void Value::dropDroppableUse(Use &U) {
218450dc09dSJohannes Doerfert   U.removeFromList();
219908215b3SPhilip Reames   if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) {
220450dc09dSJohannes Doerfert     unsigned OpNo = U.getOperandNo();
221450dc09dSJohannes Doerfert     if (OpNo == 0)
222450dc09dSJohannes Doerfert       U.set(ConstantInt::getTrue(Assume->getContext()));
223450dc09dSJohannes Doerfert     else {
224450dc09dSJohannes Doerfert       U.set(UndefValue::get(U.get()->getType()));
225450dc09dSJohannes Doerfert       CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
2266d365741STyker       BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
227450dc09dSJohannes Doerfert     }
228450dc09dSJohannes Doerfert     return;
229450dc09dSJohannes Doerfert   }
230450dc09dSJohannes Doerfert 
231450dc09dSJohannes Doerfert   llvm_unreachable("unkown droppable use");
232ce8928f2SJohannes Doerfert }
233ce8928f2SJohannes Doerfert 
234ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
2350925b24dSJakob Stoklund Olesen   // This can be computed either by scanning the instructions in BB, or by
2360925b24dSJakob Stoklund Olesen   // scanning the use list of this Value. Both lists can be very long, but
2370925b24dSJakob Stoklund Olesen   // usually one is quite short.
2380925b24dSJakob Stoklund Olesen   //
2390925b24dSJakob Stoklund Olesen   // Scan both lists simultaneously until one is exhausted. This limits the
2400925b24dSJakob Stoklund Olesen   // search to the shorter list.
2410925b24dSJakob Stoklund Olesen   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
242cdf47884SChandler Carruth   const_user_iterator UI = user_begin(), UE = user_end();
2430925b24dSJakob Stoklund Olesen   for (; BI != BE && UI != UE; ++BI, ++UI) {
2440925b24dSJakob Stoklund Olesen     // Scan basic block: Check if this Value is used by the instruction at BI.
24542531260SDavid Majnemer     if (is_contained(BI->operands(), this))
246ef860a24SChandler Carruth       return true;
2470925b24dSJakob Stoklund Olesen     // Scan use list: Check if the use at UI is in BB.
24842531260SDavid Majnemer     const auto *User = dyn_cast<Instruction>(*UI);
249ef860a24SChandler Carruth     if (User && User->getParent() == BB)
250ef860a24SChandler Carruth       return true;
251ef860a24SChandler Carruth   }
252ef860a24SChandler Carruth   return false;
253ef860a24SChandler Carruth }
254ef860a24SChandler Carruth 
2555a0872c2SVedant Kumar unsigned Value::getNumUses() const {
2565a0872c2SVedant Kumar   return (unsigned)std::distance(use_begin(), use_end());
2575a0872c2SVedant Kumar }
258ef860a24SChandler Carruth 
259ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
260c620761cSCraig Topper   ST = nullptr;
261ef860a24SChandler Carruth   if (Instruction *I = dyn_cast<Instruction>(V)) {
262ef860a24SChandler Carruth     if (BasicBlock *P = I->getParent())
263ef860a24SChandler Carruth       if (Function *PP = P->getParent())
264a53d49e1SMehdi Amini         ST = PP->getValueSymbolTable();
265ef860a24SChandler Carruth   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
266ef860a24SChandler Carruth     if (Function *P = BB->getParent())
267a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
268ef860a24SChandler Carruth   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
269ef860a24SChandler Carruth     if (Module *P = GV->getParent())
270ef860a24SChandler Carruth       ST = &P->getValueSymbolTable();
271ef860a24SChandler Carruth   } else if (Argument *A = dyn_cast<Argument>(V)) {
272ef860a24SChandler Carruth     if (Function *P = A->getParent())
273a53d49e1SMehdi Amini       ST = P->getValueSymbolTable();
2745bf8fef5SDuncan P. N. Exon Smith   } else {
275ef860a24SChandler Carruth     assert(isa<Constant>(V) && "Unknown value type!");
276ef860a24SChandler Carruth     return true;  // no name is setable for this.
277ef860a24SChandler Carruth   }
278ef860a24SChandler Carruth   return false;
279ef860a24SChandler Carruth }
280ef860a24SChandler Carruth 
2817349ab93SOwen Anderson ValueName *Value::getValueName() const {
2827349ab93SOwen Anderson   if (!HasName) return nullptr;
2837349ab93SOwen Anderson 
2847349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2857349ab93SOwen Anderson   auto I = Ctx.pImpl->ValueNames.find(this);
2867349ab93SOwen Anderson   assert(I != Ctx.pImpl->ValueNames.end() &&
2877349ab93SOwen Anderson          "No name entry found!");
2887349ab93SOwen Anderson 
2897349ab93SOwen Anderson   return I->second;
2907349ab93SOwen Anderson }
2917349ab93SOwen Anderson 
2927349ab93SOwen Anderson void Value::setValueName(ValueName *VN) {
2937349ab93SOwen Anderson   LLVMContext &Ctx = getContext();
2947349ab93SOwen Anderson 
2957349ab93SOwen Anderson   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
2967349ab93SOwen Anderson          "HasName bit out of sync!");
2977349ab93SOwen Anderson 
2987349ab93SOwen Anderson   if (!VN) {
2997349ab93SOwen Anderson     if (HasName)
3007349ab93SOwen Anderson       Ctx.pImpl->ValueNames.erase(this);
3017349ab93SOwen Anderson     HasName = false;
3027349ab93SOwen Anderson     return;
3037349ab93SOwen Anderson   }
3047349ab93SOwen Anderson 
3057349ab93SOwen Anderson   HasName = true;
3067349ab93SOwen Anderson   Ctx.pImpl->ValueNames[this] = VN;
3077349ab93SOwen Anderson }
3087349ab93SOwen Anderson 
309ef860a24SChandler Carruth StringRef Value::getName() const {
310ef860a24SChandler Carruth   // Make sure the empty string is still a C string. For historical reasons,
311ef860a24SChandler Carruth   // some clients want to call .data() on the result and expect it to be null
312ef860a24SChandler Carruth   // terminated.
3137349ab93SOwen Anderson   if (!hasName())
3145bf8fef5SDuncan P. N. Exon Smith     return StringRef("", 0);
3155bf8fef5SDuncan P. N. Exon Smith   return getValueName()->getKey();
316ef860a24SChandler Carruth }
317ef860a24SChandler Carruth 
318a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) {
31909b4a8daSMehdi Amini   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
32050af49fcSMehdi Amini   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
32109b4a8daSMehdi Amini     return;
32209b4a8daSMehdi Amini 
323ef860a24SChandler Carruth   // Fast path for common IRBuilder case of setName("") when there is no name.
324ef860a24SChandler Carruth   if (NewName.isTriviallyEmpty() && !hasName())
325ef860a24SChandler Carruth     return;
326ef860a24SChandler Carruth 
327ef860a24SChandler Carruth   SmallString<256> NameData;
328ef860a24SChandler Carruth   StringRef NameRef = NewName.toStringRef(NameData);
32909d689f9SRafael Espindola   assert(NameRef.find_first_of(0) == StringRef::npos &&
33009d689f9SRafael Espindola          "Null bytes are not allowed in names");
331ef860a24SChandler Carruth 
332ef860a24SChandler Carruth   // Name isn't changing?
333ef860a24SChandler Carruth   if (getName() == NameRef)
334ef860a24SChandler Carruth     return;
335ef860a24SChandler Carruth 
336ef860a24SChandler Carruth   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
337ef860a24SChandler Carruth 
338ef860a24SChandler Carruth   // Get the symbol table to update for this object.
339ef860a24SChandler Carruth   ValueSymbolTable *ST;
340ef860a24SChandler Carruth   if (getSymTab(this, ST))
341ef860a24SChandler Carruth     return;  // Cannot set a name on this value (e.g. constant).
342ef860a24SChandler Carruth 
343ef860a24SChandler Carruth   if (!ST) { // No symbol table to update?  Just do the change.
344ef860a24SChandler Carruth     if (NameRef.empty()) {
345ef860a24SChandler Carruth       // Free the name for this value.
3465bf8fef5SDuncan P. N. Exon Smith       destroyValueName();
347ef860a24SChandler Carruth       return;
348ef860a24SChandler Carruth     }
349ef860a24SChandler Carruth 
350ef860a24SChandler Carruth     // NOTE: Could optimize for the case the name is shrinking to not deallocate
351ef860a24SChandler Carruth     // then reallocated.
3525bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
353ef860a24SChandler Carruth 
354ef860a24SChandler Carruth     // Create the new name.
35589c8ffd5SChris Lattner     MallocAllocator Allocator;
35689c8ffd5SChris Lattner     setValueName(ValueName::Create(NameRef, Allocator));
3575bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
358ef860a24SChandler Carruth     return;
359ef860a24SChandler Carruth   }
360ef860a24SChandler Carruth 
361ef860a24SChandler Carruth   // NOTE: Could optimize for the case the name is shrinking to not deallocate
362ef860a24SChandler Carruth   // then reallocated.
363ef860a24SChandler Carruth   if (hasName()) {
364ef860a24SChandler Carruth     // Remove old name.
3655bf8fef5SDuncan P. N. Exon Smith     ST->removeValueName(getValueName());
3665bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
367ef860a24SChandler Carruth 
368ef860a24SChandler Carruth     if (NameRef.empty())
369ef860a24SChandler Carruth       return;
370ef860a24SChandler Carruth   }
371ef860a24SChandler Carruth 
372ef860a24SChandler Carruth   // Name is changing to something new.
3735bf8fef5SDuncan P. N. Exon Smith   setValueName(ST->createValueName(NameRef, this));
374ef860a24SChandler Carruth }
375ef860a24SChandler Carruth 
376a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) {
377a7c0c18cSPete Cooper   setNameImpl(NewName);
378a7c0c18cSPete Cooper   if (Function *F = dyn_cast<Function>(this))
379a7c0c18cSPete Cooper     F->recalculateIntrinsicID();
380a7c0c18cSPete Cooper }
381a7c0c18cSPete Cooper 
382ef860a24SChandler Carruth void Value::takeName(Value *V) {
383c620761cSCraig Topper   ValueSymbolTable *ST = nullptr;
384ef860a24SChandler Carruth   // If this value has a name, drop it.
385ef860a24SChandler Carruth   if (hasName()) {
386ef860a24SChandler Carruth     // Get the symtab this is in.
387ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
388ef860a24SChandler Carruth       // We can't set a name on this value, but we need to clear V's name if
389ef860a24SChandler Carruth       // it has one.
390ef860a24SChandler Carruth       if (V->hasName()) V->setName("");
391ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
392ef860a24SChandler Carruth     }
393ef860a24SChandler Carruth 
394ef860a24SChandler Carruth     // Remove old name.
395ef860a24SChandler Carruth     if (ST)
3965bf8fef5SDuncan P. N. Exon Smith       ST->removeValueName(getValueName());
3975bf8fef5SDuncan P. N. Exon Smith     destroyValueName();
398ef860a24SChandler Carruth   }
399ef860a24SChandler Carruth 
400ef860a24SChandler Carruth   // Now we know that this has no name.
401ef860a24SChandler Carruth 
402ef860a24SChandler Carruth   // If V has no name either, we're done.
403ef860a24SChandler Carruth   if (!V->hasName()) return;
404ef860a24SChandler Carruth 
405ef860a24SChandler Carruth   // Get this's symtab if we didn't before.
406ef860a24SChandler Carruth   if (!ST) {
407ef860a24SChandler Carruth     if (getSymTab(this, ST)) {
408ef860a24SChandler Carruth       // Clear V's name.
409ef860a24SChandler Carruth       V->setName("");
410ef860a24SChandler Carruth       return;  // Cannot set a name on this value (e.g. constant).
411ef860a24SChandler Carruth     }
412ef860a24SChandler Carruth   }
413ef860a24SChandler Carruth 
414ef860a24SChandler Carruth   // Get V's ST, this should always succed, because V has a name.
415ef860a24SChandler Carruth   ValueSymbolTable *VST;
416ef860a24SChandler Carruth   bool Failure = getSymTab(V, VST);
417ef860a24SChandler Carruth   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
418ef860a24SChandler Carruth 
419ef860a24SChandler Carruth   // If these values are both in the same symtab, we can do this very fast.
420ef860a24SChandler Carruth   // This works even if both values have no symtab yet.
421ef860a24SChandler Carruth   if (ST == VST) {
422ef860a24SChandler Carruth     // Take the name!
4235bf8fef5SDuncan P. N. Exon Smith     setValueName(V->getValueName());
4245bf8fef5SDuncan P. N. Exon Smith     V->setValueName(nullptr);
4255bf8fef5SDuncan P. N. Exon Smith     getValueName()->setValue(this);
426ef860a24SChandler Carruth     return;
427ef860a24SChandler Carruth   }
428ef860a24SChandler Carruth 
429ef860a24SChandler Carruth   // Otherwise, things are slightly more complex.  Remove V's name from VST and
430ef860a24SChandler Carruth   // then reinsert it into ST.
431ef860a24SChandler Carruth 
432ef860a24SChandler Carruth   if (VST)
4335bf8fef5SDuncan P. N. Exon Smith     VST->removeValueName(V->getValueName());
4345bf8fef5SDuncan P. N. Exon Smith   setValueName(V->getValueName());
4355bf8fef5SDuncan P. N. Exon Smith   V->setValueName(nullptr);
4365bf8fef5SDuncan P. N. Exon Smith   getValueName()->setValue(this);
437ef860a24SChandler Carruth 
438ef860a24SChandler Carruth   if (ST)
439ef860a24SChandler Carruth     ST->reinsertValue(this);
440ef860a24SChandler Carruth }
441ef860a24SChandler Carruth 
442905623b6SQuentin Colombet #ifndef NDEBUG
443905623b6SQuentin Colombet std::string Value::getNameOrAsOperand() const {
444905623b6SQuentin Colombet   if (!getName().empty())
445905623b6SQuentin Colombet     return std::string(getName());
446905623b6SQuentin Colombet 
447905623b6SQuentin Colombet   std::string BBName;
448905623b6SQuentin Colombet   raw_string_ostream OS(BBName);
449905623b6SQuentin Colombet   printAsOperand(OS, false);
450905623b6SQuentin Colombet   return OS.str();
451905623b6SQuentin Colombet }
452905623b6SQuentin Colombet #endif
453905623b6SQuentin Colombet 
454eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const {
455675bdcedSTodd Fiala #ifndef NDEBUG
456257a3536SRafael Espindola   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
457257a3536SRafael Espindola   if (!GV)
458257a3536SRafael Espindola     return;
459257a3536SRafael Espindola   const Module *M = GV->getParent();
460257a3536SRafael Espindola   if (!M)
461257a3536SRafael Espindola     return;
462257a3536SRafael Espindola   assert(M->isMaterialized());
463675bdcedSTodd Fiala #endif
464257a3536SRafael Espindola }
465257a3536SRafael Espindola 
466675bdcedSTodd Fiala #ifndef NDEBUG
46771b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
4687e2b7567SRafael Espindola                      Constant *C) {
46970573dcdSDavid Blaikie   if (!Cache.insert(Expr).second)
4707e2b7567SRafael Espindola     return false;
4717e2b7567SRafael Espindola 
4727e2b7567SRafael Espindola   for (auto &O : Expr->operands()) {
4737e2b7567SRafael Espindola     if (O == C)
4747e2b7567SRafael Espindola       return true;
4757e2b7567SRafael Espindola     auto *CE = dyn_cast<ConstantExpr>(O);
4767e2b7567SRafael Espindola     if (!CE)
4777e2b7567SRafael Espindola       continue;
4787e2b7567SRafael Espindola     if (contains(Cache, CE, C))
4797e2b7567SRafael Espindola       return true;
4807e2b7567SRafael Espindola   }
4817e2b7567SRafael Espindola   return false;
4827e2b7567SRafael Espindola }
4837e2b7567SRafael Espindola 
4847e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) {
4857e2b7567SRafael Espindola   if (Expr == V)
4867e2b7567SRafael Espindola     return true;
4877e2b7567SRafael Espindola 
4887e2b7567SRafael Espindola   auto *C = dyn_cast<Constant>(V);
4897e2b7567SRafael Espindola   if (!C)
4907e2b7567SRafael Espindola     return false;
4917e2b7567SRafael Espindola 
4927e2b7567SRafael Espindola   auto *CE = dyn_cast<ConstantExpr>(Expr);
4937e2b7567SRafael Espindola   if (!CE)
4947e2b7567SRafael Espindola     return false;
4957e2b7567SRafael Espindola 
4967e2b7567SRafael Espindola   SmallPtrSet<ConstantExpr *, 4> Cache;
4977e2b7567SRafael Espindola   return contains(Cache, CE, C);
4987e2b7567SRafael Espindola }
499ecefe5a8SEugene Zelenko #endif // NDEBUG
500ef860a24SChandler Carruth 
501e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
502ef860a24SChandler Carruth   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
5037e2b7567SRafael Espindola   assert(!contains(New, this) &&
5047e2b7567SRafael Espindola          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
505ef860a24SChandler Carruth   assert(New->getType() == getType() &&
506ef860a24SChandler Carruth          "replaceAllUses of value with new value of different type!");
507ef860a24SChandler Carruth 
508ef860a24SChandler Carruth   // Notify all ValueHandles (if present) that this value is going away.
509ef860a24SChandler Carruth   if (HasValueHandle)
510ef860a24SChandler Carruth     ValueHandleBase::ValueIsRAUWd(this, New);
511e69ae76bSJF Bastien   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
5125bf8fef5SDuncan P. N. Exon Smith     ValueAsMetadata::handleRAUW(this, New);
513ef860a24SChandler Carruth 
51481bbf742STeresa Johnson   while (!materialized_use_empty()) {
515ef860a24SChandler Carruth     Use &U = *UseList;
516ef860a24SChandler Carruth     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
517ef860a24SChandler Carruth     // constant because they are uniqued.
5186b238633SRafael Espindola     if (auto *C = dyn_cast<Constant>(U.getUser())) {
519ef860a24SChandler Carruth       if (!isa<GlobalValue>(C)) {
5208914d290SMehdi Amini         C->handleOperandChange(this, New);
521ef860a24SChandler Carruth         continue;
522ef860a24SChandler Carruth       }
523ef860a24SChandler Carruth     }
524ef860a24SChandler Carruth 
525ef860a24SChandler Carruth     U.set(New);
526ef860a24SChandler Carruth   }
527ef860a24SChandler Carruth 
528ef860a24SChandler Carruth   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
529ef860a24SChandler Carruth     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
530ef860a24SChandler Carruth }
531ef860a24SChandler Carruth 
5321ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) {
533e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::Yes);
5341ed53963SDavide Italiano }
5351ed53963SDavide Italiano 
5361ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) {
537e69ae76bSJF Bastien   doRAUW(New, ReplaceMetadataUses::No);
5381ed53963SDavide Italiano }
5391ed53963SDavide Italiano 
5408f681d5bSStanislav Mekhanoshin void Value::replaceUsesWithIf(Value *New,
5418f681d5bSStanislav Mekhanoshin                               llvm::function_ref<bool(Use &U)> ShouldReplace) {
5428f681d5bSStanislav Mekhanoshin   assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
5438f681d5bSStanislav Mekhanoshin   assert(New->getType() == getType() &&
5448f681d5bSStanislav Mekhanoshin          "replaceUses of value with new value of different type!");
5458f681d5bSStanislav Mekhanoshin 
546b608053eSStanislav Mekhanoshin   SmallVector<TrackingVH<Constant>, 8> Consts;
547b608053eSStanislav Mekhanoshin   SmallPtrSet<Constant *, 8> Visited;
548b608053eSStanislav Mekhanoshin 
5498f681d5bSStanislav Mekhanoshin   for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
5508f681d5bSStanislav Mekhanoshin     Use &U = *UI;
5518f681d5bSStanislav Mekhanoshin     ++UI;
5528f681d5bSStanislav Mekhanoshin     if (!ShouldReplace(U))
5538f681d5bSStanislav Mekhanoshin       continue;
5548f681d5bSStanislav Mekhanoshin     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
5558f681d5bSStanislav Mekhanoshin     // constant because they are uniqued.
5568f681d5bSStanislav Mekhanoshin     if (auto *C = dyn_cast<Constant>(U.getUser())) {
5578f681d5bSStanislav Mekhanoshin       if (!isa<GlobalValue>(C)) {
558b608053eSStanislav Mekhanoshin         if (Visited.insert(C).second)
559b608053eSStanislav Mekhanoshin           Consts.push_back(TrackingVH<Constant>(C));
5608f681d5bSStanislav Mekhanoshin         continue;
5618f681d5bSStanislav Mekhanoshin       }
5628f681d5bSStanislav Mekhanoshin     }
5638f681d5bSStanislav Mekhanoshin     U.set(New);
5648f681d5bSStanislav Mekhanoshin   }
565b608053eSStanislav Mekhanoshin 
566b608053eSStanislav Mekhanoshin   while (!Consts.empty()) {
567b608053eSStanislav Mekhanoshin     // FIXME: handleOperandChange() updates all the uses in a given Constant,
568b608053eSStanislav Mekhanoshin     //        not just the one passed to ShouldReplace
569b608053eSStanislav Mekhanoshin     Consts.pop_back_val()->handleOperandChange(this, New);
570b608053eSStanislav Mekhanoshin   }
5718f681d5bSStanislav Mekhanoshin }
5728f681d5bSStanislav Mekhanoshin 
573bbccdf6fSOCHyams /// Replace llvm.dbg.* uses of MetadataAsValue(ValueAsMetadata(V)) outside BB
574bbccdf6fSOCHyams /// with New.
575bbccdf6fSOCHyams static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) {
576bbccdf6fSOCHyams   SmallVector<DbgVariableIntrinsic *> DbgUsers;
577bbccdf6fSOCHyams   findDbgUsers(DbgUsers, V);
578bbccdf6fSOCHyams   for (auto *DVI : DbgUsers) {
579bbccdf6fSOCHyams     if (DVI->getParent() != BB)
580bbccdf6fSOCHyams       DVI->replaceVariableLocationOp(V, New);
581bbccdf6fSOCHyams   }
582bbccdf6fSOCHyams }
583bbccdf6fSOCHyams 
584ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks.
585ec6217c9SGerolf Hoflehner // This routine leaves uses within BB.
586ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
587ec6217c9SGerolf Hoflehner   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
588ec6217c9SGerolf Hoflehner   assert(!contains(New, this) &&
589ec6217c9SGerolf Hoflehner          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
590ec6217c9SGerolf Hoflehner   assert(New->getType() == getType() &&
591ec6217c9SGerolf Hoflehner          "replaceUses of value with new value of different type!");
592ec6217c9SGerolf Hoflehner   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
593ec6217c9SGerolf Hoflehner 
594bbccdf6fSOCHyams   replaceDbgUsesOutsideBlock(this, New, BB);
595081e990dSRoman Lebedev   replaceUsesWithIf(New, [BB](Use &U) {
596081e990dSRoman Lebedev     auto *I = dyn_cast<Instruction>(U.getUser());
597081e990dSRoman Lebedev     // Don't replace if it's an instruction in the BB basic block.
598081e990dSRoman Lebedev     return !I || I->getParent() != BB;
599081e990dSRoman Lebedev   });
600ec6217c9SGerolf Hoflehner }
601ec6217c9SGerolf Hoflehner 
602ef860a24SChandler Carruth namespace {
603ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers.
604ef860a24SChandler Carruth enum PointerStripKind {
605ef860a24SChandler Carruth   PSK_ZeroIndices,
6068a410bceSErich Keane   PSK_ZeroIndicesAndAliases,
6072452d703SPeter Collingbourne   PSK_ZeroIndicesSameRepresentation,
60870e3c9a8SNikita Popov   PSK_ForAliasAnalysis,
609ef860a24SChandler Carruth   PSK_InBoundsConstantIndices,
610ef860a24SChandler Carruth   PSK_InBounds
611ef860a24SChandler Carruth };
612ef860a24SChandler Carruth 
61367448a8cSTyker template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
61467448a8cSTyker 
615ef860a24SChandler Carruth template <PointerStripKind StripKind>
616b7338fb1STyker static const Value *stripPointerCastsAndOffsets(
617b7338fb1STyker     const Value *V,
61867448a8cSTyker     function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
619ef860a24SChandler Carruth   if (!V->getType()->isPointerTy())
620ef860a24SChandler Carruth     return V;
621ef860a24SChandler Carruth 
622ef860a24SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
623ef860a24SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
6241dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
625ef860a24SChandler Carruth 
626ef860a24SChandler Carruth   Visited.insert(V);
627ef860a24SChandler Carruth   do {
628b7338fb1STyker     Func(V);
6291dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
630ef860a24SChandler Carruth       switch (StripKind) {
631ef860a24SChandler Carruth       case PSK_ZeroIndices:
6328a410bceSErich Keane       case PSK_ZeroIndicesAndAliases:
6332452d703SPeter Collingbourne       case PSK_ZeroIndicesSameRepresentation:
63470e3c9a8SNikita Popov       case PSK_ForAliasAnalysis:
635ef860a24SChandler Carruth         if (!GEP->hasAllZeroIndices())
636ef860a24SChandler Carruth           return V;
637ef860a24SChandler Carruth         break;
638ef860a24SChandler Carruth       case PSK_InBoundsConstantIndices:
639ef860a24SChandler Carruth         if (!GEP->hasAllConstantIndices())
640ef860a24SChandler Carruth           return V;
641b03fd12cSJustin Bogner         LLVM_FALLTHROUGH;
642ef860a24SChandler Carruth       case PSK_InBounds:
643ef860a24SChandler Carruth         if (!GEP->isInBounds())
644ef860a24SChandler Carruth           return V;
645ef860a24SChandler Carruth         break;
646ef860a24SChandler Carruth       }
647ef860a24SChandler Carruth       V = GEP->getPointerOperand();
64840107ce7SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
64940107ce7SJohannes Doerfert       V = cast<Operator>(V)->getOperand(0);
6502b8d706bSRoman Lebedev       if (!V->getType()->isPointerTy())
6512b8d706bSRoman Lebedev         return V;
6522452d703SPeter Collingbourne     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
653b03bd4d9SMatt Arsenault                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
65440107ce7SJohannes Doerfert       // TODO: If we know an address space cast will not change the
65540107ce7SJohannes Doerfert       //       representation we could look through it here as well.
656ef860a24SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
6578a410bceSErich Keane     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
6588a410bceSErich Keane       V = cast<GlobalAlias>(V)->getAliasee();
65970e3c9a8SNikita Popov     } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
66070e3c9a8SNikita Popov                cast<PHINode>(V)->getNumIncomingValues() == 1) {
66170e3c9a8SNikita Popov       V = cast<PHINode>(V)->getIncomingValue(0);
662ef860a24SChandler Carruth     } else {
66390c09232SChandler Carruth       if (const auto *Call = dyn_cast<CallBase>(V)) {
66490c09232SChandler Carruth         if (const Value *RV = Call->getReturnedArgOperand()) {
6655c12d8feSHal Finkel           V = RV;
6665c12d8feSHal Finkel           continue;
6675c12d8feSHal Finkel         }
6685dde8094SPiotr Padlewski         // The result of launder.invariant.group must alias it's argument,
669610c966aSPiotr Padlewski         // but it can't be marked with returned attribute, that's why it needs
670610c966aSPiotr Padlewski         // special case.
67170e3c9a8SNikita Popov         if (StripKind == PSK_ForAliasAnalysis &&
67290c09232SChandler Carruth             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
67390c09232SChandler Carruth              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
67490c09232SChandler Carruth           V = Call->getArgOperand(0);
675610c966aSPiotr Padlewski           continue;
676610c966aSPiotr Padlewski         }
677610c966aSPiotr Padlewski       }
678ef860a24SChandler Carruth       return V;
679ef860a24SChandler Carruth     }
680ef860a24SChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
68170573dcdSDavid Blaikie   } while (Visited.insert(V).second);
682ef860a24SChandler Carruth 
683ef860a24SChandler Carruth   return V;
684ef860a24SChandler Carruth }
685ecefe5a8SEugene Zelenko } // end anonymous namespace
686ef860a24SChandler Carruth 
6871dd20e65SCraig Topper const Value *Value::stripPointerCasts() const {
6882452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
689c229a4ffSRafael Espindola }
690c229a4ffSRafael Espindola 
6918a410bceSErich Keane const Value *Value::stripPointerCastsAndAliases() const {
6928a410bceSErich Keane   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
6938a410bceSErich Keane }
6948a410bceSErich Keane 
69540107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const {
6962452d703SPeter Collingbourne   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
697ef860a24SChandler Carruth }
698ef860a24SChandler Carruth 
6991dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const {
700ef860a24SChandler Carruth   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
701ef860a24SChandler Carruth }
702ef860a24SChandler Carruth 
70370e3c9a8SNikita Popov const Value *Value::stripPointerCastsForAliasAnalysis() const {
70470e3c9a8SNikita Popov   return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this);
705610c966aSPiotr Padlewski }
706610c966aSPiotr Padlewski 
707e5780776SKuter Dinel const Value *Value::stripAndAccumulateConstantOffsets(
708e5780776SKuter Dinel     const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
709*75384ecdSNikita Popov     bool AllowInvariantGroup,
710e5780776SKuter Dinel     function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
7113ed286a3SJohannes Doerfert   if (!getType()->isPtrOrPtrVectorTy())
712989e6308SChandler Carruth     return this;
713989e6308SChandler Carruth 
7143ed286a3SJohannes Doerfert   unsigned BitWidth = Offset.getBitWidth();
7153ed286a3SJohannes Doerfert   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
716945b7e5aSElena Demikhovsky          "The offset bit width does not match the DL specification.");
717989e6308SChandler Carruth 
718989e6308SChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
719989e6308SChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
7201dd20e65SCraig Topper   SmallPtrSet<const Value *, 4> Visited;
721989e6308SChandler Carruth   Visited.insert(this);
7221dd20e65SCraig Topper   const Value *V = this;
723989e6308SChandler Carruth   do {
7241dd20e65SCraig Topper     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7253ed286a3SJohannes Doerfert       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
7263ed286a3SJohannes Doerfert       if (!AllowNonInbounds && !GEP->isInBounds())
727989e6308SChandler Carruth         return V;
7283ed286a3SJohannes Doerfert 
7293ed286a3SJohannes Doerfert       // If one of the values we have visited is an addrspacecast, then
7303ed286a3SJohannes Doerfert       // the pointer type of this GEP may be different from the type
7313ed286a3SJohannes Doerfert       // of the Ptr parameter which was passed to this function.  This
7323ed286a3SJohannes Doerfert       // means when we construct GEPOffset, we need to use the size
7333ed286a3SJohannes Doerfert       // of GEP's pointer type rather than the size of the original
7343ed286a3SJohannes Doerfert       // pointer type.
7353ed286a3SJohannes Doerfert       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
736e5780776SKuter Dinel       if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
737989e6308SChandler Carruth         return V;
7383ed286a3SJohannes Doerfert 
7393ed286a3SJohannes Doerfert       // Stop traversal if the pointer offset wouldn't fit in the bit-width
7403ed286a3SJohannes Doerfert       // provided by the Offset argument. This can happen due to AddrSpaceCast
7413ed286a3SJohannes Doerfert       // stripping.
7423ed286a3SJohannes Doerfert       if (GEPOffset.getMinSignedBits() > BitWidth)
7433ed286a3SJohannes Doerfert         return V;
7443ed286a3SJohannes Doerfert 
745e5780776SKuter Dinel       // External Analysis can return a result higher/lower than the value
746e5780776SKuter Dinel       // represents. We need to detect overflow/underflow.
747e5780776SKuter Dinel       APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
748e5780776SKuter Dinel       if (!ExternalAnalysis) {
749e5780776SKuter Dinel         Offset += GEPOffsetST;
750e5780776SKuter Dinel       } else {
751e5780776SKuter Dinel         bool Overflow = false;
752e5780776SKuter Dinel         APInt OldOffset = Offset;
753e5780776SKuter Dinel         Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
754e5780776SKuter Dinel         if (Overflow) {
755e5780776SKuter Dinel           Offset = OldOffset;
756e5780776SKuter Dinel           return V;
757e5780776SKuter Dinel         }
758e5780776SKuter Dinel       }
759989e6308SChandler Carruth       V = GEP->getPointerOperand();
7603ed286a3SJohannes Doerfert     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7613ed286a3SJohannes Doerfert                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
762989e6308SChandler Carruth       V = cast<Operator>(V)->getOperand(0);
7631dd20e65SCraig Topper     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7643ed286a3SJohannes Doerfert       if (!GA->isInterposable())
765989e6308SChandler Carruth         V = GA->getAliasee();
7663ed286a3SJohannes Doerfert     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
7673ed286a3SJohannes Doerfert         if (const Value *RV = Call->getReturnedArgOperand())
7685c12d8feSHal Finkel           V = RV;
769*75384ecdSNikita Popov         if (AllowInvariantGroup && Call->isLaunderOrStripInvariantGroup())
770*75384ecdSNikita Popov           V = Call->getArgOperand(0);
7715c12d8feSHal Finkel     }
7723ed286a3SJohannes Doerfert     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
77370573dcdSDavid Blaikie   } while (Visited.insert(V).second);
774989e6308SChandler Carruth 
775989e6308SChandler Carruth   return V;
776989e6308SChandler Carruth }
777989e6308SChandler Carruth 
778b7338fb1STyker const Value *
779b7338fb1STyker Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
780b7338fb1STyker   return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
781ef860a24SChandler Carruth }
782ef860a24SChandler Carruth 
783e2c6621eSPhilip Reames bool Value::canBeFreed() const {
784e2c6621eSPhilip Reames   assert(getType()->isPointerTy());
7854054b832SPhilip Reames 
7864054b832SPhilip Reames   // Cases that can simply never be deallocated
7874054b832SPhilip Reames   // *) Constants aren't allocated per se, thus not deallocated either.
788e2c6621eSPhilip Reames   if (isa<Constant>(this))
7894054b832SPhilip Reames     return false;
7904054b832SPhilip Reames 
791e7ebb872SPhilip Reames   // Handle byval/byref/sret/inalloca/preallocated arguments.  The storage
792e7ebb872SPhilip Reames   // lifetime is guaranteed to be longer than the callee's lifetime.
793ff55d01aSPhilip Reames   if (auto *A = dyn_cast<Argument>(this)) {
794e7ebb872SPhilip Reames     if (A->hasPointeeInMemoryValueAttr())
795e7ebb872SPhilip Reames       return false;
796ff55d01aSPhilip Reames     // A pointer to an object in a function which neither frees, nor can arrange
797ff55d01aSPhilip Reames     // for another thread to free on its behalf, can not be freed in the scope
798ff55d01aSPhilip Reames     // of the function.  Note that this logic is restricted to memory
799ff55d01aSPhilip Reames     // allocations in existance before the call; a nofree function *is* allowed
800ff55d01aSPhilip Reames     // to free memory it allocated.
801ff55d01aSPhilip Reames     const Function *F = A->getParent();
802ff55d01aSPhilip Reames     if (F->doesNotFreeMemory() && F->hasNoSync())
803ff55d01aSPhilip Reames       return false;
804ff55d01aSPhilip Reames   }
805e7ebb872SPhilip Reames 
8064054b832SPhilip Reames   const Function *F = nullptr;
807e2c6621eSPhilip Reames   if (auto *I = dyn_cast<Instruction>(this))
8084054b832SPhilip Reames     F = I->getFunction();
809e2c6621eSPhilip Reames   if (auto *A = dyn_cast<Argument>(this))
8104054b832SPhilip Reames     F = A->getParent();
8114054b832SPhilip Reames 
8124054b832SPhilip Reames   if (!F)
8134054b832SPhilip Reames     return true;
8144054b832SPhilip Reames 
8154054b832SPhilip Reames   // With garbage collection, deallocation typically occurs solely at or after
8164054b832SPhilip Reames   // safepoints.  If we're compiling for a collector which uses the
8174054b832SPhilip Reames   // gc.statepoint infrastructure, safepoints aren't explicitly present
8184054b832SPhilip Reames   // in the IR until after lowering from abstract to physical machine model.
8194054b832SPhilip Reames   // The collector could chose to mix explicit deallocation and gc'd objects
8204054b832SPhilip Reames   // which is why we need the explicit opt in on a per collector basis.
8214054b832SPhilip Reames   if (!F->hasGC())
8224054b832SPhilip Reames     return true;
8234054b832SPhilip Reames 
8244054b832SPhilip Reames   const auto &GCName = F->getGC();
8259430efa1SMax Kazantsev   if (GCName == "statepoint-example") {
826e2c6621eSPhilip Reames     auto *PT = cast<PointerType>(this->getType());
8274054b832SPhilip Reames     if (PT->getAddressSpace() != 1)
8289430efa1SMax Kazantsev       // For the sake of this example GC, we arbitrarily pick addrspace(1) as
8299430efa1SMax Kazantsev       // our GC managed heap.  This must match the same check in
8304054b832SPhilip Reames       // RewriteStatepointsForGC (and probably needs better factored.)
8314054b832SPhilip Reames       return true;
8324054b832SPhilip Reames 
8334054b832SPhilip Reames     // It is cheaper to scan for a declaration than to scan for a use in this
8344054b832SPhilip Reames     // function.  Note that gc.statepoint is a type overloaded function so the
8354054b832SPhilip Reames     // usual trick of requesting declaration of the intrinsic from the module
8364054b832SPhilip Reames     // doesn't work.
8374054b832SPhilip Reames     for (auto &Fn : *F->getParent())
8384054b832SPhilip Reames       if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
8394054b832SPhilip Reames         return true;
8404054b832SPhilip Reames     return false;
8414054b832SPhilip Reames   }
8429430efa1SMax Kazantsev   return true;
8439430efa1SMax Kazantsev }
8444054b832SPhilip Reames 
8453603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
8465698537fSPhilip Reames                                                bool &CanBeNull,
8475698537fSPhilip Reames                                                bool &CanBeFreed) const {
848345f0148SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
849345f0148SArtur Pilipenko 
8503603de2fSBjorn Steinbrink   uint64_t DerefBytes = 0;
851345f0148SArtur Pilipenko   CanBeNull = false;
852e2c6621eSPhilip Reames   CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
853345f0148SArtur Pilipenko   if (const Argument *A = dyn_cast<Argument>(this)) {
854345f0148SArtur Pilipenko     DerefBytes = A->getDereferenceableBytes();
855dc08185cSMatt Arsenault     if (DerefBytes == 0) {
856dc08185cSMatt Arsenault       // Handle byval/byref/inalloca/preallocated arguments
857dc08185cSMatt Arsenault       if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
858dc08185cSMatt Arsenault         if (ArgMemTy->isSized()) {
859dc08185cSMatt Arsenault           // FIXME: Why isn't this the type alloc size?
860dc08185cSMatt Arsenault           DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinSize();
86100953cbeSSanjoy Das         }
862dc08185cSMatt Arsenault       }
863dc08185cSMatt Arsenault     }
864dc08185cSMatt Arsenault 
865345f0148SArtur Pilipenko     if (DerefBytes == 0) {
866345f0148SArtur Pilipenko       DerefBytes = A->getDereferenceableOrNullBytes();
867345f0148SArtur Pilipenko       CanBeNull = true;
868345f0148SArtur Pilipenko     }
86990c09232SChandler Carruth   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
87044a3241fSArthur Eubanks     DerefBytes = Call->getRetDereferenceableBytes();
871345f0148SArtur Pilipenko     if (DerefBytes == 0) {
87244a3241fSArthur Eubanks       DerefBytes = Call->getRetDereferenceableOrNullBytes();
873345f0148SArtur Pilipenko       CanBeNull = true;
874345f0148SArtur Pilipenko     }
875345f0148SArtur Pilipenko   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
876345f0148SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
877345f0148SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
878345f0148SArtur Pilipenko       DerefBytes = CI->getLimitedValue();
879345f0148SArtur Pilipenko     }
880345f0148SArtur Pilipenko     if (DerefBytes == 0) {
881345f0148SArtur Pilipenko       if (MDNode *MD =
882345f0148SArtur Pilipenko               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
883345f0148SArtur Pilipenko         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
884345f0148SArtur Pilipenko         DerefBytes = CI->getLimitedValue();
885345f0148SArtur Pilipenko       }
886345f0148SArtur Pilipenko       CanBeNull = true;
887345f0148SArtur Pilipenko     }
8886f13637aSRyan Taylor   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
8896f13637aSRyan Taylor     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
8906f13637aSRyan Taylor       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8916f13637aSRyan Taylor       DerefBytes = CI->getLimitedValue();
8926f13637aSRyan Taylor     }
8936f13637aSRyan Taylor     if (DerefBytes == 0) {
8946f13637aSRyan Taylor       if (MDNode *MD =
8956f13637aSRyan Taylor               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
8966f13637aSRyan Taylor         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
8976f13637aSRyan Taylor         DerefBytes = CI->getLimitedValue();
8986f13637aSRyan Taylor       }
8996f13637aSRyan Taylor       CanBeNull = true;
9006f13637aSRyan Taylor     }
90100953cbeSSanjoy Das   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
902030123e8SBjorn Steinbrink     if (!AI->isArrayAllocation()) {
903ebec984eSEli Friedman       DerefBytes =
904ebec984eSEli Friedman           DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
90500953cbeSSanjoy Das       CanBeNull = false;
9065698537fSPhilip Reames       CanBeFreed = false;
90700953cbeSSanjoy Das     }
90800953cbeSSanjoy Das   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
90900953cbeSSanjoy Das     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
91000953cbeSSanjoy Das       // TODO: Don't outright reject hasExternalWeakLinkage but set the
91100953cbeSSanjoy Das       // CanBeNull flag.
912ebec984eSEli Friedman       DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
91300953cbeSSanjoy Das       CanBeNull = false;
914b86ddfdbSPhilip Reames       CanBeFreed = false;
91500953cbeSSanjoy Das     }
916345f0148SArtur Pilipenko   }
917345f0148SArtur Pilipenko   return DerefBytes;
918345f0148SArtur Pilipenko }
919345f0148SArtur Pilipenko 
920f26bdb53SEli Friedman Align Value::getPointerAlignment(const DataLayout &DL) const {
921ae51afc5SArtur Pilipenko   assert(getType()->isPointerTy() && "must be pointer");
922ae51afc5SArtur Pilipenko   if (auto *GO = dyn_cast<GlobalObject>(this)) {
923308e82ecSMichael Platings     if (isa<Function>(GO)) {
924f26bdb53SEli Friedman       Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
925308e82ecSMichael Platings       switch (DL.getFunctionPtrAlignType()) {
926308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::Independent:
927bae629b9SGuillaume Chatelet         return FunctionPtrAlign;
928308e82ecSMichael Platings       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
929f26bdb53SEli Friedman         return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
930308e82ecSMichael Platings       }
9316200a568SGuillaume Chatelet       llvm_unreachable("Unhandled FunctionPtrAlignType");
932308e82ecSMichael Platings     }
933bae629b9SGuillaume Chatelet     const MaybeAlign Alignment(GO->getAlignment());
934bae629b9SGuillaume Chatelet     if (!Alignment) {
935ae51afc5SArtur Pilipenko       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
936ae51afc5SArtur Pilipenko         Type *ObjectType = GVar->getValueType();
937ae51afc5SArtur Pilipenko         if (ObjectType->isSized()) {
938ae51afc5SArtur Pilipenko           // If the object is defined in the current Module, we'll be giving
939ae51afc5SArtur Pilipenko           // it the preferred alignment. Otherwise, we have to assume that it
940ae51afc5SArtur Pilipenko           // may only have the minimum ABI alignment.
941ae51afc5SArtur Pilipenko           if (GVar->isStrongDefinitionForLinker())
942368a5e3aSGuillaume Chatelet             return DL.getPreferredAlign(GVar);
943ae51afc5SArtur Pilipenko           else
9449068bccbSGuillaume Chatelet             return DL.getABITypeAlign(ObjectType);
945ae51afc5SArtur Pilipenko         }
946ae51afc5SArtur Pilipenko       }
947ae51afc5SArtur Pilipenko     }
948f26bdb53SEli Friedman     return Alignment.valueOrOne();
949ae51afc5SArtur Pilipenko   } else if (const Argument *A = dyn_cast<Argument>(this)) {
9509068bccbSGuillaume Chatelet     const MaybeAlign Alignment = A->getParamAlign();
951bae629b9SGuillaume Chatelet     if (!Alignment && A->hasStructRetAttr()) {
952ae51afc5SArtur Pilipenko       // An sret parameter has at least the ABI alignment of the return type.
953d65a7003SMatt Arsenault       Type *EltTy = A->getParamStructRetType();
954ae51afc5SArtur Pilipenko       if (EltTy->isSized())
9559068bccbSGuillaume Chatelet         return DL.getABITypeAlign(EltTy);
956ae51afc5SArtur Pilipenko     }
957f26bdb53SEli Friedman     return Alignment.valueOrOne();
958c97eac65SArtur Pilipenko   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
959f26bdb53SEli Friedman     return AI->getAlign();
960afd4a37bSHideto Ueno   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
961f26bdb53SEli Friedman     MaybeAlign Alignment = Call->getRetAlign();
962bae629b9SGuillaume Chatelet     if (!Alignment && Call->getCalledFunction())
963f26bdb53SEli Friedman       Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
964f26bdb53SEli Friedman     return Alignment.valueOrOne();
9656200a568SGuillaume Chatelet   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
966ae51afc5SArtur Pilipenko     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
967ae51afc5SArtur Pilipenko       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
968f26bdb53SEli Friedman       return Align(CI->getLimitedValue());
969ae51afc5SArtur Pilipenko     }
970a6492e22SRoman Lebedev   } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
971a6492e22SRoman Lebedev     if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
972a6492e22SRoman Lebedev             const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
973a6492e22SRoman Lebedev             /*OnlyIfReduced=*/true))) {
974a6492e22SRoman Lebedev       size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
975a6492e22SRoman Lebedev       // While the actual alignment may be large, elsewhere we have
976a6492e22SRoman Lebedev       // an arbitrary upper alignmet limit, so let's clamp to it.
977a6492e22SRoman Lebedev       return Align(TrailingZeros < Value::MaxAlignmentExponent
978a6492e22SRoman Lebedev                        ? uint64_t(1) << TrailingZeros
979a6492e22SRoman Lebedev                        : Value::MaximumAlignment);
980a6492e22SRoman Lebedev     }
9816200a568SGuillaume Chatelet   }
982f26bdb53SEli Friedman   return Align(1);
983ae51afc5SArtur Pilipenko }
984ae51afc5SArtur Pilipenko 
9851dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
9861dd20e65SCraig Topper                                      const BasicBlock *PredBB) const {
9871dd20e65SCraig Topper   auto *PN = dyn_cast<PHINode>(this);
988ef860a24SChandler Carruth   if (PN && PN->getParent() == CurBB)
989ef860a24SChandler Carruth     return PN->getIncomingValueForBlock(PredBB);
990ef860a24SChandler Carruth   return this;
991ef860a24SChandler Carruth }
992ef860a24SChandler Carruth 
993ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); }
994ef860a24SChandler Carruth 
9953441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() {
9963441ffe9SDuncan P. N. Exon Smith   if (!UseList || !UseList->Next)
9973441ffe9SDuncan P. N. Exon Smith     // No need to reverse 0 or 1 uses.
9983441ffe9SDuncan P. N. Exon Smith     return;
9993441ffe9SDuncan P. N. Exon Smith 
10003441ffe9SDuncan P. N. Exon Smith   Use *Head = UseList;
10013441ffe9SDuncan P. N. Exon Smith   Use *Current = UseList->Next;
10023441ffe9SDuncan P. N. Exon Smith   Head->Next = nullptr;
10033441ffe9SDuncan P. N. Exon Smith   while (Current) {
10043441ffe9SDuncan P. N. Exon Smith     Use *Next = Current->Next;
10053441ffe9SDuncan P. N. Exon Smith     Current->Next = Head;
100691ef7cb5SJay Foad     Head->Prev = &Current->Next;
10073441ffe9SDuncan P. N. Exon Smith     Head = Current;
10083441ffe9SDuncan P. N. Exon Smith     Current = Next;
10093441ffe9SDuncan P. N. Exon Smith   }
10103441ffe9SDuncan P. N. Exon Smith   UseList = Head;
101191ef7cb5SJay Foad   Head->Prev = &UseList;
10123441ffe9SDuncan P. N. Exon Smith }
10133441ffe9SDuncan P. N. Exon Smith 
1014ad830022SArnold Schwaighofer bool Value::isSwiftError() const {
1015ad830022SArnold Schwaighofer   auto *Arg = dyn_cast<Argument>(this);
1016ad830022SArnold Schwaighofer   if (Arg)
1017ad830022SArnold Schwaighofer     return Arg->hasSwiftErrorAttr();
1018ad830022SArnold Schwaighofer   auto *Alloca = dyn_cast<AllocaInst>(this);
1019ad830022SArnold Schwaighofer   if (!Alloca)
1020ad830022SArnold Schwaighofer     return false;
1021ad830022SArnold Schwaighofer   return Alloca->isSwiftError();
1022ad830022SArnold Schwaighofer }
1023ad830022SArnold Schwaighofer 
1024cab48e2fSZequan Wu bool Value::isTransitiveUsedByMetadataOnly() const {
1025cab48e2fSZequan Wu   if (use_empty())
1026cab48e2fSZequan Wu     return false;
1027cab48e2fSZequan Wu   llvm::SmallVector<const User *, 32> WorkList;
1028cab48e2fSZequan Wu   llvm::SmallPtrSet<const User *, 32> Visited;
1029cab48e2fSZequan Wu   WorkList.insert(WorkList.begin(), user_begin(), user_end());
1030cab48e2fSZequan Wu   while (!WorkList.empty()) {
103184b07c9bSKazu Hirata     const User *U = WorkList.pop_back_val();
1032cab48e2fSZequan Wu     Visited.insert(U);
1033cab48e2fSZequan Wu     // If it is transitively used by a global value or a non-constant value,
1034cab48e2fSZequan Wu     // it's obviously not only used by metadata.
1035cab48e2fSZequan Wu     if (!isa<Constant>(U) || isa<GlobalValue>(U))
1036cab48e2fSZequan Wu       return false;
1037cab48e2fSZequan Wu     for (const User *UU : U->users())
1038cab48e2fSZequan Wu       if (!Visited.count(UU))
1039cab48e2fSZequan Wu         WorkList.push_back(UU);
1040cab48e2fSZequan Wu   }
1041cab48e2fSZequan Wu   return true;
1042cab48e2fSZequan Wu }
1043cab48e2fSZequan Wu 
1044ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1045ef860a24SChandler Carruth //                             ValueHandleBase Class
1046ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
1047ef860a24SChandler Carruth 
1048ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
1049ef860a24SChandler Carruth   assert(List && "Handle list is null?");
1050ef860a24SChandler Carruth 
1051ef860a24SChandler Carruth   // Splice ourselves into the list.
1052ef860a24SChandler Carruth   Next = *List;
1053ef860a24SChandler Carruth   *List = this;
1054ef860a24SChandler Carruth   setPrevPtr(List);
1055ef860a24SChandler Carruth   if (Next) {
1056ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
10576f08789dSSanjoy Das     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
1058ef860a24SChandler Carruth   }
1059ef860a24SChandler Carruth }
1060ef860a24SChandler Carruth 
1061ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
1062ef860a24SChandler Carruth   assert(List && "Must insert after existing node");
1063ef860a24SChandler Carruth 
1064ef860a24SChandler Carruth   Next = List->Next;
1065ef860a24SChandler Carruth   setPrevPtr(&List->Next);
1066ef860a24SChandler Carruth   List->Next = this;
1067ef860a24SChandler Carruth   if (Next)
1068ef860a24SChandler Carruth     Next->setPrevPtr(&Next);
1069ef860a24SChandler Carruth }
1070ef860a24SChandler Carruth 
1071ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() {
10726f08789dSSanjoy Das   assert(getValPtr() && "Null pointer doesn't have a use list!");
1073ef860a24SChandler Carruth 
10746f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1075ef860a24SChandler Carruth 
10766f08789dSSanjoy Das   if (getValPtr()->HasValueHandle) {
1077ef860a24SChandler Carruth     // If this value already has a ValueHandle, then it must be in the
1078ef860a24SChandler Carruth     // ValueHandles map already.
10796f08789dSSanjoy Das     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
10802617dcceSCraig Topper     assert(Entry && "Value doesn't have any handles?");
1081ef860a24SChandler Carruth     AddToExistingUseList(&Entry);
1082ef860a24SChandler Carruth     return;
1083ef860a24SChandler Carruth   }
1084ef860a24SChandler Carruth 
1085ef860a24SChandler Carruth   // Ok, it doesn't have any handles yet, so we must insert it into the
1086ef860a24SChandler Carruth   // DenseMap.  However, doing this insertion could cause the DenseMap to
1087ef860a24SChandler Carruth   // reallocate itself, which would invalidate all of the PrevP pointers that
1088ef860a24SChandler Carruth   // point into the old table.  Handle this by checking for reallocation and
1089ef860a24SChandler Carruth   // updating the stale pointers only if needed.
1090ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1091ef860a24SChandler Carruth   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
1092ef860a24SChandler Carruth 
10936f08789dSSanjoy Das   ValueHandleBase *&Entry = Handles[getValPtr()];
10942617dcceSCraig Topper   assert(!Entry && "Value really did already have handles?");
1095ef860a24SChandler Carruth   AddToExistingUseList(&Entry);
10966f08789dSSanjoy Das   getValPtr()->HasValueHandle = true;
1097ef860a24SChandler Carruth 
1098ef860a24SChandler Carruth   // If reallocation didn't happen or if this was the first insertion, don't
1099ef860a24SChandler Carruth   // walk the table.
1100ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
1101ef860a24SChandler Carruth       Handles.size() == 1) {
1102ef860a24SChandler Carruth     return;
1103ef860a24SChandler Carruth   }
1104ef860a24SChandler Carruth 
1105ef860a24SChandler Carruth   // Okay, reallocation did happen.  Fix the Prev Pointers.
1106ef860a24SChandler Carruth   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
1107ef860a24SChandler Carruth        E = Handles.end(); I != E; ++I) {
11086f08789dSSanjoy Das     assert(I->second && I->first == I->second->getValPtr() &&
1109ef860a24SChandler Carruth            "List invariant broken!");
1110ef860a24SChandler Carruth     I->second->setPrevPtr(&I->second);
1111ef860a24SChandler Carruth   }
1112ef860a24SChandler Carruth }
1113ef860a24SChandler Carruth 
1114ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() {
11156f08789dSSanjoy Das   assert(getValPtr() && getValPtr()->HasValueHandle &&
1116ef860a24SChandler Carruth          "Pointer doesn't have a use list!");
1117ef860a24SChandler Carruth 
1118ef860a24SChandler Carruth   // Unlink this from its use list.
1119ef860a24SChandler Carruth   ValueHandleBase **PrevPtr = getPrevPtr();
1120ef860a24SChandler Carruth   assert(*PrevPtr == this && "List invariant broken");
1121ef860a24SChandler Carruth 
1122ef860a24SChandler Carruth   *PrevPtr = Next;
1123ef860a24SChandler Carruth   if (Next) {
1124ef860a24SChandler Carruth     assert(Next->getPrevPtr() == &Next && "List invariant broken");
1125ef860a24SChandler Carruth     Next->setPrevPtr(PrevPtr);
1126ef860a24SChandler Carruth     return;
1127ef860a24SChandler Carruth   }
1128ef860a24SChandler Carruth 
1129ef860a24SChandler Carruth   // If the Next pointer was null, then it is possible that this was the last
1130ef860a24SChandler Carruth   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
1131ef860a24SChandler Carruth   // map.
11326f08789dSSanjoy Das   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1133ef860a24SChandler Carruth   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1134ef860a24SChandler Carruth   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
11356f08789dSSanjoy Das     Handles.erase(getValPtr());
11366f08789dSSanjoy Das     getValPtr()->HasValueHandle = false;
1137ef860a24SChandler Carruth   }
1138ef860a24SChandler Carruth }
1139ef860a24SChandler Carruth 
1140ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) {
1141ef860a24SChandler Carruth   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
1142ef860a24SChandler Carruth 
1143ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
1144ef860a24SChandler Carruth   // HasValueHandle flag is set.
1145ef860a24SChandler Carruth   LLVMContextImpl *pImpl = V->getContext().pImpl;
1146ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[V];
1147ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
1148ef860a24SChandler Carruth 
1149ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
1150ef860a24SChandler Carruth   // and remove themselves from the list without breaking our iteration.  This
1151ef860a24SChandler Carruth   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
1152ef860a24SChandler Carruth   // Note that we deliberately do not the support the case when dropping a value
1153ef860a24SChandler Carruth   // handle results in a new value handle being permanently added to the list
1154ef860a24SChandler Carruth   // (as might occur in theory for CallbackVH's): the new value handle will not
1155ef860a24SChandler Carruth   // be processed and the checking code will mete out righteous punishment if
1156ef860a24SChandler Carruth   // the handle is still present once we have finished processing all the other
1157ef860a24SChandler Carruth   // value handles (it is fine to momentarily add then remove a value handle).
1158ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1159ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
1160ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
1161ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1162ef860a24SChandler Carruth 
1163ef860a24SChandler Carruth     switch (Entry->getKind()) {
1164ef860a24SChandler Carruth     case Assert:
1165ef860a24SChandler Carruth       break;
1166f1c0eafdSSanjoy Das     case Weak:
1167e6bca0eeSSanjoy Das     case WeakTracking:
1168f1c0eafdSSanjoy Das       // WeakTracking and Weak just go to null, which unlinks them
1169f1c0eafdSSanjoy Das       // from the list.
1170c620761cSCraig Topper       Entry->operator=(nullptr);
1171ef860a24SChandler Carruth       break;
1172ef860a24SChandler Carruth     case Callback:
1173ef860a24SChandler Carruth       // Forward to the subclass's implementation.
1174ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->deleted();
1175ef860a24SChandler Carruth       break;
1176ef860a24SChandler Carruth     }
1177ef860a24SChandler Carruth   }
1178ef860a24SChandler Carruth 
1179ef860a24SChandler Carruth   // All callbacks, weak references, and assertingVHs should be dropped by now.
1180ef860a24SChandler Carruth   if (V->HasValueHandle) {
1181ef860a24SChandler Carruth #ifndef NDEBUG      // Only in +Asserts mode...
1182ef860a24SChandler Carruth     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1183ef860a24SChandler Carruth            << "\n";
1184ef860a24SChandler Carruth     if (pImpl->ValueHandles[V]->getKind() == Assert)
1185ef860a24SChandler Carruth       llvm_unreachable("An asserting value handle still pointed to this"
1186ef860a24SChandler Carruth                        " value!");
1187ef860a24SChandler Carruth 
1188ef860a24SChandler Carruth #endif
1189ef860a24SChandler Carruth     llvm_unreachable("All references to V were not removed?");
1190ef860a24SChandler Carruth   }
1191ef860a24SChandler Carruth }
1192ef860a24SChandler Carruth 
1193ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1194ef860a24SChandler Carruth   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1195ef860a24SChandler Carruth   assert(Old != New && "Changing value into itself!");
1196c1892e2dSFrederic Riss   assert(Old->getType() == New->getType() &&
1197c1892e2dSFrederic Riss          "replaceAllUses of value with new value of different type!");
1198ef860a24SChandler Carruth 
1199ef860a24SChandler Carruth   // Get the linked list base, which is guaranteed to exist since the
1200ef860a24SChandler Carruth   // HasValueHandle flag is set.
1201ef860a24SChandler Carruth   LLVMContextImpl *pImpl = Old->getContext().pImpl;
1202ef860a24SChandler Carruth   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1203ef860a24SChandler Carruth 
1204ef860a24SChandler Carruth   assert(Entry && "Value bit set but no entries exist");
1205ef860a24SChandler Carruth 
1206ef860a24SChandler Carruth   // We use a local ValueHandleBase as an iterator so that
1207ef860a24SChandler Carruth   // ValueHandles can add and remove themselves from the list without
1208ef860a24SChandler Carruth   // breaking our iteration.  This is not really an AssertingVH; we
1209ef860a24SChandler Carruth   // just have to give ValueHandleBase some kind.
1210ef860a24SChandler Carruth   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1211ef860a24SChandler Carruth     Iterator.RemoveFromUseList();
1212ef860a24SChandler Carruth     Iterator.AddToExistingUseListAfter(Entry);
1213ef860a24SChandler Carruth     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1214ef860a24SChandler Carruth 
1215ef860a24SChandler Carruth     switch (Entry->getKind()) {
1216ef860a24SChandler Carruth     case Assert:
1217f1c0eafdSSanjoy Das     case Weak:
1218f1c0eafdSSanjoy Das       // Asserting and Weak handles do not follow RAUW implicitly.
1219ef860a24SChandler Carruth       break;
1220e6bca0eeSSanjoy Das     case WeakTracking:
12212cbeb00fSSanjoy Das       // Weak goes to the new value, which will unlink it from Old's list.
1222ef860a24SChandler Carruth       Entry->operator=(New);
1223ef860a24SChandler Carruth       break;
1224ef860a24SChandler Carruth     case Callback:
1225ef860a24SChandler Carruth       // Forward to the subclass's implementation.
1226ef860a24SChandler Carruth       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1227ef860a24SChandler Carruth       break;
1228ef860a24SChandler Carruth     }
1229ef860a24SChandler Carruth   }
1230ef860a24SChandler Carruth 
1231ef860a24SChandler Carruth #ifndef NDEBUG
12328a623820SSanjoy Das   // If any new weak value handles were added while processing the
1233ef860a24SChandler Carruth   // list, then complain about it now.
1234ef860a24SChandler Carruth   if (Old->HasValueHandle)
1235ef860a24SChandler Carruth     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1236ef860a24SChandler Carruth       switch (Entry->getKind()) {
1237e6bca0eeSSanjoy Das       case WeakTracking:
1238ef860a24SChandler Carruth         dbgs() << "After RAUW from " << *Old->getType() << " %"
1239ef860a24SChandler Carruth                << Old->getName() << " to " << *New->getType() << " %"
1240ef860a24SChandler Carruth                << New->getName() << "\n";
12418a623820SSanjoy Das         llvm_unreachable(
1242e6bca0eeSSanjoy Das             "A weak tracking value handle still pointed to the old value!\n");
1243ef860a24SChandler Carruth       default:
1244ef860a24SChandler Carruth         break;
1245ef860a24SChandler Carruth       }
1246ef860a24SChandler Carruth #endif
1247ef860a24SChandler Carruth }
1248ef860a24SChandler Carruth 
1249d12ccbd3SJuergen Ributzka // Pin the vtable to this file.
1250d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {}
1251