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