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