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