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