1 //===-- Value.cpp - Implement the Value class -----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Value, ValueHandle, and User classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Value.h" 14 #include "LLVMContextImpl.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/IR/Constant.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/DerivedUser.h" 23 #include "llvm/IR/GetElementPtrTypeIterator.h" 24 #include "llvm/IR/InstrTypes.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/IR/Operator.h" 29 #include "llvm/IR/Statepoint.h" 30 #include "llvm/IR/ValueHandle.h" 31 #include "llvm/IR/ValueSymbolTable.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/ManagedStatic.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> 38 39 using namespace llvm; 40 41 static cl::opt<unsigned> NonGlobalValueMaxNameSize( 42 "non-global-value-max-name-size", cl::Hidden, cl::init(1024), 43 cl::desc("Maximum size for the name of non-global values.")); 44 45 //===----------------------------------------------------------------------===// 46 // Value Class 47 //===----------------------------------------------------------------------===// 48 static inline Type *checkType(Type *Ty) { 49 assert(Ty && "Value defined with a null type: Error!"); 50 return Ty; 51 } 52 53 Value::Value(Type *ty, unsigned scid) 54 : VTy(checkType(ty)), UseList(nullptr), SubclassID(scid), 55 HasValueHandle(0), SubclassOptionalData(0), SubclassData(0), 56 NumUserOperands(0), IsUsedByMD(false), HasName(false) { 57 static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)"); 58 // FIXME: Why isn't this in the subclass gunk?? 59 // Note, we cannot call isa<CallInst> before the CallInst has been 60 // constructed. 61 if (SubclassID == Instruction::Call || SubclassID == Instruction::Invoke || 62 SubclassID == Instruction::CallBr) 63 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) && 64 "invalid CallInst type!"); 65 else if (SubclassID != BasicBlockVal && 66 (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal)) 67 assert((VTy->isFirstClassType() || VTy->isVoidTy()) && 68 "Cannot create non-first-class values except for constants!"); 69 static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned), 70 "Value too big"); 71 } 72 73 Value::~Value() { 74 // Notify all ValueHandles (if present) that this value is going away. 75 if (HasValueHandle) 76 ValueHandleBase::ValueIsDeleted(this); 77 if (isUsedByMetadata()) 78 ValueAsMetadata::handleDeletion(this); 79 80 #ifndef NDEBUG // Only in -g mode... 81 // Check to make sure that there are no uses of this value that are still 82 // around when the value is destroyed. If there are, then we have a dangling 83 // reference and something is wrong. This code is here to print out where 84 // the value is still being referenced. 85 // 86 // Note that use_empty() cannot be called here, as it eventually downcasts 87 // 'this' to GlobalValue (derived class of Value), but GlobalValue has already 88 // been destructed, so accessing it is UB. 89 // 90 if (!materialized_use_empty()) { 91 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n"; 92 for (auto *U : users()) 93 dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n"; 94 } 95 #endif 96 assert(materialized_use_empty() && "Uses remain when a value is destroyed!"); 97 98 // If this value is named, destroy the name. This should not be in a symtab 99 // at this point. 100 destroyValueName(); 101 } 102 103 void Value::deleteValue() { 104 switch (getValueID()) { 105 #define HANDLE_VALUE(Name) \ 106 case Value::Name##Val: \ 107 delete static_cast<Name *>(this); \ 108 break; 109 #define HANDLE_MEMORY_VALUE(Name) \ 110 case Value::Name##Val: \ 111 static_cast<DerivedUser *>(this)->DeleteValue( \ 112 static_cast<DerivedUser *>(this)); \ 113 break; 114 #define HANDLE_INSTRUCTION(Name) /* nothing */ 115 #include "llvm/IR/Value.def" 116 117 #define HANDLE_INST(N, OPC, CLASS) \ 118 case Value::InstructionVal + Instruction::OPC: \ 119 delete static_cast<CLASS *>(this); \ 120 break; 121 #define HANDLE_USER_INST(N, OPC, CLASS) 122 #include "llvm/IR/Instruction.def" 123 124 default: 125 llvm_unreachable("attempting to delete unknown value kind"); 126 } 127 } 128 129 void Value::destroyValueName() { 130 ValueName *Name = getValueName(); 131 if (Name) 132 Name->Destroy(); 133 setValueName(nullptr); 134 } 135 136 bool Value::hasNUses(unsigned N) const { 137 return hasNItems(use_begin(), use_end(), N); 138 } 139 140 bool Value::hasNUsesOrMore(unsigned N) const { 141 return hasNItemsOrMore(use_begin(), use_end(), N); 142 } 143 144 static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); } 145 146 Use *Value::getSingleUndroppableUse() { 147 Use *Result = nullptr; 148 for (Use &U : uses()) { 149 if (!U.getUser()->isDroppable()) { 150 if (Result) 151 return nullptr; 152 Result = &U; 153 } 154 } 155 return Result; 156 } 157 158 bool Value::hasNUndroppableUses(unsigned int N) const { 159 return hasNItems(user_begin(), user_end(), N, isUnDroppableUser); 160 } 161 162 bool Value::hasNUndroppableUsesOrMore(unsigned int N) const { 163 return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser); 164 } 165 166 void Value::dropDroppableUses( 167 llvm::function_ref<bool(const Use *)> ShouldDrop) { 168 SmallVector<Use *, 8> ToBeEdited; 169 for (Use &U : uses()) 170 if (U.getUser()->isDroppable() && ShouldDrop(&U)) 171 ToBeEdited.push_back(&U); 172 for (Use *U : ToBeEdited) { 173 U->removeFromList(); 174 if (auto *Assume = dyn_cast<IntrinsicInst>(U->getUser())) { 175 assert(Assume->getIntrinsicID() == Intrinsic::assume); 176 unsigned OpNo = U->getOperandNo(); 177 if (OpNo == 0) 178 Assume->setOperand(0, ConstantInt::getTrue(Assume->getContext())); 179 else { 180 Assume->setOperand(OpNo, UndefValue::get(U->get()->getType())); 181 CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo); 182 BOI.Tag = getContext().pImpl->getOrInsertBundleTag("ignore"); 183 } 184 } else 185 llvm_unreachable("unkown droppable use"); 186 } 187 } 188 189 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const { 190 // This can be computed either by scanning the instructions in BB, or by 191 // scanning the use list of this Value. Both lists can be very long, but 192 // usually one is quite short. 193 // 194 // Scan both lists simultaneously until one is exhausted. This limits the 195 // search to the shorter list. 196 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); 197 const_user_iterator UI = user_begin(), UE = user_end(); 198 for (; BI != BE && UI != UE; ++BI, ++UI) { 199 // Scan basic block: Check if this Value is used by the instruction at BI. 200 if (is_contained(BI->operands(), this)) 201 return true; 202 // Scan use list: Check if the use at UI is in BB. 203 const auto *User = dyn_cast<Instruction>(*UI); 204 if (User && User->getParent() == BB) 205 return true; 206 } 207 return false; 208 } 209 210 unsigned Value::getNumUses() const { 211 return (unsigned)std::distance(use_begin(), use_end()); 212 } 213 214 static bool getSymTab(Value *V, ValueSymbolTable *&ST) { 215 ST = nullptr; 216 if (Instruction *I = dyn_cast<Instruction>(V)) { 217 if (BasicBlock *P = I->getParent()) 218 if (Function *PP = P->getParent()) 219 ST = PP->getValueSymbolTable(); 220 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) { 221 if (Function *P = BB->getParent()) 222 ST = P->getValueSymbolTable(); 223 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 224 if (Module *P = GV->getParent()) 225 ST = &P->getValueSymbolTable(); 226 } else if (Argument *A = dyn_cast<Argument>(V)) { 227 if (Function *P = A->getParent()) 228 ST = P->getValueSymbolTable(); 229 } else { 230 assert(isa<Constant>(V) && "Unknown value type!"); 231 return true; // no name is setable for this. 232 } 233 return false; 234 } 235 236 ValueName *Value::getValueName() const { 237 if (!HasName) return nullptr; 238 239 LLVMContext &Ctx = getContext(); 240 auto I = Ctx.pImpl->ValueNames.find(this); 241 assert(I != Ctx.pImpl->ValueNames.end() && 242 "No name entry found!"); 243 244 return I->second; 245 } 246 247 void Value::setValueName(ValueName *VN) { 248 LLVMContext &Ctx = getContext(); 249 250 assert(HasName == Ctx.pImpl->ValueNames.count(this) && 251 "HasName bit out of sync!"); 252 253 if (!VN) { 254 if (HasName) 255 Ctx.pImpl->ValueNames.erase(this); 256 HasName = false; 257 return; 258 } 259 260 HasName = true; 261 Ctx.pImpl->ValueNames[this] = VN; 262 } 263 264 StringRef Value::getName() const { 265 // Make sure the empty string is still a C string. For historical reasons, 266 // some clients want to call .data() on the result and expect it to be null 267 // terminated. 268 if (!hasName()) 269 return StringRef("", 0); 270 return getValueName()->getKey(); 271 } 272 273 void Value::setNameImpl(const Twine &NewName) { 274 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names 275 if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this)) 276 return; 277 278 // Fast path for common IRBuilder case of setName("") when there is no name. 279 if (NewName.isTriviallyEmpty() && !hasName()) 280 return; 281 282 SmallString<256> NameData; 283 StringRef NameRef = NewName.toStringRef(NameData); 284 assert(NameRef.find_first_of(0) == StringRef::npos && 285 "Null bytes are not allowed in names"); 286 287 // Name isn't changing? 288 if (getName() == NameRef) 289 return; 290 291 // Cap the size of non-GlobalValue names. 292 if (NameRef.size() > NonGlobalValueMaxNameSize && !isa<GlobalValue>(this)) 293 NameRef = 294 NameRef.substr(0, std::max(1u, (unsigned)NonGlobalValueMaxNameSize)); 295 296 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!"); 297 298 // Get the symbol table to update for this object. 299 ValueSymbolTable *ST; 300 if (getSymTab(this, ST)) 301 return; // Cannot set a name on this value (e.g. constant). 302 303 if (!ST) { // No symbol table to update? Just do the change. 304 if (NameRef.empty()) { 305 // Free the name for this value. 306 destroyValueName(); 307 return; 308 } 309 310 // NOTE: Could optimize for the case the name is shrinking to not deallocate 311 // then reallocated. 312 destroyValueName(); 313 314 // Create the new name. 315 setValueName(ValueName::Create(NameRef)); 316 getValueName()->setValue(this); 317 return; 318 } 319 320 // NOTE: Could optimize for the case the name is shrinking to not deallocate 321 // then reallocated. 322 if (hasName()) { 323 // Remove old name. 324 ST->removeValueName(getValueName()); 325 destroyValueName(); 326 327 if (NameRef.empty()) 328 return; 329 } 330 331 // Name is changing to something new. 332 setValueName(ST->createValueName(NameRef, this)); 333 } 334 335 void Value::setName(const Twine &NewName) { 336 setNameImpl(NewName); 337 if (Function *F = dyn_cast<Function>(this)) 338 F->recalculateIntrinsicID(); 339 } 340 341 void Value::takeName(Value *V) { 342 ValueSymbolTable *ST = nullptr; 343 // If this value has a name, drop it. 344 if (hasName()) { 345 // Get the symtab this is in. 346 if (getSymTab(this, ST)) { 347 // We can't set a name on this value, but we need to clear V's name if 348 // it has one. 349 if (V->hasName()) V->setName(""); 350 return; // Cannot set a name on this value (e.g. constant). 351 } 352 353 // Remove old name. 354 if (ST) 355 ST->removeValueName(getValueName()); 356 destroyValueName(); 357 } 358 359 // Now we know that this has no name. 360 361 // If V has no name either, we're done. 362 if (!V->hasName()) return; 363 364 // Get this's symtab if we didn't before. 365 if (!ST) { 366 if (getSymTab(this, ST)) { 367 // Clear V's name. 368 V->setName(""); 369 return; // Cannot set a name on this value (e.g. constant). 370 } 371 } 372 373 // Get V's ST, this should always succed, because V has a name. 374 ValueSymbolTable *VST; 375 bool Failure = getSymTab(V, VST); 376 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure; 377 378 // If these values are both in the same symtab, we can do this very fast. 379 // This works even if both values have no symtab yet. 380 if (ST == VST) { 381 // Take the name! 382 setValueName(V->getValueName()); 383 V->setValueName(nullptr); 384 getValueName()->setValue(this); 385 return; 386 } 387 388 // Otherwise, things are slightly more complex. Remove V's name from VST and 389 // then reinsert it into ST. 390 391 if (VST) 392 VST->removeValueName(V->getValueName()); 393 setValueName(V->getValueName()); 394 V->setValueName(nullptr); 395 getValueName()->setValue(this); 396 397 if (ST) 398 ST->reinsertValue(this); 399 } 400 401 void Value::assertModuleIsMaterializedImpl() const { 402 #ifndef NDEBUG 403 const GlobalValue *GV = dyn_cast<GlobalValue>(this); 404 if (!GV) 405 return; 406 const Module *M = GV->getParent(); 407 if (!M) 408 return; 409 assert(M->isMaterialized()); 410 #endif 411 } 412 413 #ifndef NDEBUG 414 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr, 415 Constant *C) { 416 if (!Cache.insert(Expr).second) 417 return false; 418 419 for (auto &O : Expr->operands()) { 420 if (O == C) 421 return true; 422 auto *CE = dyn_cast<ConstantExpr>(O); 423 if (!CE) 424 continue; 425 if (contains(Cache, CE, C)) 426 return true; 427 } 428 return false; 429 } 430 431 static bool contains(Value *Expr, Value *V) { 432 if (Expr == V) 433 return true; 434 435 auto *C = dyn_cast<Constant>(V); 436 if (!C) 437 return false; 438 439 auto *CE = dyn_cast<ConstantExpr>(Expr); 440 if (!CE) 441 return false; 442 443 SmallPtrSet<ConstantExpr *, 4> Cache; 444 return contains(Cache, CE, C); 445 } 446 #endif // NDEBUG 447 448 void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) { 449 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!"); 450 assert(!contains(New, this) && 451 "this->replaceAllUsesWith(expr(this)) is NOT valid!"); 452 assert(New->getType() == getType() && 453 "replaceAllUses of value with new value of different type!"); 454 455 // Notify all ValueHandles (if present) that this value is going away. 456 if (HasValueHandle) 457 ValueHandleBase::ValueIsRAUWd(this, New); 458 if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata()) 459 ValueAsMetadata::handleRAUW(this, New); 460 461 while (!materialized_use_empty()) { 462 Use &U = *UseList; 463 // Must handle Constants specially, we cannot call replaceUsesOfWith on a 464 // constant because they are uniqued. 465 if (auto *C = dyn_cast<Constant>(U.getUser())) { 466 if (!isa<GlobalValue>(C)) { 467 C->handleOperandChange(this, New); 468 continue; 469 } 470 } 471 472 U.set(New); 473 } 474 475 if (BasicBlock *BB = dyn_cast<BasicBlock>(this)) 476 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New)); 477 } 478 479 void Value::replaceAllUsesWith(Value *New) { 480 doRAUW(New, ReplaceMetadataUses::Yes); 481 } 482 483 void Value::replaceNonMetadataUsesWith(Value *New) { 484 doRAUW(New, ReplaceMetadataUses::No); 485 } 486 487 // Like replaceAllUsesWith except it does not handle constants or basic blocks. 488 // This routine leaves uses within BB. 489 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) { 490 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!"); 491 assert(!contains(New, this) && 492 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!"); 493 assert(New->getType() == getType() && 494 "replaceUses of value with new value of different type!"); 495 assert(BB && "Basic block that may contain a use of 'New' must be defined\n"); 496 497 replaceUsesWithIf(New, [BB](Use &U) { 498 auto *I = dyn_cast<Instruction>(U.getUser()); 499 // Don't replace if it's an instruction in the BB basic block. 500 return !I || I->getParent() != BB; 501 }); 502 } 503 504 namespace { 505 // Various metrics for how much to strip off of pointers. 506 enum PointerStripKind { 507 PSK_ZeroIndices, 508 PSK_ZeroIndicesAndAliases, 509 PSK_ZeroIndicesSameRepresentation, 510 PSK_ZeroIndicesAndInvariantGroups, 511 PSK_InBoundsConstantIndices, 512 PSK_InBounds 513 }; 514 515 template <PointerStripKind StripKind> 516 static const Value *stripPointerCastsAndOffsets(const Value *V) { 517 if (!V->getType()->isPointerTy()) 518 return V; 519 520 // Even though we don't look through PHI nodes, we could be called on an 521 // instruction in an unreachable block, which may be on a cycle. 522 SmallPtrSet<const Value *, 4> Visited; 523 524 Visited.insert(V); 525 do { 526 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 527 switch (StripKind) { 528 case PSK_ZeroIndices: 529 case PSK_ZeroIndicesAndAliases: 530 case PSK_ZeroIndicesSameRepresentation: 531 case PSK_ZeroIndicesAndInvariantGroups: 532 if (!GEP->hasAllZeroIndices()) 533 return V; 534 break; 535 case PSK_InBoundsConstantIndices: 536 if (!GEP->hasAllConstantIndices()) 537 return V; 538 LLVM_FALLTHROUGH; 539 case PSK_InBounds: 540 if (!GEP->isInBounds()) 541 return V; 542 break; 543 } 544 V = GEP->getPointerOperand(); 545 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 546 V = cast<Operator>(V)->getOperand(0); 547 } else if (StripKind != PSK_ZeroIndicesSameRepresentation && 548 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 549 // TODO: If we know an address space cast will not change the 550 // representation we could look through it here as well. 551 V = cast<Operator>(V)->getOperand(0); 552 } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) { 553 V = cast<GlobalAlias>(V)->getAliasee(); 554 } else { 555 if (const auto *Call = dyn_cast<CallBase>(V)) { 556 if (const Value *RV = Call->getReturnedArgOperand()) { 557 V = RV; 558 continue; 559 } 560 // The result of launder.invariant.group must alias it's argument, 561 // but it can't be marked with returned attribute, that's why it needs 562 // special case. 563 if (StripKind == PSK_ZeroIndicesAndInvariantGroups && 564 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group || 565 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) { 566 V = Call->getArgOperand(0); 567 continue; 568 } 569 } 570 return V; 571 } 572 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 573 } while (Visited.insert(V).second); 574 575 return V; 576 } 577 } // end anonymous namespace 578 579 const Value *Value::stripPointerCasts() const { 580 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this); 581 } 582 583 const Value *Value::stripPointerCastsAndAliases() const { 584 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this); 585 } 586 587 const Value *Value::stripPointerCastsSameRepresentation() const { 588 return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this); 589 } 590 591 const Value *Value::stripInBoundsConstantOffsets() const { 592 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this); 593 } 594 595 const Value *Value::stripPointerCastsAndInvariantGroups() const { 596 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this); 597 } 598 599 const Value * 600 Value::stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, 601 bool AllowNonInbounds) const { 602 if (!getType()->isPtrOrPtrVectorTy()) 603 return this; 604 605 unsigned BitWidth = Offset.getBitWidth(); 606 assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) && 607 "The offset bit width does not match the DL specification."); 608 609 // Even though we don't look through PHI nodes, we could be called on an 610 // instruction in an unreachable block, which may be on a cycle. 611 SmallPtrSet<const Value *, 4> Visited; 612 Visited.insert(this); 613 const Value *V = this; 614 do { 615 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 616 // If in-bounds was requested, we do not strip non-in-bounds GEPs. 617 if (!AllowNonInbounds && !GEP->isInBounds()) 618 return V; 619 620 // If one of the values we have visited is an addrspacecast, then 621 // the pointer type of this GEP may be different from the type 622 // of the Ptr parameter which was passed to this function. This 623 // means when we construct GEPOffset, we need to use the size 624 // of GEP's pointer type rather than the size of the original 625 // pointer type. 626 APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0); 627 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 628 return V; 629 630 // Stop traversal if the pointer offset wouldn't fit in the bit-width 631 // provided by the Offset argument. This can happen due to AddrSpaceCast 632 // stripping. 633 if (GEPOffset.getMinSignedBits() > BitWidth) 634 return V; 635 636 Offset += GEPOffset.sextOrTrunc(BitWidth); 637 V = GEP->getPointerOperand(); 638 } else if (Operator::getOpcode(V) == Instruction::BitCast || 639 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 640 V = cast<Operator>(V)->getOperand(0); 641 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 642 if (!GA->isInterposable()) 643 V = GA->getAliasee(); 644 } else if (const auto *Call = dyn_cast<CallBase>(V)) { 645 if (const Value *RV = Call->getReturnedArgOperand()) 646 V = RV; 647 } 648 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 649 } while (Visited.insert(V).second); 650 651 return V; 652 } 653 654 const Value *Value::stripInBoundsOffsets() const { 655 return stripPointerCastsAndOffsets<PSK_InBounds>(this); 656 } 657 658 uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL, 659 bool &CanBeNull) const { 660 assert(getType()->isPointerTy() && "must be pointer"); 661 662 uint64_t DerefBytes = 0; 663 CanBeNull = false; 664 if (const Argument *A = dyn_cast<Argument>(this)) { 665 DerefBytes = A->getDereferenceableBytes(); 666 if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) { 667 Type *PT = cast<PointerType>(A->getType())->getElementType(); 668 if (PT->isSized()) 669 DerefBytes = DL.getTypeStoreSize(PT).getKnownMinSize(); 670 } 671 if (DerefBytes == 0) { 672 DerefBytes = A->getDereferenceableOrNullBytes(); 673 CanBeNull = true; 674 } 675 } else if (const auto *Call = dyn_cast<CallBase>(this)) { 676 DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex); 677 if (DerefBytes == 0) { 678 DerefBytes = 679 Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex); 680 CanBeNull = true; 681 } 682 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 683 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) { 684 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 685 DerefBytes = CI->getLimitedValue(); 686 } 687 if (DerefBytes == 0) { 688 if (MDNode *MD = 689 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 690 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 691 DerefBytes = CI->getLimitedValue(); 692 } 693 CanBeNull = true; 694 } 695 } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) { 696 if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) { 697 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 698 DerefBytes = CI->getLimitedValue(); 699 } 700 if (DerefBytes == 0) { 701 if (MDNode *MD = 702 IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 703 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 704 DerefBytes = CI->getLimitedValue(); 705 } 706 CanBeNull = true; 707 } 708 } else if (auto *AI = dyn_cast<AllocaInst>(this)) { 709 if (!AI->isArrayAllocation()) { 710 DerefBytes = 711 DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize(); 712 CanBeNull = false; 713 } 714 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) { 715 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) { 716 // TODO: Don't outright reject hasExternalWeakLinkage but set the 717 // CanBeNull flag. 718 DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize(); 719 CanBeNull = false; 720 } 721 } 722 return DerefBytes; 723 } 724 725 MaybeAlign Value::getPointerAlignment(const DataLayout &DL) const { 726 assert(getType()->isPointerTy() && "must be pointer"); 727 if (auto *GO = dyn_cast<GlobalObject>(this)) { 728 if (isa<Function>(GO)) { 729 const MaybeAlign FunctionPtrAlign = DL.getFunctionPtrAlign(); 730 switch (DL.getFunctionPtrAlignType()) { 731 case DataLayout::FunctionPtrAlignType::Independent: 732 return FunctionPtrAlign; 733 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign: 734 return std::max(FunctionPtrAlign, MaybeAlign(GO->getAlignment())); 735 } 736 llvm_unreachable("Unhandled FunctionPtrAlignType"); 737 } 738 const MaybeAlign Alignment(GO->getAlignment()); 739 if (!Alignment) { 740 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 741 Type *ObjectType = GVar->getValueType(); 742 if (ObjectType->isSized()) { 743 // If the object is defined in the current Module, we'll be giving 744 // it the preferred alignment. Otherwise, we have to assume that it 745 // may only have the minimum ABI alignment. 746 if (GVar->isStrongDefinitionForLinker()) 747 return MaybeAlign(DL.getPreferredAlignment(GVar)); 748 else 749 return Align(DL.getABITypeAlignment(ObjectType)); 750 } 751 } 752 } 753 return Alignment; 754 } else if (const Argument *A = dyn_cast<Argument>(this)) { 755 const MaybeAlign Alignment(A->getParamAlignment()); 756 if (!Alignment && A->hasStructRetAttr()) { 757 // An sret parameter has at least the ABI alignment of the return type. 758 Type *EltTy = cast<PointerType>(A->getType())->getElementType(); 759 if (EltTy->isSized()) 760 return Align(DL.getABITypeAlignment(EltTy)); 761 } 762 return Alignment; 763 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) { 764 const MaybeAlign Alignment(AI->getAlignment()); 765 if (!Alignment) { 766 Type *AllocatedType = AI->getAllocatedType(); 767 if (AllocatedType->isSized()) 768 return MaybeAlign(DL.getPrefTypeAlignment(AllocatedType)); 769 } 770 return Alignment; 771 } else if (const auto *Call = dyn_cast<CallBase>(this)) { 772 const MaybeAlign Alignment(Call->getRetAlignment()); 773 if (!Alignment && Call->getCalledFunction()) 774 return MaybeAlign( 775 Call->getCalledFunction()->getAttributes().getRetAlignment()); 776 return Alignment; 777 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 778 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) { 779 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 780 return MaybeAlign(CI->getLimitedValue()); 781 } 782 } else if (auto *CstPtr = dyn_cast<Constant>(this)) { 783 if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt( 784 const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()), 785 /*OnlyIfReduced=*/true))) { 786 size_t TrailingZeros = CstInt->getValue().countTrailingZeros(); 787 // While the actual alignment may be large, elsewhere we have 788 // an arbitrary upper alignmet limit, so let's clamp to it. 789 return Align(TrailingZeros < Value::MaxAlignmentExponent 790 ? uint64_t(1) << TrailingZeros 791 : Value::MaximumAlignment); 792 } 793 } 794 return llvm::None; 795 } 796 797 const Value *Value::DoPHITranslation(const BasicBlock *CurBB, 798 const BasicBlock *PredBB) const { 799 auto *PN = dyn_cast<PHINode>(this); 800 if (PN && PN->getParent() == CurBB) 801 return PN->getIncomingValueForBlock(PredBB); 802 return this; 803 } 804 805 LLVMContext &Value::getContext() const { return VTy->getContext(); } 806 807 void Value::reverseUseList() { 808 if (!UseList || !UseList->Next) 809 // No need to reverse 0 or 1 uses. 810 return; 811 812 Use *Head = UseList; 813 Use *Current = UseList->Next; 814 Head->Next = nullptr; 815 while (Current) { 816 Use *Next = Current->Next; 817 Current->Next = Head; 818 Head->setPrev(&Current->Next); 819 Head = Current; 820 Current = Next; 821 } 822 UseList = Head; 823 Head->setPrev(&UseList); 824 } 825 826 bool Value::isSwiftError() const { 827 auto *Arg = dyn_cast<Argument>(this); 828 if (Arg) 829 return Arg->hasSwiftErrorAttr(); 830 auto *Alloca = dyn_cast<AllocaInst>(this); 831 if (!Alloca) 832 return false; 833 return Alloca->isSwiftError(); 834 } 835 836 //===----------------------------------------------------------------------===// 837 // ValueHandleBase Class 838 //===----------------------------------------------------------------------===// 839 840 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) { 841 assert(List && "Handle list is null?"); 842 843 // Splice ourselves into the list. 844 Next = *List; 845 *List = this; 846 setPrevPtr(List); 847 if (Next) { 848 Next->setPrevPtr(&Next); 849 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?"); 850 } 851 } 852 853 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) { 854 assert(List && "Must insert after existing node"); 855 856 Next = List->Next; 857 setPrevPtr(&List->Next); 858 List->Next = this; 859 if (Next) 860 Next->setPrevPtr(&Next); 861 } 862 863 void ValueHandleBase::AddToUseList() { 864 assert(getValPtr() && "Null pointer doesn't have a use list!"); 865 866 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 867 868 if (getValPtr()->HasValueHandle) { 869 // If this value already has a ValueHandle, then it must be in the 870 // ValueHandles map already. 871 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()]; 872 assert(Entry && "Value doesn't have any handles?"); 873 AddToExistingUseList(&Entry); 874 return; 875 } 876 877 // Ok, it doesn't have any handles yet, so we must insert it into the 878 // DenseMap. However, doing this insertion could cause the DenseMap to 879 // reallocate itself, which would invalidate all of the PrevP pointers that 880 // point into the old table. Handle this by checking for reallocation and 881 // updating the stale pointers only if needed. 882 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 883 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray(); 884 885 ValueHandleBase *&Entry = Handles[getValPtr()]; 886 assert(!Entry && "Value really did already have handles?"); 887 AddToExistingUseList(&Entry); 888 getValPtr()->HasValueHandle = true; 889 890 // If reallocation didn't happen or if this was the first insertion, don't 891 // walk the table. 892 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 893 Handles.size() == 1) { 894 return; 895 } 896 897 // Okay, reallocation did happen. Fix the Prev Pointers. 898 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(), 899 E = Handles.end(); I != E; ++I) { 900 assert(I->second && I->first == I->second->getValPtr() && 901 "List invariant broken!"); 902 I->second->setPrevPtr(&I->second); 903 } 904 } 905 906 void ValueHandleBase::RemoveFromUseList() { 907 assert(getValPtr() && getValPtr()->HasValueHandle && 908 "Pointer doesn't have a use list!"); 909 910 // Unlink this from its use list. 911 ValueHandleBase **PrevPtr = getPrevPtr(); 912 assert(*PrevPtr == this && "List invariant broken"); 913 914 *PrevPtr = Next; 915 if (Next) { 916 assert(Next->getPrevPtr() == &Next && "List invariant broken"); 917 Next->setPrevPtr(PrevPtr); 918 return; 919 } 920 921 // If the Next pointer was null, then it is possible that this was the last 922 // ValueHandle watching VP. If so, delete its entry from the ValueHandles 923 // map. 924 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 925 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 926 if (Handles.isPointerIntoBucketsArray(PrevPtr)) { 927 Handles.erase(getValPtr()); 928 getValPtr()->HasValueHandle = false; 929 } 930 } 931 932 void ValueHandleBase::ValueIsDeleted(Value *V) { 933 assert(V->HasValueHandle && "Should only be called if ValueHandles present"); 934 935 // Get the linked list base, which is guaranteed to exist since the 936 // HasValueHandle flag is set. 937 LLVMContextImpl *pImpl = V->getContext().pImpl; 938 ValueHandleBase *Entry = pImpl->ValueHandles[V]; 939 assert(Entry && "Value bit set but no entries exist"); 940 941 // We use a local ValueHandleBase as an iterator so that ValueHandles can add 942 // and remove themselves from the list without breaking our iteration. This 943 // is not really an AssertingVH; we just have to give ValueHandleBase a kind. 944 // Note that we deliberately do not the support the case when dropping a value 945 // handle results in a new value handle being permanently added to the list 946 // (as might occur in theory for CallbackVH's): the new value handle will not 947 // be processed and the checking code will mete out righteous punishment if 948 // the handle is still present once we have finished processing all the other 949 // value handles (it is fine to momentarily add then remove a value handle). 950 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 951 Iterator.RemoveFromUseList(); 952 Iterator.AddToExistingUseListAfter(Entry); 953 assert(Entry->Next == &Iterator && "Loop invariant broken."); 954 955 switch (Entry->getKind()) { 956 case Assert: 957 break; 958 case Weak: 959 case WeakTracking: 960 // WeakTracking and Weak just go to null, which unlinks them 961 // from the list. 962 Entry->operator=(nullptr); 963 break; 964 case Callback: 965 // Forward to the subclass's implementation. 966 static_cast<CallbackVH*>(Entry)->deleted(); 967 break; 968 } 969 } 970 971 // All callbacks, weak references, and assertingVHs should be dropped by now. 972 if (V->HasValueHandle) { 973 #ifndef NDEBUG // Only in +Asserts mode... 974 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName() 975 << "\n"; 976 if (pImpl->ValueHandles[V]->getKind() == Assert) 977 llvm_unreachable("An asserting value handle still pointed to this" 978 " value!"); 979 980 #endif 981 llvm_unreachable("All references to V were not removed?"); 982 } 983 } 984 985 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) { 986 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present"); 987 assert(Old != New && "Changing value into itself!"); 988 assert(Old->getType() == New->getType() && 989 "replaceAllUses of value with new value of different type!"); 990 991 // Get the linked list base, which is guaranteed to exist since the 992 // HasValueHandle flag is set. 993 LLVMContextImpl *pImpl = Old->getContext().pImpl; 994 ValueHandleBase *Entry = pImpl->ValueHandles[Old]; 995 996 assert(Entry && "Value bit set but no entries exist"); 997 998 // We use a local ValueHandleBase as an iterator so that 999 // ValueHandles can add and remove themselves from the list without 1000 // breaking our iteration. This is not really an AssertingVH; we 1001 // just have to give ValueHandleBase some kind. 1002 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 1003 Iterator.RemoveFromUseList(); 1004 Iterator.AddToExistingUseListAfter(Entry); 1005 assert(Entry->Next == &Iterator && "Loop invariant broken."); 1006 1007 switch (Entry->getKind()) { 1008 case Assert: 1009 case Weak: 1010 // Asserting and Weak handles do not follow RAUW implicitly. 1011 break; 1012 case WeakTracking: 1013 // Weak goes to the new value, which will unlink it from Old's list. 1014 Entry->operator=(New); 1015 break; 1016 case Callback: 1017 // Forward to the subclass's implementation. 1018 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New); 1019 break; 1020 } 1021 } 1022 1023 #ifndef NDEBUG 1024 // If any new weak value handles were added while processing the 1025 // list, then complain about it now. 1026 if (Old->HasValueHandle) 1027 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next) 1028 switch (Entry->getKind()) { 1029 case WeakTracking: 1030 dbgs() << "After RAUW from " << *Old->getType() << " %" 1031 << Old->getName() << " to " << *New->getType() << " %" 1032 << New->getName() << "\n"; 1033 llvm_unreachable( 1034 "A weak tracking value handle still pointed to the old value!\n"); 1035 default: 1036 break; 1037 } 1038 #endif 1039 } 1040 1041 // Pin the vtable to this file. 1042 void CallbackVH::anchor() {} 1043