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