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> static void NoopCallback(const Value *) {} 519 520 template <PointerStripKind StripKind> 521 static const Value *stripPointerCastsAndOffsets( 522 const Value *V, 523 function_ref<void(const Value *)> Func = NoopCallback<StripKind>) { 524 if (!V->getType()->isPointerTy()) 525 return V; 526 527 // Even though we don't look through PHI nodes, we could be called on an 528 // instruction in an unreachable block, which may be on a cycle. 529 SmallPtrSet<const Value *, 4> Visited; 530 531 Visited.insert(V); 532 do { 533 Func(V); 534 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 535 switch (StripKind) { 536 case PSK_ZeroIndices: 537 case PSK_ZeroIndicesAndAliases: 538 case PSK_ZeroIndicesSameRepresentation: 539 case PSK_ZeroIndicesAndInvariantGroups: 540 if (!GEP->hasAllZeroIndices()) 541 return V; 542 break; 543 case PSK_InBoundsConstantIndices: 544 if (!GEP->hasAllConstantIndices()) 545 return V; 546 LLVM_FALLTHROUGH; 547 case PSK_InBounds: 548 if (!GEP->isInBounds()) 549 return V; 550 break; 551 } 552 V = GEP->getPointerOperand(); 553 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 554 V = cast<Operator>(V)->getOperand(0); 555 if (!V->getType()->isPointerTy()) 556 return V; 557 } else if (StripKind != PSK_ZeroIndicesSameRepresentation && 558 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 559 // TODO: If we know an address space cast will not change the 560 // representation we could look through it here as well. 561 V = cast<Operator>(V)->getOperand(0); 562 } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) { 563 V = cast<GlobalAlias>(V)->getAliasee(); 564 } else { 565 if (const auto *Call = dyn_cast<CallBase>(V)) { 566 if (const Value *RV = Call->getReturnedArgOperand()) { 567 V = RV; 568 continue; 569 } 570 // The result of launder.invariant.group must alias it's argument, 571 // but it can't be marked with returned attribute, that's why it needs 572 // special case. 573 if (StripKind == PSK_ZeroIndicesAndInvariantGroups && 574 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group || 575 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) { 576 V = Call->getArgOperand(0); 577 continue; 578 } 579 } 580 return V; 581 } 582 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 583 } while (Visited.insert(V).second); 584 585 return V; 586 } 587 } // end anonymous namespace 588 589 const Value *Value::stripPointerCasts() const { 590 return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this); 591 } 592 593 const Value *Value::stripPointerCastsAndAliases() const { 594 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this); 595 } 596 597 const Value *Value::stripPointerCastsSameRepresentation() const { 598 return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this); 599 } 600 601 const Value *Value::stripInBoundsConstantOffsets() const { 602 return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this); 603 } 604 605 const Value *Value::stripPointerCastsAndInvariantGroups() const { 606 return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndInvariantGroups>(this); 607 } 608 609 const Value *Value::stripAndAccumulateConstantOffsets( 610 const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, 611 function_ref<bool(Value &, APInt &)> ExternalAnalysis) const { 612 if (!getType()->isPtrOrPtrVectorTy()) 613 return this; 614 615 unsigned BitWidth = Offset.getBitWidth(); 616 assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) && 617 "The offset bit width does not match the DL specification."); 618 619 // Even though we don't look through PHI nodes, we could be called on an 620 // instruction in an unreachable block, which may be on a cycle. 621 SmallPtrSet<const Value *, 4> Visited; 622 Visited.insert(this); 623 const Value *V = this; 624 do { 625 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 626 // If in-bounds was requested, we do not strip non-in-bounds GEPs. 627 if (!AllowNonInbounds && !GEP->isInBounds()) 628 return V; 629 630 // If one of the values we have visited is an addrspacecast, then 631 // the pointer type of this GEP may be different from the type 632 // of the Ptr parameter which was passed to this function. This 633 // means when we construct GEPOffset, we need to use the size 634 // of GEP's pointer type rather than the size of the original 635 // pointer type. 636 APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0); 637 if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis)) 638 return V; 639 640 // Stop traversal if the pointer offset wouldn't fit in the bit-width 641 // provided by the Offset argument. This can happen due to AddrSpaceCast 642 // stripping. 643 if (GEPOffset.getMinSignedBits() > BitWidth) 644 return V; 645 646 // External Analysis can return a result higher/lower than the value 647 // represents. We need to detect overflow/underflow. 648 APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth); 649 if (!ExternalAnalysis) { 650 Offset += GEPOffsetST; 651 } else { 652 bool Overflow = false; 653 APInt OldOffset = Offset; 654 Offset = Offset.sadd_ov(GEPOffsetST, Overflow); 655 if (Overflow) { 656 Offset = OldOffset; 657 return V; 658 } 659 } 660 V = GEP->getPointerOperand(); 661 } else if (Operator::getOpcode(V) == Instruction::BitCast || 662 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 663 V = cast<Operator>(V)->getOperand(0); 664 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 665 if (!GA->isInterposable()) 666 V = GA->getAliasee(); 667 } else if (const auto *Call = dyn_cast<CallBase>(V)) { 668 if (const Value *RV = Call->getReturnedArgOperand()) 669 V = RV; 670 } 671 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 672 } while (Visited.insert(V).second); 673 674 return V; 675 } 676 677 const Value * 678 Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const { 679 return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func); 680 } 681 682 uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL, 683 bool &CanBeNull) const { 684 assert(getType()->isPointerTy() && "must be pointer"); 685 686 uint64_t DerefBytes = 0; 687 CanBeNull = false; 688 if (const Argument *A = dyn_cast<Argument>(this)) { 689 DerefBytes = A->getDereferenceableBytes(); 690 if (DerefBytes == 0 && (A->hasByValAttr() || A->hasStructRetAttr())) { 691 Type *PT = cast<PointerType>(A->getType())->getElementType(); 692 if (PT->isSized()) 693 DerefBytes = DL.getTypeStoreSize(PT).getKnownMinSize(); 694 } 695 if (DerefBytes == 0) { 696 DerefBytes = A->getDereferenceableOrNullBytes(); 697 CanBeNull = true; 698 } 699 } else if (const auto *Call = dyn_cast<CallBase>(this)) { 700 DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex); 701 if (DerefBytes == 0) { 702 DerefBytes = 703 Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex); 704 CanBeNull = true; 705 } 706 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 707 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) { 708 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 709 DerefBytes = CI->getLimitedValue(); 710 } 711 if (DerefBytes == 0) { 712 if (MDNode *MD = 713 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 714 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 715 DerefBytes = CI->getLimitedValue(); 716 } 717 CanBeNull = true; 718 } 719 } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) { 720 if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) { 721 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 722 DerefBytes = CI->getLimitedValue(); 723 } 724 if (DerefBytes == 0) { 725 if (MDNode *MD = 726 IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) { 727 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 728 DerefBytes = CI->getLimitedValue(); 729 } 730 CanBeNull = true; 731 } 732 } else if (auto *AI = dyn_cast<AllocaInst>(this)) { 733 if (!AI->isArrayAllocation()) { 734 DerefBytes = 735 DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize(); 736 CanBeNull = false; 737 } 738 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) { 739 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) { 740 // TODO: Don't outright reject hasExternalWeakLinkage but set the 741 // CanBeNull flag. 742 DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize(); 743 CanBeNull = false; 744 } 745 } 746 return DerefBytes; 747 } 748 749 Align Value::getPointerAlignment(const DataLayout &DL) const { 750 assert(getType()->isPointerTy() && "must be pointer"); 751 if (auto *GO = dyn_cast<GlobalObject>(this)) { 752 if (isa<Function>(GO)) { 753 Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne(); 754 switch (DL.getFunctionPtrAlignType()) { 755 case DataLayout::FunctionPtrAlignType::Independent: 756 return FunctionPtrAlign; 757 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign: 758 return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne()); 759 } 760 llvm_unreachable("Unhandled FunctionPtrAlignType"); 761 } 762 const MaybeAlign Alignment(GO->getAlignment()); 763 if (!Alignment) { 764 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) { 765 Type *ObjectType = GVar->getValueType(); 766 if (ObjectType->isSized()) { 767 // If the object is defined in the current Module, we'll be giving 768 // it the preferred alignment. Otherwise, we have to assume that it 769 // may only have the minimum ABI alignment. 770 if (GVar->isStrongDefinitionForLinker()) 771 return DL.getPreferredAlign(GVar); 772 else 773 return DL.getABITypeAlign(ObjectType); 774 } 775 } 776 } 777 return Alignment.valueOrOne(); 778 } else if (const Argument *A = dyn_cast<Argument>(this)) { 779 const MaybeAlign Alignment = A->getParamAlign(); 780 if (!Alignment && A->hasStructRetAttr()) { 781 // An sret parameter has at least the ABI alignment of the return type. 782 Type *EltTy = cast<PointerType>(A->getType())->getElementType(); 783 if (EltTy->isSized()) 784 return DL.getABITypeAlign(EltTy); 785 } 786 return Alignment.valueOrOne(); 787 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) { 788 return AI->getAlign(); 789 } else if (const auto *Call = dyn_cast<CallBase>(this)) { 790 MaybeAlign Alignment = Call->getRetAlign(); 791 if (!Alignment && Call->getCalledFunction()) 792 Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment(); 793 return Alignment.valueOrOne(); 794 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) { 795 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) { 796 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0)); 797 return Align(CI->getLimitedValue()); 798 } 799 } else if (auto *CstPtr = dyn_cast<Constant>(this)) { 800 if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt( 801 const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()), 802 /*OnlyIfReduced=*/true))) { 803 size_t TrailingZeros = CstInt->getValue().countTrailingZeros(); 804 // While the actual alignment may be large, elsewhere we have 805 // an arbitrary upper alignmet limit, so let's clamp to it. 806 return Align(TrailingZeros < Value::MaxAlignmentExponent 807 ? uint64_t(1) << TrailingZeros 808 : Value::MaximumAlignment); 809 } 810 } 811 return Align(1); 812 } 813 814 const Value *Value::DoPHITranslation(const BasicBlock *CurBB, 815 const BasicBlock *PredBB) const { 816 auto *PN = dyn_cast<PHINode>(this); 817 if (PN && PN->getParent() == CurBB) 818 return PN->getIncomingValueForBlock(PredBB); 819 return this; 820 } 821 822 LLVMContext &Value::getContext() const { return VTy->getContext(); } 823 824 void Value::reverseUseList() { 825 if (!UseList || !UseList->Next) 826 // No need to reverse 0 or 1 uses. 827 return; 828 829 Use *Head = UseList; 830 Use *Current = UseList->Next; 831 Head->Next = nullptr; 832 while (Current) { 833 Use *Next = Current->Next; 834 Current->Next = Head; 835 Head->Prev = &Current->Next; 836 Head = Current; 837 Current = Next; 838 } 839 UseList = Head; 840 Head->Prev = &UseList; 841 } 842 843 bool Value::isSwiftError() const { 844 auto *Arg = dyn_cast<Argument>(this); 845 if (Arg) 846 return Arg->hasSwiftErrorAttr(); 847 auto *Alloca = dyn_cast<AllocaInst>(this); 848 if (!Alloca) 849 return false; 850 return Alloca->isSwiftError(); 851 } 852 853 //===----------------------------------------------------------------------===// 854 // ValueHandleBase Class 855 //===----------------------------------------------------------------------===// 856 857 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) { 858 assert(List && "Handle list is null?"); 859 860 // Splice ourselves into the list. 861 Next = *List; 862 *List = this; 863 setPrevPtr(List); 864 if (Next) { 865 Next->setPrevPtr(&Next); 866 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?"); 867 } 868 } 869 870 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) { 871 assert(List && "Must insert after existing node"); 872 873 Next = List->Next; 874 setPrevPtr(&List->Next); 875 List->Next = this; 876 if (Next) 877 Next->setPrevPtr(&Next); 878 } 879 880 void ValueHandleBase::AddToUseList() { 881 assert(getValPtr() && "Null pointer doesn't have a use list!"); 882 883 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 884 885 if (getValPtr()->HasValueHandle) { 886 // If this value already has a ValueHandle, then it must be in the 887 // ValueHandles map already. 888 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()]; 889 assert(Entry && "Value doesn't have any handles?"); 890 AddToExistingUseList(&Entry); 891 return; 892 } 893 894 // Ok, it doesn't have any handles yet, so we must insert it into the 895 // DenseMap. However, doing this insertion could cause the DenseMap to 896 // reallocate itself, which would invalidate all of the PrevP pointers that 897 // point into the old table. Handle this by checking for reallocation and 898 // updating the stale pointers only if needed. 899 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 900 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray(); 901 902 ValueHandleBase *&Entry = Handles[getValPtr()]; 903 assert(!Entry && "Value really did already have handles?"); 904 AddToExistingUseList(&Entry); 905 getValPtr()->HasValueHandle = true; 906 907 // If reallocation didn't happen or if this was the first insertion, don't 908 // walk the table. 909 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) || 910 Handles.size() == 1) { 911 return; 912 } 913 914 // Okay, reallocation did happen. Fix the Prev Pointers. 915 for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(), 916 E = Handles.end(); I != E; ++I) { 917 assert(I->second && I->first == I->second->getValPtr() && 918 "List invariant broken!"); 919 I->second->setPrevPtr(&I->second); 920 } 921 } 922 923 void ValueHandleBase::RemoveFromUseList() { 924 assert(getValPtr() && getValPtr()->HasValueHandle && 925 "Pointer doesn't have a use list!"); 926 927 // Unlink this from its use list. 928 ValueHandleBase **PrevPtr = getPrevPtr(); 929 assert(*PrevPtr == this && "List invariant broken"); 930 931 *PrevPtr = Next; 932 if (Next) { 933 assert(Next->getPrevPtr() == &Next && "List invariant broken"); 934 Next->setPrevPtr(PrevPtr); 935 return; 936 } 937 938 // If the Next pointer was null, then it is possible that this was the last 939 // ValueHandle watching VP. If so, delete its entry from the ValueHandles 940 // map. 941 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl; 942 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles; 943 if (Handles.isPointerIntoBucketsArray(PrevPtr)) { 944 Handles.erase(getValPtr()); 945 getValPtr()->HasValueHandle = false; 946 } 947 } 948 949 void ValueHandleBase::ValueIsDeleted(Value *V) { 950 assert(V->HasValueHandle && "Should only be called if ValueHandles present"); 951 952 // Get the linked list base, which is guaranteed to exist since the 953 // HasValueHandle flag is set. 954 LLVMContextImpl *pImpl = V->getContext().pImpl; 955 ValueHandleBase *Entry = pImpl->ValueHandles[V]; 956 assert(Entry && "Value bit set but no entries exist"); 957 958 // We use a local ValueHandleBase as an iterator so that ValueHandles can add 959 // and remove themselves from the list without breaking our iteration. This 960 // is not really an AssertingVH; we just have to give ValueHandleBase a kind. 961 // Note that we deliberately do not the support the case when dropping a value 962 // handle results in a new value handle being permanently added to the list 963 // (as might occur in theory for CallbackVH's): the new value handle will not 964 // be processed and the checking code will mete out righteous punishment if 965 // the handle is still present once we have finished processing all the other 966 // value handles (it is fine to momentarily add then remove a value handle). 967 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 968 Iterator.RemoveFromUseList(); 969 Iterator.AddToExistingUseListAfter(Entry); 970 assert(Entry->Next == &Iterator && "Loop invariant broken."); 971 972 switch (Entry->getKind()) { 973 case Assert: 974 break; 975 case Weak: 976 case WeakTracking: 977 // WeakTracking and Weak just go to null, which unlinks them 978 // from the list. 979 Entry->operator=(nullptr); 980 break; 981 case Callback: 982 // Forward to the subclass's implementation. 983 static_cast<CallbackVH*>(Entry)->deleted(); 984 break; 985 } 986 } 987 988 // All callbacks, weak references, and assertingVHs should be dropped by now. 989 if (V->HasValueHandle) { 990 #ifndef NDEBUG // Only in +Asserts mode... 991 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName() 992 << "\n"; 993 if (pImpl->ValueHandles[V]->getKind() == Assert) 994 llvm_unreachable("An asserting value handle still pointed to this" 995 " value!"); 996 997 #endif 998 llvm_unreachable("All references to V were not removed?"); 999 } 1000 } 1001 1002 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) { 1003 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present"); 1004 assert(Old != New && "Changing value into itself!"); 1005 assert(Old->getType() == New->getType() && 1006 "replaceAllUses of value with new value of different type!"); 1007 1008 // Get the linked list base, which is guaranteed to exist since the 1009 // HasValueHandle flag is set. 1010 LLVMContextImpl *pImpl = Old->getContext().pImpl; 1011 ValueHandleBase *Entry = pImpl->ValueHandles[Old]; 1012 1013 assert(Entry && "Value bit set but no entries exist"); 1014 1015 // We use a local ValueHandleBase as an iterator so that 1016 // ValueHandles can add and remove themselves from the list without 1017 // breaking our iteration. This is not really an AssertingVH; we 1018 // just have to give ValueHandleBase some kind. 1019 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) { 1020 Iterator.RemoveFromUseList(); 1021 Iterator.AddToExistingUseListAfter(Entry); 1022 assert(Entry->Next == &Iterator && "Loop invariant broken."); 1023 1024 switch (Entry->getKind()) { 1025 case Assert: 1026 case Weak: 1027 // Asserting and Weak handles do not follow RAUW implicitly. 1028 break; 1029 case WeakTracking: 1030 // Weak goes to the new value, which will unlink it from Old's list. 1031 Entry->operator=(New); 1032 break; 1033 case Callback: 1034 // Forward to the subclass's implementation. 1035 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New); 1036 break; 1037 } 1038 } 1039 1040 #ifndef NDEBUG 1041 // If any new weak value handles were added while processing the 1042 // list, then complain about it now. 1043 if (Old->HasValueHandle) 1044 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next) 1045 switch (Entry->getKind()) { 1046 case WeakTracking: 1047 dbgs() << "After RAUW from " << *Old->getType() << " %" 1048 << Old->getName() << " to " << *New->getType() << " %" 1049 << New->getName() << "\n"; 1050 llvm_unreachable( 1051 "A weak tracking value handle still pointed to the old value!\n"); 1052 default: 1053 break; 1054 } 1055 #endif 1056 } 1057 1058 // Pin the vtable to this file. 1059 void CallbackVH::anchor() {} 1060