1ef860a24SChandler Carruth //===-- Value.cpp - Implement the Value class -----------------------------===// 2ef860a24SChandler Carruth // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6ef860a24SChandler Carruth // 7ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 8ef860a24SChandler Carruth // 9ef860a24SChandler Carruth // This file implements the Value, ValueHandle, and User classes. 10ef860a24SChandler Carruth // 11ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 12ef860a24SChandler Carruth 139fb823bbSChandler Carruth #include "llvm/IR/Value.h" 14ef860a24SChandler Carruth #include "LLVMContextImpl.h" 15ef860a24SChandler Carruth #include "llvm/ADT/DenseMap.h" 162f2ace98SDmitry Mikulin #include "llvm/ADT/SetVector.h" 174c1a1d3cSReid Kleckner #include "llvm/ADT/SmallString.h" 189fb823bbSChandler Carruth #include "llvm/IR/Constant.h" 199fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 202e42c34dSHal Finkel #include "llvm/IR/DataLayout.h" 219fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h" 2296ab8726SReid Kleckner #include "llvm/IR/DerivedUser.h" 2303eb0de9SChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h" 249fb823bbSChandler Carruth #include "llvm/IR/InstrTypes.h" 259fb823bbSChandler Carruth #include "llvm/IR/Instructions.h" 26a7343d65SRamkumar Ramachandra #include "llvm/IR/IntrinsicInst.h" 279fb823bbSChandler Carruth #include "llvm/IR/Module.h" 289fb823bbSChandler Carruth #include "llvm/IR/Operator.h" 29a7343d65SRamkumar Ramachandra #include "llvm/IR/Statepoint.h" 304220e9c1SChandler Carruth #include "llvm/IR/ValueHandle.h" 319fb823bbSChandler Carruth #include "llvm/IR/ValueSymbolTable.h" 324c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h" 33ef860a24SChandler Carruth #include "llvm/Support/Debug.h" 34ef860a24SChandler Carruth #include "llvm/Support/ErrorHandling.h" 35ef860a24SChandler Carruth #include "llvm/Support/ManagedStatic.h" 36799003bfSBenjamin Kramer #include "llvm/Support/raw_ostream.h" 37ef860a24SChandler Carruth #include <algorithm> 38ecefe5a8SEugene Zelenko 39ef860a24SChandler Carruth using namespace llvm; 40ef860a24SChandler Carruth 414c975578SSerge Guelton static cl::opt<unsigned> NonGlobalValueMaxNameSize( 424c975578SSerge Guelton "non-global-value-max-name-size", cl::Hidden, cl::init(1024), 434c975578SSerge Guelton cl::desc("Maximum size for the name of non-global values.")); 444c975578SSerge Guelton 45ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 46ef860a24SChandler Carruth // Value Class 47ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 48ef860a24SChandler Carruth static inline Type *checkType(Type *Ty) { 49ef860a24SChandler Carruth assert(Ty && "Value defined with a null type: Error!"); 5016bf89ecSReid Kleckner return Ty; 51ef860a24SChandler Carruth } 52ef860a24SChandler Carruth 53ef860a24SChandler Carruth Value::Value(Type *ty, unsigned scid) 547349ab93SOwen Anderson : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), 557349ab93SOwen Anderson HasValueHandle(0), SubclassOptionalData(0), SubclassData(0), 56b4eede2cSPete Cooper NumUserOperands(0), IsUsedByMD(false), HasName(false) { 579fd33f24SSerge Guelton static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)"); 58ef860a24SChandler Carruth // FIXME: Why isn't this in the subclass gunk?? 59ef860a24SChandler Carruth // Note, we cannot call isa<CallInst> before the CallInst has been 60ef860a24SChandler Carruth // constructed. 61784929d0SCraig Topper if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke || 62784929d0SCraig Topper SubclassID == Instruction::CallBr) 63ef860a24SChandler Carruth assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) && 64ef860a24SChandler Carruth "invalid CallInst type!"); 65ef860a24SChandler Carruth else if (SubclassID != BasicBlockVal && 669fd33f24SSerge Guelton (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal)) 67ef860a24SChandler Carruth assert((VTy->isFirstClassType() || VTy->isVoidTy()) && 68ef860a24SChandler Carruth "Cannot create non-first-class values except for constants!"); 6996ab8726SReid Kleckner static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned), 701762ad3eSReid Kleckner "Value too big"); 71ef860a24SChandler Carruth } 72ef860a24SChandler Carruth 73ef860a24SChandler Carruth Value::~Value() { 74ef860a24SChandler Carruth // Notify all ValueHandles (if present) that this value is going away. 75ef860a24SChandler Carruth if (HasValueHandle) 76ef860a24SChandler Carruth ValueHandleBase::ValueIsDeleted(this); 775bf8fef5SDuncan P. N. Exon Smith if (isUsedByMetadata()) 785bf8fef5SDuncan P. N. Exon Smith ValueAsMetadata::handleDeletion(this); 79ef860a24SChandler Carruth 80ef860a24SChandler Carruth #ifndef NDEBUG // Only in -g mode... 81ef860a24SChandler Carruth // Check to make sure that there are no uses of this value that are still 82ef860a24SChandler Carruth // around when the value is destroyed. If there are, then we have a dangling 83b93fb82bSAndrew Kaylor // reference and something is wrong. This code is here to print out where 84b93fb82bSAndrew Kaylor // the value is still being referenced. 85ef860a24SChandler Carruth // 86*7dd28109SEvgenii Stepanov // Note that use_empty() cannot be called here, as it eventually downcasts 87*7dd28109SEvgenii Stepanov // 'this' to GlobalValue (derived class of Value), but GlobalValue has already 88*7dd28109SEvgenii Stepanov // been destructed, so accessing it is UB. 89*7dd28109SEvgenii Stepanov // 90*7dd28109SEvgenii Stepanov if (!materialized_use_empty()) { 91ef860a24SChandler Carruth dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n"; 92b93fb82bSAndrew Kaylor for (auto *U : users()) 93b93fb82bSAndrew Kaylor dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n"; 94ef860a24SChandler Carruth } 95ef860a24SChandler Carruth #endif 96*7dd28109SEvgenii Stepanov assert(materialized_use_empty() && "Uses remain when a value is destroyed!"); 97ef860a24SChandler Carruth 98ef860a24SChandler Carruth // If this value is named, destroy the name. This should not be in a symtab 99ef860a24SChandler Carruth // at this point. 1005bf8fef5SDuncan P. N. Exon Smith destroyValueName(); 101ef860a24SChandler Carruth } 102ef860a24SChandler Carruth 10396ab8726SReid Kleckner void Value::deleteValue() { 10496ab8726SReid Kleckner switch (getValueID()) { 10596ab8726SReid Kleckner #define HANDLE_VALUE(Name) \ 10696ab8726SReid Kleckner case Value::Name##Val: \ 10796ab8726SReid Kleckner delete static_cast<Name *>(this); \ 10896ab8726SReid Kleckner break; 10996ab8726SReid Kleckner #define HANDLE_MEMORY_VALUE(Name) \ 11096ab8726SReid Kleckner case Value::Name##Val: \ 11196ab8726SReid Kleckner static_cast<DerivedUser *>(this)->DeleteValue( \ 11296ab8726SReid Kleckner static_cast<DerivedUser *>(this)); \ 11396ab8726SReid Kleckner break; 11496ab8726SReid Kleckner #define HANDLE_INSTRUCTION(Name) /* nothing */ 11596ab8726SReid Kleckner #include "llvm/IR/Value.def" 11696ab8726SReid Kleckner 11796ab8726SReid Kleckner #define HANDLE_INST(N, OPC, CLASS) \ 11896ab8726SReid Kleckner case Value::InstructionVal + Instruction::OPC: \ 11996ab8726SReid Kleckner delete static_cast<CLASS *>(this); \ 12096ab8726SReid Kleckner break; 12196ab8726SReid Kleckner #define HANDLE_USER_INST(N, OPC, CLASS) 12296ab8726SReid Kleckner #include "llvm/IR/Instruction.def" 12396ab8726SReid Kleckner 12496ab8726SReid Kleckner default: 12596ab8726SReid Kleckner llvm_unreachable("attempting to delete unknown value kind"); 12696ab8726SReid Kleckner } 12796ab8726SReid Kleckner } 12896ab8726SReid Kleckner 1295bf8fef5SDuncan P. N. Exon Smith void Value::destroyValueName() { 1305bf8fef5SDuncan P. N. Exon Smith ValueName *Name = getValueName(); 1315bf8fef5SDuncan P. N. Exon Smith if (Name) 1325bf8fef5SDuncan P. N. Exon Smith Name->Destroy(); 1335bf8fef5SDuncan P. N. Exon Smith setValueName(nullptr); 1345bf8fef5SDuncan P. N. Exon Smith } 1355bf8fef5SDuncan P. N. Exon Smith 136ef860a24SChandler Carruth bool Value::hasNUses(unsigned N) const { 1374de31bbaSVedant Kumar return hasNItems(use_begin(), use_end(), N); 138ef860a24SChandler Carruth } 139ef860a24SChandler Carruth 140ef860a24SChandler Carruth bool Value::hasNUsesOrMore(unsigned N) const { 1414de31bbaSVedant Kumar return hasNItemsOrMore(use_begin(), use_end(), N); 142ef860a24SChandler Carruth } 143ef860a24SChandler Carruth 144ef860a24SChandler Carruth bool Value::isUsedInBasicBlock(const BasicBlock *BB) const { 1450925b24dSJakob Stoklund Olesen // This can be computed either by scanning the instructions in BB, or by 1460925b24dSJakob Stoklund Olesen // scanning the use list of this Value. Both lists can be very long, but 1470925b24dSJakob Stoklund Olesen // usually one is quite short. 1480925b24dSJakob Stoklund Olesen // 1490925b24dSJakob Stoklund Olesen // Scan both lists simultaneously until one is exhausted. This limits the 1500925b24dSJakob Stoklund Olesen // search to the shorter list. 1510925b24dSJakob Stoklund Olesen BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); 152cdf47884SChandler Carruth const_user_iterator UI = user_begin(), UE = user_end(); 1530925b24dSJakob Stoklund Olesen for (; BI != BE && UI != UE; ++BI, ++UI) { 1540925b24dSJakob Stoklund Olesen // Scan basic block: Check if this Value is used by the instruction at BI. 15542531260SDavid Majnemer if (is_contained(BI->operands(), this)) 156ef860a24SChandler Carruth return true; 1570925b24dSJakob Stoklund Olesen // Scan use list: Check if the use at UI is in BB. 15842531260SDavid Majnemer const auto *User = dyn_cast<Instruction>(*UI); 159ef860a24SChandler Carruth if (User && User->getParent() == BB) 160ef860a24SChandler Carruth return true; 161ef860a24SChandler Carruth } 162ef860a24SChandler Carruth return false; 163ef860a24SChandler Carruth } 164ef860a24SChandler Carruth 1655a0872c2SVedant Kumar unsigned Value::getNumUses() const { 1665a0872c2SVedant Kumar return (unsigned)std::distance(use_begin(), use_end()); 1675a0872c2SVedant Kumar } 168ef860a24SChandler Carruth 169ef860a24SChandler Carruth static bool getSymTab(Value *V, ValueSymbolTable *&ST) { 170c620761cSCraig Topper ST = nullptr; 171ef860a24SChandler Carruth if (Instruction *I = dyn_cast<Instruction>(V)) { 172ef860a24SChandler Carruth if (BasicBlock *P = I->getParent()) 173ef860a24SChandler Carruth if (Function *PP = P->getParent()) 174a53d49e1SMehdi Amini ST = PP->getValueSymbolTable(); 175ef860a24SChandler Carruth } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 176ef860a24SChandler Carruth if (Function *P = BB->getParent()) 177a53d49e1SMehdi Amini ST = P->getValueSymbolTable(); 178ef860a24SChandler Carruth } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 179ef860a24SChandler Carruth if (Module *P = GV->getParent()) 180ef860a24SChandler Carruth ST = &P->getValueSymbolTable(); 181ef860a24SChandler Carruth } else if (Argument *A = dyn_cast<Argument>(V)) { 182ef860a24SChandler Carruth if (Function *P = A->getParent()) 183a53d49e1SMehdi Amini ST = P->getValueSymbolTable(); 1845bf8fef5SDuncan P. N. Exon Smith } else { 185ef860a24SChandler Carruth assert(isa<Constant>(V) && "Unknown value type!"); 186ef860a24SChandler Carruth return true; // no name is setable for this. 187ef860a24SChandler Carruth } 188ef860a24SChandler Carruth return false; 189ef860a24SChandler Carruth } 190ef860a24SChandler Carruth 1917349ab93SOwen Anderson ValueName *Value::getValueName() const { 1927349ab93SOwen Anderson if (!HasName) return nullptr; 1937349ab93SOwen Anderson 1947349ab93SOwen Anderson LLVMContext &Ctx = getContext(); 1957349ab93SOwen Anderson auto I = Ctx.pImpl->ValueNames.find(this); 1967349ab93SOwen Anderson assert(I != Ctx.pImpl->ValueNames.end() && 1977349ab93SOwen Anderson "No name entry found!"); 1987349ab93SOwen Anderson 1997349ab93SOwen Anderson return I->second; 2007349ab93SOwen Anderson } 2017349ab93SOwen Anderson 2027349ab93SOwen Anderson void Value::setValueName(ValueName *VN) { 2037349ab93SOwen Anderson LLVMContext &Ctx = getContext(); 2047349ab93SOwen Anderson 2057349ab93SOwen Anderson assert(HasName == Ctx.pImpl->ValueNames.count(this) && 2067349ab93SOwen Anderson "HasName bit out of sync!"); 2077349ab93SOwen Anderson 2087349ab93SOwen Anderson if (!VN) { 2097349ab93SOwen Anderson if (HasName) 2107349ab93SOwen Anderson Ctx.pImpl->ValueNames.erase(this); 2117349ab93SOwen Anderson HasName = false; 2127349ab93SOwen Anderson return; 2137349ab93SOwen Anderson } 2147349ab93SOwen Anderson 2157349ab93SOwen Anderson HasName = true; 2167349ab93SOwen Anderson Ctx.pImpl->ValueNames[this] = VN; 2177349ab93SOwen Anderson } 2187349ab93SOwen Anderson 219ef860a24SChandler Carruth StringRef Value::getName() const { 220ef860a24SChandler Carruth // Make sure the empty string is still a C string. For historical reasons, 221ef860a24SChandler Carruth // some clients want to call .data() on the result and expect it to be null 222ef860a24SChandler Carruth // terminated. 2237349ab93SOwen Anderson if (!hasName()) 2245bf8fef5SDuncan P. N. Exon Smith return StringRef("", 0); 2255bf8fef5SDuncan P. N. Exon Smith return getValueName()->getKey(); 226ef860a24SChandler Carruth } 227ef860a24SChandler Carruth 228a7c0c18cSPete Cooper void Value::setNameImpl(const Twine &NewName) { 22909b4a8daSMehdi Amini // Fast-path: LLVMContext can be set to strip out non-GlobalValue names 23050af49fcSMehdi Amini if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this)) 23109b4a8daSMehdi Amini return; 23209b4a8daSMehdi Amini 233ef860a24SChandler Carruth // Fast path for common IRBuilder case of setName("") when there is no name. 234ef860a24SChandler Carruth if (NewName.isTriviallyEmpty() && !hasName()) 235ef860a24SChandler Carruth return; 236ef860a24SChandler Carruth 237ef860a24SChandler Carruth SmallString<256> NameData; 238ef860a24SChandler Carruth StringRef NameRef = NewName.toStringRef(NameData); 23909d689f9SRafael Espindola assert(NameRef.find_first_of(0) == StringRef::npos && 24009d689f9SRafael Espindola "Null bytes are not allowed in names"); 241ef860a24SChandler Carruth 242ef860a24SChandler Carruth // Name isn't changing? 243ef860a24SChandler Carruth if (getName() == NameRef) 244ef860a24SChandler Carruth return; 245ef860a24SChandler Carruth 2464c975578SSerge Guelton // Cap the size of non-GlobalValue names. 2474c975578SSerge Guelton if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this)) 2484c975578SSerge Guelton NameRef = 2494c975578SSerge Guelton NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize)); 2504c975578SSerge Guelton 251ef860a24SChandler Carruth assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); 252ef860a24SChandler Carruth 253ef860a24SChandler Carruth // Get the symbol table to update for this object. 254ef860a24SChandler Carruth ValueSymbolTable *ST; 255ef860a24SChandler Carruth if (getSymTab(this, ST)) 256ef860a24SChandler Carruth return; // Cannot set a name on this value (e.g. constant). 257ef860a24SChandler Carruth 258ef860a24SChandler Carruth if (!ST) { // No symbol table to update? Just do the change. 259ef860a24SChandler Carruth if (NameRef.empty()) { 260ef860a24SChandler Carruth // Free the name for this value. 2615bf8fef5SDuncan P. N. Exon Smith destroyValueName(); 262ef860a24SChandler Carruth return; 263ef860a24SChandler Carruth } 264ef860a24SChandler Carruth 265ef860a24SChandler Carruth // NOTE: Could optimize for the case the name is shrinking to not deallocate 266ef860a24SChandler Carruth // then reallocated. 2675bf8fef5SDuncan P. N. Exon Smith destroyValueName(); 268ef860a24SChandler Carruth 269ef860a24SChandler Carruth // Create the new name. 2705bf8fef5SDuncan P. N. Exon Smith setValueName(ValueName::Create(NameRef)); 2715bf8fef5SDuncan P. N. Exon Smith getValueName()->setValue(this); 272ef860a24SChandler Carruth return; 273ef860a24SChandler Carruth } 274ef860a24SChandler Carruth 275ef860a24SChandler Carruth // NOTE: Could optimize for the case the name is shrinking to not deallocate 276ef860a24SChandler Carruth // then reallocated. 277ef860a24SChandler Carruth if (hasName()) { 278ef860a24SChandler Carruth // Remove old name. 2795bf8fef5SDuncan P. N. Exon Smith ST->removeValueName(getValueName()); 2805bf8fef5SDuncan P. N. Exon Smith destroyValueName(); 281ef860a24SChandler Carruth 282ef860a24SChandler Carruth if (NameRef.empty()) 283ef860a24SChandler Carruth return; 284ef860a24SChandler Carruth } 285ef860a24SChandler Carruth 286ef860a24SChandler Carruth // Name is changing to something new. 2875bf8fef5SDuncan P. N. Exon Smith setValueName(ST->createValueName(NameRef, this)); 288ef860a24SChandler Carruth } 289ef860a24SChandler Carruth 290a7c0c18cSPete Cooper void Value::setName(const Twine &NewName) { 291a7c0c18cSPete Cooper setNameImpl(NewName); 292a7c0c18cSPete Cooper if (Function *F = dyn_cast<Function>(this)) 293a7c0c18cSPete Cooper F->recalculateIntrinsicID(); 294a7c0c18cSPete Cooper } 295a7c0c18cSPete Cooper 296ef860a24SChandler Carruth void Value::takeName(Value *V) { 297c620761cSCraig Topper ValueSymbolTable *ST = nullptr; 298ef860a24SChandler Carruth // If this value has a name, drop it. 299ef860a24SChandler Carruth if (hasName()) { 300ef860a24SChandler Carruth // Get the symtab this is in. 301ef860a24SChandler Carruth if (getSymTab(this, ST)) { 302ef860a24SChandler Carruth // We can't set a name on this value, but we need to clear V's name if 303ef860a24SChandler Carruth // it has one. 304ef860a24SChandler Carruth if (V->hasName()) V->setName(""); 305ef860a24SChandler Carruth return; // Cannot set a name on this value (e.g. constant). 306ef860a24SChandler Carruth } 307ef860a24SChandler Carruth 308ef860a24SChandler Carruth // Remove old name. 309ef860a24SChandler Carruth if (ST) 3105bf8fef5SDuncan P. N. Exon Smith ST->removeValueName(getValueName()); 3115bf8fef5SDuncan P. N. Exon Smith destroyValueName(); 312ef860a24SChandler Carruth } 313ef860a24SChandler Carruth 314ef860a24SChandler Carruth // Now we know that this has no name. 315ef860a24SChandler Carruth 316ef860a24SChandler Carruth // If V has no name either, we're done. 317ef860a24SChandler Carruth if (!V->hasName()) return; 318ef860a24SChandler Carruth 319ef860a24SChandler Carruth // Get this's symtab if we didn't before. 320ef860a24SChandler Carruth if (!ST) { 321ef860a24SChandler Carruth if (getSymTab(this, ST)) { 322ef860a24SChandler Carruth // Clear V's name. 323ef860a24SChandler Carruth V->setName(""); 324ef860a24SChandler Carruth return; // Cannot set a name on this value (e.g. constant). 325ef860a24SChandler Carruth } 326ef860a24SChandler Carruth } 327ef860a24SChandler Carruth 328ef860a24SChandler Carruth // Get V's ST, this should always succed, because V has a name. 329ef860a24SChandler Carruth ValueSymbolTable *VST; 330ef860a24SChandler Carruth bool Failure = getSymTab(V, VST); 331ef860a24SChandler Carruth assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure; 332ef860a24SChandler Carruth 333ef860a24SChandler Carruth // If these values are both in the same symtab, we can do this very fast. 334ef860a24SChandler Carruth // This works even if both values have no symtab yet. 335ef860a24SChandler Carruth if (ST == VST) { 336ef860a24SChandler Carruth // Take the name! 3375bf8fef5SDuncan P. N. Exon Smith setValueName(V->getValueName()); 3385bf8fef5SDuncan P. N. Exon Smith V->setValueName(nullptr); 3395bf8fef5SDuncan P. N. Exon Smith getValueName()->setValue(this); 340ef860a24SChandler Carruth return; 341ef860a24SChandler Carruth } 342ef860a24SChandler Carruth 343ef860a24SChandler Carruth // Otherwise, things are slightly more complex. Remove V's name from VST and 344ef860a24SChandler Carruth // then reinsert it into ST. 345ef860a24SChandler Carruth 346ef860a24SChandler Carruth if (VST) 3475bf8fef5SDuncan P. N. Exon Smith VST->removeValueName(V->getValueName()); 3485bf8fef5SDuncan P. N. Exon Smith setValueName(V->getValueName()); 3495bf8fef5SDuncan P. N. Exon Smith V->setValueName(nullptr); 3505bf8fef5SDuncan P. N. Exon Smith getValueName()->setValue(this); 351ef860a24SChandler Carruth 352ef860a24SChandler Carruth if (ST) 353ef860a24SChandler Carruth ST->reinsertValue(this); 354ef860a24SChandler Carruth } 355ef860a24SChandler Carruth 356eec48903SCraig Topper void Value::assertModuleIsMaterializedImpl() const { 357675bdcedSTodd Fiala #ifndef NDEBUG 358257a3536SRafael Espindola const GlobalValue *GV = dyn_cast<GlobalValue>(this); 359257a3536SRafael Espindola if (!GV) 360257a3536SRafael Espindola return; 361257a3536SRafael Espindola const Module *M = GV->getParent(); 362257a3536SRafael Espindola if (!M) 363257a3536SRafael Espindola return; 364257a3536SRafael Espindola assert(M->isMaterialized()); 365675bdcedSTodd Fiala #endif 366257a3536SRafael Espindola } 367257a3536SRafael Espindola 368675bdcedSTodd Fiala #ifndef NDEBUG 36971b7b68bSCraig Topper static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr, 3707e2b7567SRafael Espindola Constant *C) { 37170573dcdSDavid Blaikie if (!Cache.insert(Expr).second) 3727e2b7567SRafael Espindola return false; 3737e2b7567SRafael Espindola 3747e2b7567SRafael Espindola for (auto &O : Expr->operands()) { 3757e2b7567SRafael Espindola if (O == C) 3767e2b7567SRafael Espindola return true; 3777e2b7567SRafael Espindola auto *CE = dyn_cast<ConstantExpr>(O); 3787e2b7567SRafael Espindola if (!CE) 3797e2b7567SRafael Espindola continue; 3807e2b7567SRafael Espindola if (contains(Cache, CE, C)) 3817e2b7567SRafael Espindola return true; 3827e2b7567SRafael Espindola } 3837e2b7567SRafael Espindola return false; 3847e2b7567SRafael Espindola } 3857e2b7567SRafael Espindola 3867e2b7567SRafael Espindola static bool contains(Value *Expr, Value *V) { 3877e2b7567SRafael Espindola if (Expr == V) 3887e2b7567SRafael Espindola return true; 3897e2b7567SRafael Espindola 3907e2b7567SRafael Espindola auto *C = dyn_cast<Constant>(V); 3917e2b7567SRafael Espindola if (!C) 3927e2b7567SRafael Espindola return false; 3937e2b7567SRafael Espindola 3947e2b7567SRafael Espindola auto *CE = dyn_cast<ConstantExpr>(Expr); 3957e2b7567SRafael Espindola if (!CE) 3967e2b7567SRafael Espindola return false; 3977e2b7567SRafael Espindola 3987e2b7567SRafael Espindola SmallPtrSet<ConstantExpr *, 4> Cache; 3997e2b7567SRafael Espindola return contains(Cache, CE, C); 4007e2b7567SRafael Espindola } 401ecefe5a8SEugene Zelenko #endif // NDEBUG 402ef860a24SChandler Carruth 403e69ae76bSJF Bastien void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) { 404ef860a24SChandler Carruth assert(New && "Value::replaceAllUsesWith(<null>) is invalid!"); 4057e2b7567SRafael Espindola assert(!contains(New, this) && 4067e2b7567SRafael Espindola "this->replaceAllUsesWith(expr(this)) is NOT valid!"); 407ef860a24SChandler Carruth assert(New->getType() == getType() && 408ef860a24SChandler Carruth "replaceAllUses of value with new value of different type!"); 409ef860a24SChandler Carruth 410ef860a24SChandler Carruth // Notify all ValueHandles (if present) that this value is going away. 411ef860a24SChandler Carruth if (HasValueHandle) 412ef860a24SChandler Carruth ValueHandleBase::ValueIsRAUWd(this, New); 413e69ae76bSJF Bastien if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata()) 4145bf8fef5SDuncan P. N. Exon Smith ValueAsMetadata::handleRAUW(this, New); 415ef860a24SChandler Carruth 41681bbf742STeresa Johnson while (!materialized_use_empty()) { 417ef860a24SChandler Carruth Use &U = *UseList; 418ef860a24SChandler Carruth // Must handle Constants specially, we cannot call replaceUsesOfWith on a 419ef860a24SChandler Carruth // constant because they are uniqued. 4206b238633SRafael Espindola if (auto *C = dyn_cast<Constant>(U.getUser())) { 421ef860a24SChandler Carruth if (!isa<GlobalValue>(C)) { 4228914d290SMehdi Amini C->handleOperandChange(this, New); 423ef860a24SChandler Carruth continue; 424ef860a24SChandler Carruth } 425ef860a24SChandler Carruth } 426ef860a24SChandler Carruth 427ef860a24SChandler Carruth U.set(New); 428ef860a24SChandler Carruth } 429ef860a24SChandler Carruth 430ef860a24SChandler Carruth if (BasicBlock *BB = dyn_cast<BasicBlock>(this)) 431ef860a24SChandler Carruth BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New)); 432ef860a24SChandler Carruth } 433ef860a24SChandler Carruth 4341ed53963SDavide Italiano void Value::replaceAllUsesWith(Value *New) { 435e69ae76bSJF Bastien doRAUW(New, ReplaceMetadataUses::Yes); 4361ed53963SDavide Italiano } 4371ed53963SDavide Italiano 4381ed53963SDavide Italiano void Value::replaceNonMetadataUsesWith(Value *New) { 439e69ae76bSJF Bastien doRAUW(New, ReplaceMetadataUses::No); 4401ed53963SDavide Italiano } 4411ed53963SDavide Italiano 442ec6217c9SGerolf Hoflehner // Like replaceAllUsesWith except it does not handle constants or basic blocks. 443ec6217c9SGerolf Hoflehner // This routine leaves uses within BB. 444ec6217c9SGerolf Hoflehner void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) { 445ec6217c9SGerolf Hoflehner assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!"); 446ec6217c9SGerolf Hoflehner assert(!contains(New, this) && 447ec6217c9SGerolf Hoflehner "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!"); 448ec6217c9SGerolf Hoflehner assert(New->getType() == getType() && 449ec6217c9SGerolf Hoflehner "replaceUses of value with new value of different type!"); 450ec6217c9SGerolf Hoflehner assert(BB && "Basic block that may contain a use of 'New' must be defined\n"); 451ec6217c9SGerolf Hoflehner 452081e990dSRoman Lebedev replaceUsesWithIf(New, [BB](Use &U) { 453081e990dSRoman Lebedev auto *I = dyn_cast<Instruction>(U.getUser()); 454081e990dSRoman Lebedev // Don't replace if it's an instruction in the BB basic block. 455081e990dSRoman Lebedev return !I || I->getParent() != BB; 456081e990dSRoman Lebedev }); 457ec6217c9SGerolf Hoflehner } 458ec6217c9SGerolf Hoflehner 459ef860a24SChandler Carruth namespace { 460ef860a24SChandler Carruth // Various metrics for how much to strip off of pointers. 461ef860a24SChandler Carruth enum PointerStripKind { 462ef860a24SChandler Carruth PSK_ZeroIndices, 4638a410bceSErich Keane PSK_ZeroIndicesAndAliases, 4642452d703SPeter Collingbourne PSK_ZeroIndicesSameRepresentation, 4652452d703SPeter Collingbourne PSK_ZeroIndicesAndInvariantGroups, 466ef860a24SChandler Carruth PSK_InBoundsConstantIndices, 467ef860a24SChandler Carruth PSK_InBounds 468ef860a24SChandler Carruth }; 469ef860a24SChandler Carruth 470ef860a24SChandler Carruth template <PointerStripKind StripKind> 4711dd20e65SCraig Topper static const Value *stripPointerCastsAndOffsets(const Value *V) { 472ef860a24SChandler Carruth if (!V->getType()->isPointerTy()) 473ef860a24SChandler Carruth return V; 474ef860a24SChandler Carruth 475ef860a24SChandler Carruth // Even though we don't look through PHI nodes, we could be called on an 476ef860a24SChandler Carruth // instruction in an unreachable block, which may be on a cycle. 4771dd20e65SCraig Topper SmallPtrSet<const Value *, 4> Visited; 478ef860a24SChandler Carruth 479ef860a24SChandler Carruth Visited.insert(V); 480ef860a24SChandler Carruth do { 4811dd20e65SCraig Topper if (auto *GEP = dyn_cast<GEPOperator>(V)) { 482ef860a24SChandler Carruth switch (StripKind) { 483ef860a24SChandler Carruth case PSK_ZeroIndices: 4848a410bceSErich Keane case PSK_ZeroIndicesAndAliases: 4852452d703SPeter Collingbourne case PSK_ZeroIndicesSameRepresentation: 4862452d703SPeter Collingbourne case PSK_ZeroIndicesAndInvariantGroups: 487ef860a24SChandler Carruth if (!GEP->hasAllZeroIndices()) 488ef860a24SChandler Carruth return V; 489ef860a24SChandler Carruth break; 490ef860a24SChandler Carruth case PSK_InBoundsConstantIndices: 491ef860a24SChandler Carruth if (!GEP->hasAllConstantIndices()) 492ef860a24SChandler Carruth return V; 493b03fd12cSJustin Bogner LLVM_FALLTHROUGH; 494ef860a24SChandler Carruth case PSK_InBounds: 495ef860a24SChandler Carruth if (!GEP->isInBounds()) 496ef860a24SChandler Carruth return V; 497ef860a24SChandler Carruth break; 498ef860a24SChandler Carruth } 499ef860a24SChandler Carruth V = GEP->getPointerOperand(); 50040107ce7SJohannes Doerfert } else if (Operator::getOpcode(V) == Instruction::BitCast) { 50140107ce7SJohannes Doerfert V = cast<Operator>(V)->getOperand(0); 5022452d703SPeter Collingbourne } else if (StripKind != PSK_ZeroIndicesSameRepresentation && 503b03bd4d9SMatt Arsenault Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 50440107ce7SJohannes Doerfert // TODO: If we know an address space cast will not change the 50540107ce7SJohannes Doerfert // representation we could look through it here as well. 506ef860a24SChandler Carruth V = cast<Operator>(V)->getOperand(0); 5078a410bceSErich Keane } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) { 5088a410bceSErich Keane V = cast<GlobalAlias>(V)->getAliasee(); 509ef860a24SChandler Carruth } else { 51090c09232SChandler Carruth if (const auto *Call = dyn_cast<CallBase>(V)) { 51190c09232SChandler Carruth if (const Value *RV = Call->getReturnedArgOperand()) { 5125c12d8feSHal Finkel V = RV; 5135c12d8feSHal Finkel continue; 5145c12d8feSHal Finkel } 5155dde8094SPiotr Padlewski // The result of launder.invariant.group must alias it's argument, 516610c966aSPiotr Padlewski // but it can't be marked with returned attribute, that's why it needs 517610c966aSPiotr Padlewski // special case. 5182452d703SPeter Collingbourne if (StripKind == PSK_ZeroIndicesAndInvariantGroups && 51990c09232SChandler Carruth (Call->getIntrinsicID() == Intrinsic::launder_invariant_group || 52090c09232SChandler Carruth Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) { 52190c09232SChandler Carruth V = Call->getArgOperand(0); 522610c966aSPiotr Padlewski continue; 523610c966aSPiotr Padlewski } 524610c966aSPiotr Padlewski } 525ef860a24SChandler Carruth return V; 526ef860a24SChandler Carruth } 527ef860a24SChandler Carruth assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 52870573dcdSDavid Blaikie } while (Visited.insert(V).second); 529ef860a24SChandler Carruth 530ef860a24SChandler Carruth return V; 531ef860a24SChandler Carruth } 532ecefe5a8SEugene Zelenko } // end anonymous namespace 533ef860a24SChandler Carruth 5341dd20e65SCraig Topper const Value *Value::stripPointerCasts() const { 5352452d703SPeter Collingbourne return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this); 536c229a4ffSRafael Espindola } 537c229a4ffSRafael Espindola 5388a410bceSErich Keane const Value *Value::stripPointerCastsAndAliases() const { 5398a410bceSErich Keane return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this); 5408a410bceSErich Keane } 5418a410bceSErich Keane 54240107ce7SJohannes Doerfert const Value *Value::stripPointerCastsSameRepresentation() const { 5432452d703SPeter Collingbourne return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this); 544ef860a24SChandler Carruth } 545ef860a24SChandler Carruth 5461dd20e65SCraig Topper const Value *Value::stripInBoundsConstantOffsets() const { 547ef860a24SChandler Carruth return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this); 548ef860a24SChandler Carruth } 549ef860a24SChandler Carruth 5505dde8094SPiotr Padlewski const Value *Value::stripPointerCastsAndInvariantGroups() const { 5512452d703SPeter Collingbourne return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this); 552610c966aSPiotr Padlewski } 553610c966aSPiotr Padlewski 5541dd20e65SCraig Topper const Value * 5553ed286a3SJohannes Doerfert Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, 5563ed286a3SJohannes Doerfert bool AllowNonInbounds) const { 5573ed286a3SJohannes Doerfert if (!getType()->isPtrOrPtrVectorTy()) 558989e6308SChandler Carruth return this; 559989e6308SChandler Carruth 5603ed286a3SJohannes Doerfert unsigned BitWidth = Offset.getBitWidth(); 5613ed286a3SJohannes Doerfert assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) && 562945b7e5aSElena Demikhovsky "The offset bit width does not match the DL specification."); 563989e6308SChandler Carruth 564989e6308SChandler Carruth // Even though we don't look through PHI nodes, we could be called on an 565989e6308SChandler Carruth // instruction in an unreachable block, which may be on a cycle. 5661dd20e65SCraig Topper SmallPtrSet<const Value *, 4> Visited; 567989e6308SChandler Carruth Visited.insert(this); 5681dd20e65SCraig Topper const Value *V = this; 569989e6308SChandler Carruth do { 5701dd20e65SCraig Topper if (auto *GEP = dyn_cast<GEPOperator>(V)) { 5713ed286a3SJohannes Doerfert // If in-bounds was requested, we do not strip non-in-bounds GEPs. 5723ed286a3SJohannes Doerfert if (!AllowNonInbounds && !GEP->isInBounds()) 573989e6308SChandler Carruth return V; 5743ed286a3SJohannes Doerfert 5753ed286a3SJohannes Doerfert // If one of the values we have visited is an addrspacecast, then 5763ed286a3SJohannes Doerfert // the pointer type of this GEP may be different from the type 5773ed286a3SJohannes Doerfert // of the Ptr parameter which was passed to this function. This 5783ed286a3SJohannes Doerfert // means when we construct GEPOffset, we need to use the size 5793ed286a3SJohannes Doerfert // of GEP's pointer type rather than the size of the original 5803ed286a3SJohannes Doerfert // pointer type. 5813ed286a3SJohannes Doerfert APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0); 582ba689b33SChandler Carruth if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 583989e6308SChandler Carruth return V; 5843ed286a3SJohannes Doerfert 5853ed286a3SJohannes Doerfert // Stop traversal if the pointer offset wouldn't fit in the bit-width 5863ed286a3SJohannes Doerfert // provided by the Offset argument. This can happen due to AddrSpaceCast 5873ed286a3SJohannes Doerfert // stripping. 5883ed286a3SJohannes Doerfert if (GEPOffset.getMinSignedBits() > BitWidth) 5893ed286a3SJohannes Doerfert return V; 5903ed286a3SJohannes Doerfert 5913ed286a3SJohannes Doerfert Offset += GEPOffset.sextOrTrunc(BitWidth); 592989e6308SChandler Carruth V = GEP->getPointerOperand(); 5933ed286a3SJohannes Doerfert } else if (Operator::getOpcode(V) == Instruction::BitCast || 5943ed286a3SJohannes Doerfert Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 595989e6308SChandler Carruth V = cast<Operator>(V)->getOperand(0); 5961dd20e65SCraig Topper } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 5973ed286a3SJohannes Doerfert if (!GA->isInterposable()) 598989e6308SChandler Carruth V = GA->getAliasee(); 5993ed286a3SJohannes Doerfert } else if (const auto *Call = dyn_cast<CallBase>(V)) { 6003ed286a3SJohannes Doerfert if (const Value *RV = Call->getReturnedArgOperand()) 6015c12d8feSHal Finkel V = RV; 6025c12d8feSHal Finkel } 6033ed286a3SJohannes Doerfert assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 60470573dcdSDavid Blaikie } while (Visited.insert(V).second); 605989e6308SChandler Carruth 606989e6308SChandler Carruth return V; 607989e6308SChandler Carruth } 608989e6308SChandler Carruth 6091dd20e65SCraig Topper const Value *Value::stripInBoundsOffsets() const { 610ef860a24SChandler Carruth return stripPointerCastsAndOffsets<PSK_InBounds>(this); 611ef860a24SChandler Carruth } 612ef860a24SChandler Carruth 6133603de2fSBjorn Steinbrink uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL, 61400953cbeSSanjoy Das bool &CanBeNull) const { 615345f0148SArtur Pilipenko assert(getType()->isPointerTy() && "must be pointer"); 616345f0148SArtur Pilipenko 6173603de2fSBjorn Steinbrink uint64_t DerefBytes = 0; 618345f0148SArtur Pilipenko CanBeNull = false; 619345f0148SArtur Pilipenko if (const Argument *A = dyn_cast<Argument>(this)) { 620345f0148SArtur Pilipenko DerefBytes = A->getDereferenceableBytes(); 6212da4d9d8SBjorn Steinbrink if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) { 622c27f81b9SBjorn Steinbrink Type *PT = cast<PointerType>(A->getType())->getElementType(); 6232da4d9d8SBjorn Steinbrink if (PT->isSized()) 624c27f81b9SBjorn Steinbrink DerefBytes = DL.getTypeStoreSize(PT); 62500953cbeSSanjoy Das } 626345f0148SArtur Pilipenko if (DerefBytes == 0) { 627345f0148SArtur Pilipenko DerefBytes = A->getDereferenceableOrNullBytes(); 628345f0148SArtur Pilipenko CanBeNull = true; 629345f0148SArtur Pilipenko } 63090c09232SChandler Carruth } else if (const auto *Call = dyn_cast<CallBase>(this)) { 63190c09232SChandler Carruth DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex); 632345f0148SArtur Pilipenko if (DerefBytes == 0) { 63390c09232SChandler Carruth DerefBytes = 63490c09232SChandler Carruth Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex); 635345f0148SArtur Pilipenko CanBeNull = true; 636345f0148SArtur Pilipenko } 637345f0148SArtur Pilipenko } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 638345f0148SArtur Pilipenko if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) { 639345f0148SArtur Pilipenko ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 640345f0148SArtur Pilipenko DerefBytes = CI->getLimitedValue(); 641345f0148SArtur Pilipenko } 642345f0148SArtur Pilipenko if (DerefBytes == 0) { 643345f0148SArtur Pilipenko if (MDNode *MD = 644345f0148SArtur Pilipenko LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 645345f0148SArtur Pilipenko ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 646345f0148SArtur Pilipenko DerefBytes = CI->getLimitedValue(); 647345f0148SArtur Pilipenko } 648345f0148SArtur Pilipenko CanBeNull = true; 649345f0148SArtur Pilipenko } 6506f13637aSRyan Taylor } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) { 6516f13637aSRyan Taylor if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) { 6526f13637aSRyan Taylor ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 6536f13637aSRyan Taylor DerefBytes = CI->getLimitedValue(); 6546f13637aSRyan Taylor } 6556f13637aSRyan Taylor if (DerefBytes == 0) { 6566f13637aSRyan Taylor if (MDNode *MD = 6576f13637aSRyan Taylor IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 6586f13637aSRyan Taylor ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 6596f13637aSRyan Taylor DerefBytes = CI->getLimitedValue(); 6606f13637aSRyan Taylor } 6616f13637aSRyan Taylor CanBeNull = true; 6626f13637aSRyan Taylor } 66300953cbeSSanjoy Das } else if (auto *AI = dyn_cast<AllocaInst>(this)) { 664030123e8SBjorn Steinbrink if (!AI->isArrayAllocation()) { 665030123e8SBjorn Steinbrink DerefBytes = DL.getTypeStoreSize(AI->getAllocatedType()); 66600953cbeSSanjoy Das CanBeNull = false; 66700953cbeSSanjoy Das } 66800953cbeSSanjoy Das } else if (auto *GV = dyn_cast<GlobalVariable>(this)) { 66900953cbeSSanjoy Das if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) { 67000953cbeSSanjoy Das // TODO: Don't outright reject hasExternalWeakLinkage but set the 67100953cbeSSanjoy Das // CanBeNull flag. 67200953cbeSSanjoy Das DerefBytes = DL.getTypeStoreSize(GV->getValueType()); 67300953cbeSSanjoy Das CanBeNull = false; 67400953cbeSSanjoy Das } 675345f0148SArtur Pilipenko } 676345f0148SArtur Pilipenko return DerefBytes; 677345f0148SArtur Pilipenko } 678345f0148SArtur Pilipenko 679bae629b9SGuillaume Chatelet MaybeAlign Value::getPointerAlignment(const DataLayout &DL) const { 680ae51afc5SArtur Pilipenko assert(getType()->isPointerTy() && "must be pointer"); 681ae51afc5SArtur Pilipenko if (auto *GO = dyn_cast<GlobalObject>(this)) { 682308e82ecSMichael Platings if (isa<Function>(GO)) { 68318f805a7SGuillaume Chatelet const MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign(); 684308e82ecSMichael Platings switch (DL.getFunctionPtrAlignType()) { 685308e82ecSMichael Platings case DataLayout::FunctionPtrAlignType::Independent: 686bae629b9SGuillaume Chatelet return FunctionPtrAlign; 687308e82ecSMichael Platings case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign: 688bae629b9SGuillaume Chatelet return std::max(FunctionPtrAlign, MaybeAlign(GO->getAlignment())); 689308e82ecSMichael Platings } 6906200a568SGuillaume Chatelet llvm_unreachable("Unhandled FunctionPtrAlignType"); 691308e82ecSMichael Platings } 692bae629b9SGuillaume Chatelet const MaybeAlign Alignment(GO->getAlignment()); 693bae629b9SGuillaume Chatelet if (!Alignment) { 694ae51afc5SArtur Pilipenko if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 695ae51afc5SArtur Pilipenko Type *ObjectType = GVar->getValueType(); 696ae51afc5SArtur Pilipenko if (ObjectType->isSized()) { 697ae51afc5SArtur Pilipenko // If the object is defined in the current Module, we'll be giving 698ae51afc5SArtur Pilipenko // it the preferred alignment. Otherwise, we have to assume that it 699ae51afc5SArtur Pilipenko // may only have the minimum ABI alignment. 700ae51afc5SArtur Pilipenko if (GVar->isStrongDefinitionForLinker()) 701bae629b9SGuillaume Chatelet return MaybeAlign(DL.getPreferredAlignment(GVar)); 702ae51afc5SArtur Pilipenko else 703bae629b9SGuillaume Chatelet return Align(DL.getABITypeAlignment(ObjectType)); 704ae51afc5SArtur Pilipenko } 705ae51afc5SArtur Pilipenko } 706ae51afc5SArtur Pilipenko } 707bae629b9SGuillaume Chatelet return Alignment; 708ae51afc5SArtur Pilipenko } else if (const Argument *A = dyn_cast<Argument>(this)) { 709bae629b9SGuillaume Chatelet const MaybeAlign Alignment(A->getParamAlignment()); 710bae629b9SGuillaume Chatelet if (!Alignment && A->hasStructRetAttr()) { 711ae51afc5SArtur Pilipenko // An sret parameter has at least the ABI alignment of the return type. 712ae51afc5SArtur Pilipenko Type *EltTy = cast<PointerType>(A->getType())->getElementType(); 713ae51afc5SArtur Pilipenko if (EltTy->isSized()) 714bae629b9SGuillaume Chatelet return Align(DL.getABITypeAlignment(EltTy)); 715ae51afc5SArtur Pilipenko } 716bae629b9SGuillaume Chatelet return Alignment; 717c97eac65SArtur Pilipenko } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) { 718bae629b9SGuillaume Chatelet const MaybeAlign Alignment(AI->getAlignment()); 719bae629b9SGuillaume Chatelet if (!Alignment) { 720c97eac65SArtur Pilipenko Type *AllocatedType = AI->getAllocatedType(); 721c97eac65SArtur Pilipenko if (AllocatedType->isSized()) 722bae629b9SGuillaume Chatelet return MaybeAlign(DL.getPrefTypeAlignment(AllocatedType)); 723c97eac65SArtur Pilipenko } 724bae629b9SGuillaume Chatelet return Alignment; 725afd4a37bSHideto Ueno } else if (const auto *Call = dyn_cast<CallBase>(this)) { 726bae629b9SGuillaume Chatelet const MaybeAlign Alignment(Call->getRetAlignment()); 727bae629b9SGuillaume Chatelet if (!Alignment && Call->getCalledFunction()) 728bae629b9SGuillaume Chatelet return MaybeAlign( 729bae629b9SGuillaume Chatelet Call->getCalledFunction()->getAttributes().getRetAlignment()); 730bae629b9SGuillaume Chatelet return Alignment; 7316200a568SGuillaume Chatelet } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 732ae51afc5SArtur Pilipenko if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) { 733ae51afc5SArtur Pilipenko ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 734bae629b9SGuillaume Chatelet return MaybeAlign(CI->getLimitedValue()); 735ae51afc5SArtur Pilipenko } 736a6492e22SRoman Lebedev } else if (auto *CstPtr = dyn_cast<Constant>(this)) { 737a6492e22SRoman Lebedev if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt( 738a6492e22SRoman Lebedev const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()), 739a6492e22SRoman Lebedev /*OnlyIfReduced=*/true))) { 740a6492e22SRoman Lebedev size_t TrailingZeros = CstInt->getValue().countTrailingZeros(); 741a6492e22SRoman Lebedev // While the actual alignment may be large, elsewhere we have 742a6492e22SRoman Lebedev // an arbitrary upper alignmet limit, so let's clamp to it. 743a6492e22SRoman Lebedev return Align(TrailingZeros < Value::MaxAlignmentExponent 744a6492e22SRoman Lebedev ? uint64_t(1) << TrailingZeros 745a6492e22SRoman Lebedev : Value::MaximumAlignment); 746a6492e22SRoman Lebedev } 7476200a568SGuillaume Chatelet } 748bae629b9SGuillaume Chatelet return llvm::None; 749ae51afc5SArtur Pilipenko } 750ae51afc5SArtur Pilipenko 7511dd20e65SCraig Topper const Value *Value::DoPHITranslation(const BasicBlock *CurBB, 7521dd20e65SCraig Topper const BasicBlock *PredBB) const { 7531dd20e65SCraig Topper auto *PN = dyn_cast<PHINode>(this); 754ef860a24SChandler Carruth if (PN && PN->getParent() == CurBB) 755ef860a24SChandler Carruth return PN->getIncomingValueForBlock(PredBB); 756ef860a24SChandler Carruth return this; 757ef860a24SChandler Carruth } 758ef860a24SChandler Carruth 759ef860a24SChandler Carruth LLVMContext &Value::getContext() const { return VTy->getContext(); } 760ef860a24SChandler Carruth 7613441ffe9SDuncan P. N. Exon Smith void Value::reverseUseList() { 7623441ffe9SDuncan P. N. Exon Smith if (!UseList || !UseList->Next) 7633441ffe9SDuncan P. N. Exon Smith // No need to reverse 0 or 1 uses. 7643441ffe9SDuncan P. N. Exon Smith return; 7653441ffe9SDuncan P. N. Exon Smith 7663441ffe9SDuncan P. N. Exon Smith Use *Head = UseList; 7673441ffe9SDuncan P. N. Exon Smith Use *Current = UseList->Next; 7683441ffe9SDuncan P. N. Exon Smith Head->Next = nullptr; 7693441ffe9SDuncan P. N. Exon Smith while (Current) { 7703441ffe9SDuncan P. N. Exon Smith Use *Next = Current->Next; 7713441ffe9SDuncan P. N. Exon Smith Current->Next = Head; 7723441ffe9SDuncan P. N. Exon Smith Head->setPrev(&Current->Next); 7733441ffe9SDuncan P. N. Exon Smith Head = Current; 7743441ffe9SDuncan P. N. Exon Smith Current = Next; 7753441ffe9SDuncan P. N. Exon Smith } 7763441ffe9SDuncan P. N. Exon Smith UseList = Head; 7773441ffe9SDuncan P. N. Exon Smith Head->setPrev(&UseList); 7783441ffe9SDuncan P. N. Exon Smith } 7793441ffe9SDuncan P. N. Exon Smith 780ad830022SArnold Schwaighofer bool Value::isSwiftError() const { 781ad830022SArnold Schwaighofer auto *Arg = dyn_cast<Argument>(this); 782ad830022SArnold Schwaighofer if (Arg) 783ad830022SArnold Schwaighofer return Arg->hasSwiftErrorAttr(); 784ad830022SArnold Schwaighofer auto *Alloca = dyn_cast<AllocaInst>(this); 785ad830022SArnold Schwaighofer if (!Alloca) 786ad830022SArnold Schwaighofer return false; 787ad830022SArnold Schwaighofer return Alloca->isSwiftError(); 788ad830022SArnold Schwaighofer } 789ad830022SArnold Schwaighofer 790ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 791ef860a24SChandler Carruth // ValueHandleBase Class 792ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 793ef860a24SChandler Carruth 794ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) { 795ef860a24SChandler Carruth assert(List && "Handle list is null?"); 796ef860a24SChandler Carruth 797ef860a24SChandler Carruth // Splice ourselves into the list. 798ef860a24SChandler Carruth Next = *List; 799ef860a24SChandler Carruth *List = this; 800ef860a24SChandler Carruth setPrevPtr(List); 801ef860a24SChandler Carruth if (Next) { 802ef860a24SChandler Carruth Next->setPrevPtr(&Next); 8036f08789dSSanjoy Das assert(getValPtr() == Next->getValPtr() && "Added to wrong list?"); 804ef860a24SChandler Carruth } 805ef860a24SChandler Carruth } 806ef860a24SChandler Carruth 807ef860a24SChandler Carruth void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) { 808ef860a24SChandler Carruth assert(List && "Must insert after existing node"); 809ef860a24SChandler Carruth 810ef860a24SChandler Carruth Next = List->Next; 811ef860a24SChandler Carruth setPrevPtr(&List->Next); 812ef860a24SChandler Carruth List->Next = this; 813ef860a24SChandler Carruth if (Next) 814ef860a24SChandler Carruth Next->setPrevPtr(&Next); 815ef860a24SChandler Carruth } 816ef860a24SChandler Carruth 817ef860a24SChandler Carruth void ValueHandleBase::AddToUseList() { 8186f08789dSSanjoy Das assert(getValPtr() && "Null pointer doesn't have a use list!"); 819ef860a24SChandler Carruth 8206f08789dSSanjoy Das LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 821ef860a24SChandler Carruth 8226f08789dSSanjoy Das if (getValPtr()->HasValueHandle) { 823ef860a24SChandler Carruth // If this value already has a ValueHandle, then it must be in the 824ef860a24SChandler Carruth // ValueHandles map already. 8256f08789dSSanjoy Das ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()]; 8262617dcceSCraig Topper assert(Entry && "Value doesn't have any handles?"); 827ef860a24SChandler Carruth AddToExistingUseList(&Entry); 828ef860a24SChandler Carruth return; 829ef860a24SChandler Carruth } 830ef860a24SChandler Carruth 831ef860a24SChandler Carruth // Ok, it doesn't have any handles yet, so we must insert it into the 832ef860a24SChandler Carruth // DenseMap. However, doing this insertion could cause the DenseMap to 833ef860a24SChandler Carruth // reallocate itself, which would invalidate all of the PrevP pointers that 834ef860a24SChandler Carruth // point into the old table. Handle this by checking for reallocation and 835ef860a24SChandler Carruth // updating the stale pointers only if needed. 836ef860a24SChandler Carruth DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 837ef860a24SChandler Carruth const void *OldBucketPtr = Handles.getPointerIntoBucketsArray(); 838ef860a24SChandler Carruth 8396f08789dSSanjoy Das ValueHandleBase *&Entry = Handles[getValPtr()]; 8402617dcceSCraig Topper assert(!Entry && "Value really did already have handles?"); 841ef860a24SChandler Carruth AddToExistingUseList(&Entry); 8426f08789dSSanjoy Das getValPtr()->HasValueHandle = true; 843ef860a24SChandler Carruth 844ef860a24SChandler Carruth // If reallocation didn't happen or if this was the first insertion, don't 845ef860a24SChandler Carruth // walk the table. 846ef860a24SChandler Carruth if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 847ef860a24SChandler Carruth Handles.size() == 1) { 848ef860a24SChandler Carruth return; 849ef860a24SChandler Carruth } 850ef860a24SChandler Carruth 851ef860a24SChandler Carruth // Okay, reallocation did happen. Fix the Prev Pointers. 852ef860a24SChandler Carruth for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(), 853ef860a24SChandler Carruth E = Handles.end(); I != E; ++I) { 8546f08789dSSanjoy Das assert(I->second && I->first == I->second->getValPtr() && 855ef860a24SChandler Carruth "List invariant broken!"); 856ef860a24SChandler Carruth I->second->setPrevPtr(&I->second); 857ef860a24SChandler Carruth } 858ef860a24SChandler Carruth } 859ef860a24SChandler Carruth 860ef860a24SChandler Carruth void ValueHandleBase::RemoveFromUseList() { 8616f08789dSSanjoy Das assert(getValPtr() && getValPtr()->HasValueHandle && 862ef860a24SChandler Carruth "Pointer doesn't have a use list!"); 863ef860a24SChandler Carruth 864ef860a24SChandler Carruth // Unlink this from its use list. 865ef860a24SChandler Carruth ValueHandleBase **PrevPtr = getPrevPtr(); 866ef860a24SChandler Carruth assert(*PrevPtr == this && "List invariant broken"); 867ef860a24SChandler Carruth 868ef860a24SChandler Carruth *PrevPtr = Next; 869ef860a24SChandler Carruth if (Next) { 870ef860a24SChandler Carruth assert(Next->getPrevPtr() == &Next && "List invariant broken"); 871ef860a24SChandler Carruth Next->setPrevPtr(PrevPtr); 872ef860a24SChandler Carruth return; 873ef860a24SChandler Carruth } 874ef860a24SChandler Carruth 875ef860a24SChandler Carruth // If the Next pointer was null, then it is possible that this was the last 876ef860a24SChandler Carruth // ValueHandle watching VP. If so, delete its entry from the ValueHandles 877ef860a24SChandler Carruth // map. 8786f08789dSSanjoy Das LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 879ef860a24SChandler Carruth DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 880ef860a24SChandler Carruth if (Handles.isPointerIntoBucketsArray(PrevPtr)) { 8816f08789dSSanjoy Das Handles.erase(getValPtr()); 8826f08789dSSanjoy Das getValPtr()->HasValueHandle = false; 883ef860a24SChandler Carruth } 884ef860a24SChandler Carruth } 885ef860a24SChandler Carruth 886ef860a24SChandler Carruth void ValueHandleBase::ValueIsDeleted(Value *V) { 887ef860a24SChandler Carruth assert(V->HasValueHandle && "Should only be called if ValueHandles present"); 888ef860a24SChandler Carruth 889ef860a24SChandler Carruth // Get the linked list base, which is guaranteed to exist since the 890ef860a24SChandler Carruth // HasValueHandle flag is set. 891ef860a24SChandler Carruth LLVMContextImpl *pImpl = V->getContext().pImpl; 892ef860a24SChandler Carruth ValueHandleBase *Entry = pImpl->ValueHandles[V]; 893ef860a24SChandler Carruth assert(Entry && "Value bit set but no entries exist"); 894ef860a24SChandler Carruth 895ef860a24SChandler Carruth // We use a local ValueHandleBase as an iterator so that ValueHandles can add 896ef860a24SChandler Carruth // and remove themselves from the list without breaking our iteration. This 897ef860a24SChandler Carruth // is not really an AssertingVH; we just have to give ValueHandleBase a kind. 898ef860a24SChandler Carruth // Note that we deliberately do not the support the case when dropping a value 899ef860a24SChandler Carruth // handle results in a new value handle being permanently added to the list 900ef860a24SChandler Carruth // (as might occur in theory for CallbackVH's): the new value handle will not 901ef860a24SChandler Carruth // be processed and the checking code will mete out righteous punishment if 902ef860a24SChandler Carruth // the handle is still present once we have finished processing all the other 903ef860a24SChandler Carruth // value handles (it is fine to momentarily add then remove a value handle). 904ef860a24SChandler Carruth for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 905ef860a24SChandler Carruth Iterator.RemoveFromUseList(); 906ef860a24SChandler Carruth Iterator.AddToExistingUseListAfter(Entry); 907ef860a24SChandler Carruth assert(Entry->Next == &Iterator && "Loop invariant broken."); 908ef860a24SChandler Carruth 909ef860a24SChandler Carruth switch (Entry->getKind()) { 910ef860a24SChandler Carruth case Assert: 911ef860a24SChandler Carruth break; 912f1c0eafdSSanjoy Das case Weak: 913e6bca0eeSSanjoy Das case WeakTracking: 914f1c0eafdSSanjoy Das // WeakTracking and Weak just go to null, which unlinks them 915f1c0eafdSSanjoy Das // from the list. 916c620761cSCraig Topper Entry->operator=(nullptr); 917ef860a24SChandler Carruth break; 918ef860a24SChandler Carruth case Callback: 919ef860a24SChandler Carruth // Forward to the subclass's implementation. 920ef860a24SChandler Carruth static_cast<CallbackVH*>(Entry)->deleted(); 921ef860a24SChandler Carruth break; 922ef860a24SChandler Carruth } 923ef860a24SChandler Carruth } 924ef860a24SChandler Carruth 925ef860a24SChandler Carruth // All callbacks, weak references, and assertingVHs should be dropped by now. 926ef860a24SChandler Carruth if (V->HasValueHandle) { 927ef860a24SChandler Carruth #ifndef NDEBUG // Only in +Asserts mode... 928ef860a24SChandler Carruth dbgs() << "While deleting: " << *V->getType() << " %" << V->getName() 929ef860a24SChandler Carruth << "\n"; 930ef860a24SChandler Carruth if (pImpl->ValueHandles[V]->getKind() == Assert) 931ef860a24SChandler Carruth llvm_unreachable("An asserting value handle still pointed to this" 932ef860a24SChandler Carruth " value!"); 933ef860a24SChandler Carruth 934ef860a24SChandler Carruth #endif 935ef860a24SChandler Carruth llvm_unreachable("All references to V were not removed?"); 936ef860a24SChandler Carruth } 937ef860a24SChandler Carruth } 938ef860a24SChandler Carruth 939ef860a24SChandler Carruth void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) { 940ef860a24SChandler Carruth assert(Old->HasValueHandle &&"Should only be called if ValueHandles present"); 941ef860a24SChandler Carruth assert(Old != New && "Changing value into itself!"); 942c1892e2dSFrederic Riss assert(Old->getType() == New->getType() && 943c1892e2dSFrederic Riss "replaceAllUses of value with new value of different type!"); 944ef860a24SChandler Carruth 945ef860a24SChandler Carruth // Get the linked list base, which is guaranteed to exist since the 946ef860a24SChandler Carruth // HasValueHandle flag is set. 947ef860a24SChandler Carruth LLVMContextImpl *pImpl = Old->getContext().pImpl; 948ef860a24SChandler Carruth ValueHandleBase *Entry = pImpl->ValueHandles[Old]; 949ef860a24SChandler Carruth 950ef860a24SChandler Carruth assert(Entry && "Value bit set but no entries exist"); 951ef860a24SChandler Carruth 952ef860a24SChandler Carruth // We use a local ValueHandleBase as an iterator so that 953ef860a24SChandler Carruth // ValueHandles can add and remove themselves from the list without 954ef860a24SChandler Carruth // breaking our iteration. This is not really an AssertingVH; we 955ef860a24SChandler Carruth // just have to give ValueHandleBase some kind. 956ef860a24SChandler Carruth for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 957ef860a24SChandler Carruth Iterator.RemoveFromUseList(); 958ef860a24SChandler Carruth Iterator.AddToExistingUseListAfter(Entry); 959ef860a24SChandler Carruth assert(Entry->Next == &Iterator && "Loop invariant broken."); 960ef860a24SChandler Carruth 961ef860a24SChandler Carruth switch (Entry->getKind()) { 962ef860a24SChandler Carruth case Assert: 963f1c0eafdSSanjoy Das case Weak: 964f1c0eafdSSanjoy Das // Asserting and Weak handles do not follow RAUW implicitly. 965ef860a24SChandler Carruth break; 966e6bca0eeSSanjoy Das case WeakTracking: 9672cbeb00fSSanjoy Das // Weak goes to the new value, which will unlink it from Old's list. 968ef860a24SChandler Carruth Entry->operator=(New); 969ef860a24SChandler Carruth break; 970ef860a24SChandler Carruth case Callback: 971ef860a24SChandler Carruth // Forward to the subclass's implementation. 972ef860a24SChandler Carruth static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New); 973ef860a24SChandler Carruth break; 974ef860a24SChandler Carruth } 975ef860a24SChandler Carruth } 976ef860a24SChandler Carruth 977ef860a24SChandler Carruth #ifndef NDEBUG 9788a623820SSanjoy Das // If any new weak value handles were added while processing the 979ef860a24SChandler Carruth // list, then complain about it now. 980ef860a24SChandler Carruth if (Old->HasValueHandle) 981ef860a24SChandler Carruth for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next) 982ef860a24SChandler Carruth switch (Entry->getKind()) { 983e6bca0eeSSanjoy Das case WeakTracking: 984ef860a24SChandler Carruth dbgs() << "After RAUW from " << *Old->getType() << " %" 985ef860a24SChandler Carruth << Old->getName() << " to " << *New->getType() << " %" 986ef860a24SChandler Carruth << New->getName() << "\n"; 9878a623820SSanjoy Das llvm_unreachable( 988e6bca0eeSSanjoy Das "A weak tracking value handle still pointed to the old value!\n"); 989ef860a24SChandler Carruth default: 990ef860a24SChandler Carruth break; 991ef860a24SChandler Carruth } 992ef860a24SChandler Carruth #endif 993ef860a24SChandler Carruth } 994ef860a24SChandler Carruth 995d12ccbd3SJuergen Ributzka // Pin the vtable to this file. 996d12ccbd3SJuergen Ributzka void CallbackVH::anchor() {} 997