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