xref: /llvm-project-15.0.7/llvm/lib/IR/Value.cpp (revision f84dbd2f)
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/DebugInfo.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/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> UseDerefAtPointSemantics(
42     "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(false),
43     cl::desc("Deref attributes and metadata infer facts at definition only"));
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), HasValueHandle(0),
55       SubclassOptionalData(0), SubclassData(0), NumUserOperands(0),
56       IsUsedByMD(false), HasName(false), HasMetadata(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   unsigned OpCode = 0;
62   if (SubclassID >= InstructionVal)
63     OpCode = SubclassID - InstructionVal;
64   if (OpCode == Instruction::Call || OpCode == Instruction::Invoke ||
65       OpCode == Instruction::CallBr)
66     assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
67            "invalid CallBase type!");
68   else if (SubclassID != BasicBlockVal &&
69            (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
70     assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
71            "Cannot create non-first-class values except for constants!");
72   static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
73                 "Value too big");
74 }
75 
76 Value::~Value() {
77   // Notify all ValueHandles (if present) that this value is going away.
78   if (HasValueHandle)
79     ValueHandleBase::ValueIsDeleted(this);
80   if (isUsedByMetadata())
81     ValueAsMetadata::handleDeletion(this);
82 
83   // Remove associated metadata from context.
84   if (HasMetadata)
85     clearMetadata();
86 
87 #ifndef NDEBUG      // Only in -g mode...
88   // Check to make sure that there are no uses of this value that are still
89   // around when the value is destroyed.  If there are, then we have a dangling
90   // reference and something is wrong.  This code is here to print out where
91   // the value is still being referenced.
92   //
93   // Note that use_empty() cannot be called here, as it eventually downcasts
94   // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
95   // been destructed, so accessing it is UB.
96   //
97   if (!materialized_use_empty()) {
98     dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
99     for (auto *U : users())
100       dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
101   }
102 #endif
103   assert(materialized_use_empty() && "Uses remain when a value is destroyed!");
104 
105   // If this value is named, destroy the name.  This should not be in a symtab
106   // at this point.
107   destroyValueName();
108 }
109 
110 void Value::deleteValue() {
111   switch (getValueID()) {
112 #define HANDLE_VALUE(Name)                                                     \
113   case Value::Name##Val:                                                       \
114     delete static_cast<Name *>(this);                                          \
115     break;
116 #define HANDLE_MEMORY_VALUE(Name)                                              \
117   case Value::Name##Val:                                                       \
118     static_cast<DerivedUser *>(this)->DeleteValue(                             \
119         static_cast<DerivedUser *>(this));                                     \
120     break;
121 #define HANDLE_CONSTANT(Name)                                                  \
122   case Value::Name##Val:                                                       \
123     llvm_unreachable("constants should be destroyed with destroyConstant");    \
124     break;
125 #define HANDLE_INSTRUCTION(Name)  /* nothing */
126 #include "llvm/IR/Value.def"
127 
128 #define HANDLE_INST(N, OPC, CLASS)                                             \
129   case Value::InstructionVal + Instruction::OPC:                               \
130     delete static_cast<CLASS *>(this);                                         \
131     break;
132 #define HANDLE_USER_INST(N, OPC, CLASS)
133 #include "llvm/IR/Instruction.def"
134 
135   default:
136     llvm_unreachable("attempting to delete unknown value kind");
137   }
138 }
139 
140 void Value::destroyValueName() {
141   ValueName *Name = getValueName();
142   if (Name) {
143     MallocAllocator Allocator;
144     Name->Destroy(Allocator);
145   }
146   setValueName(nullptr);
147 }
148 
149 bool Value::hasNUses(unsigned N) const {
150   return hasNItems(use_begin(), use_end(), N);
151 }
152 
153 bool Value::hasNUsesOrMore(unsigned N) const {
154   return hasNItemsOrMore(use_begin(), use_end(), N);
155 }
156 
157 bool Value::hasOneUser() const {
158   if (use_empty())
159     return false;
160   if (hasOneUse())
161     return true;
162   return std::equal(++user_begin(), user_end(), user_begin());
163 }
164 
165 static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
166 
167 Use *Value::getSingleUndroppableUse() {
168   Use *Result = nullptr;
169   for (Use &U : uses()) {
170     if (!U.getUser()->isDroppable()) {
171       if (Result)
172         return nullptr;
173       Result = &U;
174     }
175   }
176   return Result;
177 }
178 
179 bool Value::hasNUndroppableUses(unsigned int N) const {
180   return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
181 }
182 
183 bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
184   return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
185 }
186 
187 void Value::dropDroppableUses(
188     llvm::function_ref<bool(const Use *)> ShouldDrop) {
189   SmallVector<Use *, 8> ToBeEdited;
190   for (Use &U : uses())
191     if (U.getUser()->isDroppable() && ShouldDrop(&U))
192       ToBeEdited.push_back(&U);
193   for (Use *U : ToBeEdited)
194     dropDroppableUse(*U);
195 }
196 
197 void Value::dropDroppableUsesIn(User &Usr) {
198   assert(Usr.isDroppable() && "Expected a droppable user!");
199   for (Use &UsrOp : Usr.operands()) {
200     if (UsrOp.get() == this)
201       dropDroppableUse(UsrOp);
202   }
203 }
204 
205 void Value::dropDroppableUse(Use &U) {
206   U.removeFromList();
207   if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) {
208     unsigned OpNo = U.getOperandNo();
209     if (OpNo == 0)
210       U.set(ConstantInt::getTrue(Assume->getContext()));
211     else {
212       U.set(UndefValue::get(U.get()->getType()));
213       CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
214       BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
215     }
216     return;
217   }
218 
219   llvm_unreachable("unkown droppable use");
220 }
221 
222 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
223   // This can be computed either by scanning the instructions in BB, or by
224   // scanning the use list of this Value. Both lists can be very long, but
225   // usually one is quite short.
226   //
227   // Scan both lists simultaneously until one is exhausted. This limits the
228   // search to the shorter list.
229   BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
230   const_user_iterator UI = user_begin(), UE = user_end();
231   for (; BI != BE && UI != UE; ++BI, ++UI) {
232     // Scan basic block: Check if this Value is used by the instruction at BI.
233     if (is_contained(BI->operands(), this))
234       return true;
235     // Scan use list: Check if the use at UI is in BB.
236     const auto *User = dyn_cast<Instruction>(*UI);
237     if (User && User->getParent() == BB)
238       return true;
239   }
240   return false;
241 }
242 
243 unsigned Value::getNumUses() const {
244   return (unsigned)std::distance(use_begin(), use_end());
245 }
246 
247 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
248   ST = nullptr;
249   if (Instruction *I = dyn_cast<Instruction>(V)) {
250     if (BasicBlock *P = I->getParent())
251       if (Function *PP = P->getParent())
252         ST = PP->getValueSymbolTable();
253   } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
254     if (Function *P = BB->getParent())
255       ST = P->getValueSymbolTable();
256   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
257     if (Module *P = GV->getParent())
258       ST = &P->getValueSymbolTable();
259   } else if (Argument *A = dyn_cast<Argument>(V)) {
260     if (Function *P = A->getParent())
261       ST = P->getValueSymbolTable();
262   } else {
263     assert(isa<Constant>(V) && "Unknown value type!");
264     return true;  // no name is setable for this.
265   }
266   return false;
267 }
268 
269 ValueName *Value::getValueName() const {
270   if (!HasName) return nullptr;
271 
272   LLVMContext &Ctx = getContext();
273   auto I = Ctx.pImpl->ValueNames.find(this);
274   assert(I != Ctx.pImpl->ValueNames.end() &&
275          "No name entry found!");
276 
277   return I->second;
278 }
279 
280 void Value::setValueName(ValueName *VN) {
281   LLVMContext &Ctx = getContext();
282 
283   assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
284          "HasName bit out of sync!");
285 
286   if (!VN) {
287     if (HasName)
288       Ctx.pImpl->ValueNames.erase(this);
289     HasName = false;
290     return;
291   }
292 
293   HasName = true;
294   Ctx.pImpl->ValueNames[this] = VN;
295 }
296 
297 StringRef Value::getName() const {
298   // Make sure the empty string is still a C string. For historical reasons,
299   // some clients want to call .data() on the result and expect it to be null
300   // terminated.
301   if (!hasName())
302     return StringRef("", 0);
303   return getValueName()->getKey();
304 }
305 
306 void Value::setNameImpl(const Twine &NewName) {
307   // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
308   if (getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this))
309     return;
310 
311   // Fast path for common IRBuilder case of setName("") when there is no name.
312   if (NewName.isTriviallyEmpty() && !hasName())
313     return;
314 
315   SmallString<256> NameData;
316   StringRef NameRef = NewName.toStringRef(NameData);
317   assert(NameRef.find_first_of(0) == StringRef::npos &&
318          "Null bytes are not allowed in names");
319 
320   // Name isn't changing?
321   if (getName() == NameRef)
322     return;
323 
324   assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
325 
326   // Get the symbol table to update for this object.
327   ValueSymbolTable *ST;
328   if (getSymTab(this, ST))
329     return;  // Cannot set a name on this value (e.g. constant).
330 
331   if (!ST) { // No symbol table to update?  Just do the change.
332     if (NameRef.empty()) {
333       // Free the name for this value.
334       destroyValueName();
335       return;
336     }
337 
338     // NOTE: Could optimize for the case the name is shrinking to not deallocate
339     // then reallocated.
340     destroyValueName();
341 
342     // Create the new name.
343     MallocAllocator Allocator;
344     setValueName(ValueName::Create(NameRef, Allocator));
345     getValueName()->setValue(this);
346     return;
347   }
348 
349   // NOTE: Could optimize for the case the name is shrinking to not deallocate
350   // then reallocated.
351   if (hasName()) {
352     // Remove old name.
353     ST->removeValueName(getValueName());
354     destroyValueName();
355 
356     if (NameRef.empty())
357       return;
358   }
359 
360   // Name is changing to something new.
361   setValueName(ST->createValueName(NameRef, this));
362 }
363 
364 void Value::setName(const Twine &NewName) {
365   setNameImpl(NewName);
366   if (Function *F = dyn_cast<Function>(this))
367     F->recalculateIntrinsicID();
368 }
369 
370 void Value::takeName(Value *V) {
371   ValueSymbolTable *ST = nullptr;
372   // If this value has a name, drop it.
373   if (hasName()) {
374     // Get the symtab this is in.
375     if (getSymTab(this, ST)) {
376       // We can't set a name on this value, but we need to clear V's name if
377       // it has one.
378       if (V->hasName()) V->setName("");
379       return;  // Cannot set a name on this value (e.g. constant).
380     }
381 
382     // Remove old name.
383     if (ST)
384       ST->removeValueName(getValueName());
385     destroyValueName();
386   }
387 
388   // Now we know that this has no name.
389 
390   // If V has no name either, we're done.
391   if (!V->hasName()) return;
392 
393   // Get this's symtab if we didn't before.
394   if (!ST) {
395     if (getSymTab(this, ST)) {
396       // Clear V's name.
397       V->setName("");
398       return;  // Cannot set a name on this value (e.g. constant).
399     }
400   }
401 
402   // Get V's ST, this should always succed, because V has a name.
403   ValueSymbolTable *VST;
404   bool Failure = getSymTab(V, VST);
405   assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
406 
407   // If these values are both in the same symtab, we can do this very fast.
408   // This works even if both values have no symtab yet.
409   if (ST == VST) {
410     // Take the name!
411     setValueName(V->getValueName());
412     V->setValueName(nullptr);
413     getValueName()->setValue(this);
414     return;
415   }
416 
417   // Otherwise, things are slightly more complex.  Remove V's name from VST and
418   // then reinsert it into ST.
419 
420   if (VST)
421     VST->removeValueName(V->getValueName());
422   setValueName(V->getValueName());
423   V->setValueName(nullptr);
424   getValueName()->setValue(this);
425 
426   if (ST)
427     ST->reinsertValue(this);
428 }
429 
430 #ifndef NDEBUG
431 std::string Value::getNameOrAsOperand() const {
432   if (!getName().empty())
433     return std::string(getName());
434 
435   std::string BBName;
436   raw_string_ostream OS(BBName);
437   printAsOperand(OS, false);
438   return OS.str();
439 }
440 #endif
441 
442 void Value::assertModuleIsMaterializedImpl() const {
443 #ifndef NDEBUG
444   const GlobalValue *GV = dyn_cast<GlobalValue>(this);
445   if (!GV)
446     return;
447   const Module *M = GV->getParent();
448   if (!M)
449     return;
450   assert(M->isMaterialized());
451 #endif
452 }
453 
454 #ifndef NDEBUG
455 static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
456                      Constant *C) {
457   if (!Cache.insert(Expr).second)
458     return false;
459 
460   for (auto &O : Expr->operands()) {
461     if (O == C)
462       return true;
463     auto *CE = dyn_cast<ConstantExpr>(O);
464     if (!CE)
465       continue;
466     if (contains(Cache, CE, C))
467       return true;
468   }
469   return false;
470 }
471 
472 static bool contains(Value *Expr, Value *V) {
473   if (Expr == V)
474     return true;
475 
476   auto *C = dyn_cast<Constant>(V);
477   if (!C)
478     return false;
479 
480   auto *CE = dyn_cast<ConstantExpr>(Expr);
481   if (!CE)
482     return false;
483 
484   SmallPtrSet<ConstantExpr *, 4> Cache;
485   return contains(Cache, CE, C);
486 }
487 #endif // NDEBUG
488 
489 void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
490   assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
491   assert(!contains(New, this) &&
492          "this->replaceAllUsesWith(expr(this)) is NOT valid!");
493   assert(New->getType() == getType() &&
494          "replaceAllUses of value with new value of different type!");
495 
496   // Notify all ValueHandles (if present) that this value is going away.
497   if (HasValueHandle)
498     ValueHandleBase::ValueIsRAUWd(this, New);
499   if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
500     ValueAsMetadata::handleRAUW(this, New);
501 
502   while (!materialized_use_empty()) {
503     Use &U = *UseList;
504     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
505     // constant because they are uniqued.
506     if (auto *C = dyn_cast<Constant>(U.getUser())) {
507       if (!isa<GlobalValue>(C)) {
508         C->handleOperandChange(this, New);
509         continue;
510       }
511     }
512 
513     U.set(New);
514   }
515 
516   if (BasicBlock *BB = dyn_cast<BasicBlock>(this))
517     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
518 }
519 
520 void Value::replaceAllUsesWith(Value *New) {
521   doRAUW(New, ReplaceMetadataUses::Yes);
522 }
523 
524 void Value::replaceNonMetadataUsesWith(Value *New) {
525   doRAUW(New, ReplaceMetadataUses::No);
526 }
527 
528 void Value::replaceUsesWithIf(Value *New,
529                               llvm::function_ref<bool(Use &U)> ShouldReplace) {
530   assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
531   assert(New->getType() == getType() &&
532          "replaceUses of value with new value of different type!");
533 
534   for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
535     Use &U = *UI;
536     ++UI;
537     if (!ShouldReplace(U))
538       continue;
539     // Must handle Constants specially, we cannot call replaceUsesOfWith on a
540     // constant because they are uniqued.
541     if (auto *C = dyn_cast<Constant>(U.getUser())) {
542       if (!isa<GlobalValue>(C)) {
543         C->handleOperandChange(this, New);
544         continue;
545       }
546     }
547     U.set(New);
548   }
549 }
550 
551 /// Replace llvm.dbg.* uses of MetadataAsValue(ValueAsMetadata(V)) outside BB
552 /// with New.
553 static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) {
554   SmallVector<DbgVariableIntrinsic *> DbgUsers;
555   findDbgUsers(DbgUsers, V);
556   for (auto *DVI : DbgUsers) {
557     if (DVI->getParent() != BB)
558       DVI->replaceVariableLocationOp(V, New);
559   }
560 }
561 
562 // Like replaceAllUsesWith except it does not handle constants or basic blocks.
563 // This routine leaves uses within BB.
564 void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
565   assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
566   assert(!contains(New, this) &&
567          "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
568   assert(New->getType() == getType() &&
569          "replaceUses of value with new value of different type!");
570   assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
571 
572   replaceDbgUsesOutsideBlock(this, New, BB);
573   replaceUsesWithIf(New, [BB](Use &U) {
574     auto *I = dyn_cast<Instruction>(U.getUser());
575     // Don't replace if it's an instruction in the BB basic block.
576     return !I || I->getParent() != BB;
577   });
578 }
579 
580 namespace {
581 // Various metrics for how much to strip off of pointers.
582 enum PointerStripKind {
583   PSK_ZeroIndices,
584   PSK_ZeroIndicesAndAliases,
585   PSK_ZeroIndicesSameRepresentation,
586   PSK_ForAliasAnalysis,
587   PSK_InBoundsConstantIndices,
588   PSK_InBounds
589 };
590 
591 template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
592 
593 template <PointerStripKind StripKind>
594 static const Value *stripPointerCastsAndOffsets(
595     const Value *V,
596     function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
597   if (!V->getType()->isPointerTy())
598     return V;
599 
600   // Even though we don't look through PHI nodes, we could be called on an
601   // instruction in an unreachable block, which may be on a cycle.
602   SmallPtrSet<const Value *, 4> Visited;
603 
604   Visited.insert(V);
605   do {
606     Func(V);
607     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
608       switch (StripKind) {
609       case PSK_ZeroIndices:
610       case PSK_ZeroIndicesAndAliases:
611       case PSK_ZeroIndicesSameRepresentation:
612       case PSK_ForAliasAnalysis:
613         if (!GEP->hasAllZeroIndices())
614           return V;
615         break;
616       case PSK_InBoundsConstantIndices:
617         if (!GEP->hasAllConstantIndices())
618           return V;
619         LLVM_FALLTHROUGH;
620       case PSK_InBounds:
621         if (!GEP->isInBounds())
622           return V;
623         break;
624       }
625       V = GEP->getPointerOperand();
626     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
627       V = cast<Operator>(V)->getOperand(0);
628       if (!V->getType()->isPointerTy())
629         return V;
630     } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
631                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
632       // TODO: If we know an address space cast will not change the
633       //       representation we could look through it here as well.
634       V = cast<Operator>(V)->getOperand(0);
635     } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
636       V = cast<GlobalAlias>(V)->getAliasee();
637     } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
638                cast<PHINode>(V)->getNumIncomingValues() == 1) {
639       V = cast<PHINode>(V)->getIncomingValue(0);
640     } else {
641       if (const auto *Call = dyn_cast<CallBase>(V)) {
642         if (const Value *RV = Call->getReturnedArgOperand()) {
643           V = RV;
644           continue;
645         }
646         // The result of launder.invariant.group must alias it's argument,
647         // but it can't be marked with returned attribute, that's why it needs
648         // special case.
649         if (StripKind == PSK_ForAliasAnalysis &&
650             (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
651              Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
652           V = Call->getArgOperand(0);
653           continue;
654         }
655       }
656       return V;
657     }
658     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
659   } while (Visited.insert(V).second);
660 
661   return V;
662 }
663 } // end anonymous namespace
664 
665 const Value *Value::stripPointerCasts() const {
666   return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
667 }
668 
669 const Value *Value::stripPointerCastsAndAliases() const {
670   return stripPointerCastsAndOffsets<PSK_ZeroIndicesAndAliases>(this);
671 }
672 
673 const Value *Value::stripPointerCastsSameRepresentation() const {
674   return stripPointerCastsAndOffsets<PSK_ZeroIndicesSameRepresentation>(this);
675 }
676 
677 const Value *Value::stripInBoundsConstantOffsets() const {
678   return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
679 }
680 
681 const Value *Value::stripPointerCastsForAliasAnalysis() const {
682   return stripPointerCastsAndOffsets<PSK_ForAliasAnalysis>(this);
683 }
684 
685 const Value *Value::stripAndAccumulateConstantOffsets(
686     const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
687     function_ref<bool(Value &, APInt &)> ExternalAnalysis) const {
688   if (!getType()->isPtrOrPtrVectorTy())
689     return this;
690 
691   unsigned BitWidth = Offset.getBitWidth();
692   assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
693          "The offset bit width does not match the DL specification.");
694 
695   // Even though we don't look through PHI nodes, we could be called on an
696   // instruction in an unreachable block, which may be on a cycle.
697   SmallPtrSet<const Value *, 4> Visited;
698   Visited.insert(this);
699   const Value *V = this;
700   do {
701     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
702       // If in-bounds was requested, we do not strip non-in-bounds GEPs.
703       if (!AllowNonInbounds && !GEP->isInBounds())
704         return V;
705 
706       // If one of the values we have visited is an addrspacecast, then
707       // the pointer type of this GEP may be different from the type
708       // of the Ptr parameter which was passed to this function.  This
709       // means when we construct GEPOffset, we need to use the size
710       // of GEP's pointer type rather than the size of the original
711       // pointer type.
712       APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
713       if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
714         return V;
715 
716       // Stop traversal if the pointer offset wouldn't fit in the bit-width
717       // provided by the Offset argument. This can happen due to AddrSpaceCast
718       // stripping.
719       if (GEPOffset.getMinSignedBits() > BitWidth)
720         return V;
721 
722       // External Analysis can return a result higher/lower than the value
723       // represents. We need to detect overflow/underflow.
724       APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
725       if (!ExternalAnalysis) {
726         Offset += GEPOffsetST;
727       } else {
728         bool Overflow = false;
729         APInt OldOffset = Offset;
730         Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
731         if (Overflow) {
732           Offset = OldOffset;
733           return V;
734         }
735       }
736       V = GEP->getPointerOperand();
737     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
738                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
739       V = cast<Operator>(V)->getOperand(0);
740     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
741       if (!GA->isInterposable())
742         V = GA->getAliasee();
743     } else if (const auto *Call = dyn_cast<CallBase>(V)) {
744         if (const Value *RV = Call->getReturnedArgOperand())
745           V = RV;
746     }
747     assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
748   } while (Visited.insert(V).second);
749 
750   return V;
751 }
752 
753 const Value *
754 Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
755   return stripPointerCastsAndOffsets<PSK_InBounds>(this, Func);
756 }
757 
758 bool Value::canBeFreed() const {
759   assert(getType()->isPointerTy());
760 
761   // Cases that can simply never be deallocated
762   // *) Constants aren't allocated per se, thus not deallocated either.
763   if (isa<Constant>(this))
764     return false;
765 
766   // Handle byval/byref/sret/inalloca/preallocated arguments.  The storage
767   // lifetime is guaranteed to be longer than the callee's lifetime.
768   if (auto *A = dyn_cast<Argument>(this)) {
769     if (A->hasPointeeInMemoryValueAttr())
770       return false;
771     // A pointer to an object in a function which neither frees, nor can arrange
772     // for another thread to free on its behalf, can not be freed in the scope
773     // of the function.  Note that this logic is restricted to memory
774     // allocations in existance before the call; a nofree function *is* allowed
775     // to free memory it allocated.
776     const Function *F = A->getParent();
777     if (F->doesNotFreeMemory() && F->hasNoSync())
778       return false;
779   }
780 
781   const Function *F = nullptr;
782   if (auto *I = dyn_cast<Instruction>(this))
783     F = I->getFunction();
784   if (auto *A = dyn_cast<Argument>(this))
785     F = A->getParent();
786 
787   if (!F)
788     return true;
789 
790   // With garbage collection, deallocation typically occurs solely at or after
791   // safepoints.  If we're compiling for a collector which uses the
792   // gc.statepoint infrastructure, safepoints aren't explicitly present
793   // in the IR until after lowering from abstract to physical machine model.
794   // The collector could chose to mix explicit deallocation and gc'd objects
795   // which is why we need the explicit opt in on a per collector basis.
796   if (!F->hasGC())
797     return true;
798 
799   const auto &GCName = F->getGC();
800   if (GCName == "statepoint-example") {
801     auto *PT = cast<PointerType>(this->getType());
802     if (PT->getAddressSpace() != 1)
803       // For the sake of this example GC, we arbitrarily pick addrspace(1) as
804       // our GC managed heap.  This must match the same check in
805       // RewriteStatepointsForGC (and probably needs better factored.)
806       return true;
807 
808     // It is cheaper to scan for a declaration than to scan for a use in this
809     // function.  Note that gc.statepoint is a type overloaded function so the
810     // usual trick of requesting declaration of the intrinsic from the module
811     // doesn't work.
812     for (auto &Fn : *F->getParent())
813       if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
814         return true;
815     return false;
816   }
817   return true;
818 }
819 
820 uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
821                                                bool &CanBeNull,
822                                                bool &CanBeFreed) const {
823   assert(getType()->isPointerTy() && "must be pointer");
824 
825   uint64_t DerefBytes = 0;
826   CanBeNull = false;
827   CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
828   if (const Argument *A = dyn_cast<Argument>(this)) {
829     DerefBytes = A->getDereferenceableBytes();
830     if (DerefBytes == 0) {
831       // Handle byval/byref/inalloca/preallocated arguments
832       if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
833         if (ArgMemTy->isSized()) {
834           // FIXME: Why isn't this the type alloc size?
835           DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinSize();
836         }
837       }
838     }
839 
840     if (DerefBytes == 0) {
841       DerefBytes = A->getDereferenceableOrNullBytes();
842       CanBeNull = true;
843     }
844   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
845     DerefBytes = Call->getDereferenceableBytes(AttributeList::ReturnIndex);
846     if (DerefBytes == 0) {
847       DerefBytes =
848           Call->getDereferenceableOrNullBytes(AttributeList::ReturnIndex);
849       CanBeNull = true;
850     }
851   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
852     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
853       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
854       DerefBytes = CI->getLimitedValue();
855     }
856     if (DerefBytes == 0) {
857       if (MDNode *MD =
858               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
859         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
860         DerefBytes = CI->getLimitedValue();
861       }
862       CanBeNull = true;
863     }
864   } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
865     if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
866       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
867       DerefBytes = CI->getLimitedValue();
868     }
869     if (DerefBytes == 0) {
870       if (MDNode *MD =
871               IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
872         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
873         DerefBytes = CI->getLimitedValue();
874       }
875       CanBeNull = true;
876     }
877   } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
878     if (!AI->isArrayAllocation()) {
879       DerefBytes =
880           DL.getTypeStoreSize(AI->getAllocatedType()).getKnownMinSize();
881       CanBeNull = false;
882       CanBeFreed = false;
883     }
884   } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
885     if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
886       // TODO: Don't outright reject hasExternalWeakLinkage but set the
887       // CanBeNull flag.
888       DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedSize();
889       CanBeNull = false;
890     }
891   }
892   return DerefBytes;
893 }
894 
895 Align Value::getPointerAlignment(const DataLayout &DL) const {
896   assert(getType()->isPointerTy() && "must be pointer");
897   if (auto *GO = dyn_cast<GlobalObject>(this)) {
898     if (isa<Function>(GO)) {
899       Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
900       switch (DL.getFunctionPtrAlignType()) {
901       case DataLayout::FunctionPtrAlignType::Independent:
902         return FunctionPtrAlign;
903       case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
904         return std::max(FunctionPtrAlign, GO->getAlign().valueOrOne());
905       }
906       llvm_unreachable("Unhandled FunctionPtrAlignType");
907     }
908     const MaybeAlign Alignment(GO->getAlignment());
909     if (!Alignment) {
910       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
911         Type *ObjectType = GVar->getValueType();
912         if (ObjectType->isSized()) {
913           // If the object is defined in the current Module, we'll be giving
914           // it the preferred alignment. Otherwise, we have to assume that it
915           // may only have the minimum ABI alignment.
916           if (GVar->isStrongDefinitionForLinker())
917             return DL.getPreferredAlign(GVar);
918           else
919             return DL.getABITypeAlign(ObjectType);
920         }
921       }
922     }
923     return Alignment.valueOrOne();
924   } else if (const Argument *A = dyn_cast<Argument>(this)) {
925     const MaybeAlign Alignment = A->getParamAlign();
926     if (!Alignment && A->hasStructRetAttr()) {
927       // An sret parameter has at least the ABI alignment of the return type.
928       Type *EltTy = A->getParamStructRetType();
929       if (EltTy->isSized())
930         return DL.getABITypeAlign(EltTy);
931     }
932     return Alignment.valueOrOne();
933   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
934     return AI->getAlign();
935   } else if (const auto *Call = dyn_cast<CallBase>(this)) {
936     MaybeAlign Alignment = Call->getRetAlign();
937     if (!Alignment && Call->getCalledFunction())
938       Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
939     return Alignment.valueOrOne();
940   } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
941     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
942       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
943       return Align(CI->getLimitedValue());
944     }
945   } else if (auto *CstPtr = dyn_cast<Constant>(this)) {
946     if (auto *CstInt = dyn_cast_or_null<ConstantInt>(ConstantExpr::getPtrToInt(
947             const_cast<Constant *>(CstPtr), DL.getIntPtrType(getType()),
948             /*OnlyIfReduced=*/true))) {
949       size_t TrailingZeros = CstInt->getValue().countTrailingZeros();
950       // While the actual alignment may be large, elsewhere we have
951       // an arbitrary upper alignmet limit, so let's clamp to it.
952       return Align(TrailingZeros < Value::MaxAlignmentExponent
953                        ? uint64_t(1) << TrailingZeros
954                        : Value::MaximumAlignment);
955     }
956   }
957   return Align(1);
958 }
959 
960 const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
961                                      const BasicBlock *PredBB) const {
962   auto *PN = dyn_cast<PHINode>(this);
963   if (PN && PN->getParent() == CurBB)
964     return PN->getIncomingValueForBlock(PredBB);
965   return this;
966 }
967 
968 LLVMContext &Value::getContext() const { return VTy->getContext(); }
969 
970 void Value::reverseUseList() {
971   if (!UseList || !UseList->Next)
972     // No need to reverse 0 or 1 uses.
973     return;
974 
975   Use *Head = UseList;
976   Use *Current = UseList->Next;
977   Head->Next = nullptr;
978   while (Current) {
979     Use *Next = Current->Next;
980     Current->Next = Head;
981     Head->Prev = &Current->Next;
982     Head = Current;
983     Current = Next;
984   }
985   UseList = Head;
986   Head->Prev = &UseList;
987 }
988 
989 bool Value::isSwiftError() const {
990   auto *Arg = dyn_cast<Argument>(this);
991   if (Arg)
992     return Arg->hasSwiftErrorAttr();
993   auto *Alloca = dyn_cast<AllocaInst>(this);
994   if (!Alloca)
995     return false;
996   return Alloca->isSwiftError();
997 }
998 
999 bool Value::isTransitiveUsedByMetadataOnly() const {
1000   if (use_empty())
1001     return false;
1002   llvm::SmallVector<const User *, 32> WorkList;
1003   llvm::SmallPtrSet<const User *, 32> Visited;
1004   WorkList.insert(WorkList.begin(), user_begin(), user_end());
1005   while (!WorkList.empty()) {
1006     const User *U = WorkList.back();
1007     WorkList.pop_back();
1008     Visited.insert(U);
1009     // If it is transitively used by a global value or a non-constant value,
1010     // it's obviously not only used by metadata.
1011     if (!isa<Constant>(U) || isa<GlobalValue>(U))
1012       return false;
1013     for (const User *UU : U->users())
1014       if (!Visited.count(UU))
1015         WorkList.push_back(UU);
1016   }
1017   return true;
1018 }
1019 
1020 //===----------------------------------------------------------------------===//
1021 //                             ValueHandleBase Class
1022 //===----------------------------------------------------------------------===//
1023 
1024 void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
1025   assert(List && "Handle list is null?");
1026 
1027   // Splice ourselves into the list.
1028   Next = *List;
1029   *List = this;
1030   setPrevPtr(List);
1031   if (Next) {
1032     Next->setPrevPtr(&Next);
1033     assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
1034   }
1035 }
1036 
1037 void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
1038   assert(List && "Must insert after existing node");
1039 
1040   Next = List->Next;
1041   setPrevPtr(&List->Next);
1042   List->Next = this;
1043   if (Next)
1044     Next->setPrevPtr(&Next);
1045 }
1046 
1047 void ValueHandleBase::AddToUseList() {
1048   assert(getValPtr() && "Null pointer doesn't have a use list!");
1049 
1050   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1051 
1052   if (getValPtr()->HasValueHandle) {
1053     // If this value already has a ValueHandle, then it must be in the
1054     // ValueHandles map already.
1055     ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
1056     assert(Entry && "Value doesn't have any handles?");
1057     AddToExistingUseList(&Entry);
1058     return;
1059   }
1060 
1061   // Ok, it doesn't have any handles yet, so we must insert it into the
1062   // DenseMap.  However, doing this insertion could cause the DenseMap to
1063   // reallocate itself, which would invalidate all of the PrevP pointers that
1064   // point into the old table.  Handle this by checking for reallocation and
1065   // updating the stale pointers only if needed.
1066   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1067   const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
1068 
1069   ValueHandleBase *&Entry = Handles[getValPtr()];
1070   assert(!Entry && "Value really did already have handles?");
1071   AddToExistingUseList(&Entry);
1072   getValPtr()->HasValueHandle = true;
1073 
1074   // If reallocation didn't happen or if this was the first insertion, don't
1075   // walk the table.
1076   if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
1077       Handles.size() == 1) {
1078     return;
1079   }
1080 
1081   // Okay, reallocation did happen.  Fix the Prev Pointers.
1082   for (DenseMap<Value*, ValueHandleBase*>::iterator I = Handles.begin(),
1083        E = Handles.end(); I != E; ++I) {
1084     assert(I->second && I->first == I->second->getValPtr() &&
1085            "List invariant broken!");
1086     I->second->setPrevPtr(&I->second);
1087   }
1088 }
1089 
1090 void ValueHandleBase::RemoveFromUseList() {
1091   assert(getValPtr() && getValPtr()->HasValueHandle &&
1092          "Pointer doesn't have a use list!");
1093 
1094   // Unlink this from its use list.
1095   ValueHandleBase **PrevPtr = getPrevPtr();
1096   assert(*PrevPtr == this && "List invariant broken");
1097 
1098   *PrevPtr = Next;
1099   if (Next) {
1100     assert(Next->getPrevPtr() == &Next && "List invariant broken");
1101     Next->setPrevPtr(PrevPtr);
1102     return;
1103   }
1104 
1105   // If the Next pointer was null, then it is possible that this was the last
1106   // ValueHandle watching VP.  If so, delete its entry from the ValueHandles
1107   // map.
1108   LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1109   DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1110   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
1111     Handles.erase(getValPtr());
1112     getValPtr()->HasValueHandle = false;
1113   }
1114 }
1115 
1116 void ValueHandleBase::ValueIsDeleted(Value *V) {
1117   assert(V->HasValueHandle && "Should only be called if ValueHandles present");
1118 
1119   // Get the linked list base, which is guaranteed to exist since the
1120   // HasValueHandle flag is set.
1121   LLVMContextImpl *pImpl = V->getContext().pImpl;
1122   ValueHandleBase *Entry = pImpl->ValueHandles[V];
1123   assert(Entry && "Value bit set but no entries exist");
1124 
1125   // We use a local ValueHandleBase as an iterator so that ValueHandles can add
1126   // and remove themselves from the list without breaking our iteration.  This
1127   // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
1128   // Note that we deliberately do not the support the case when dropping a value
1129   // handle results in a new value handle being permanently added to the list
1130   // (as might occur in theory for CallbackVH's): the new value handle will not
1131   // be processed and the checking code will mete out righteous punishment if
1132   // the handle is still present once we have finished processing all the other
1133   // value handles (it is fine to momentarily add then remove a value handle).
1134   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1135     Iterator.RemoveFromUseList();
1136     Iterator.AddToExistingUseListAfter(Entry);
1137     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1138 
1139     switch (Entry->getKind()) {
1140     case Assert:
1141       break;
1142     case Weak:
1143     case WeakTracking:
1144       // WeakTracking and Weak just go to null, which unlinks them
1145       // from the list.
1146       Entry->operator=(nullptr);
1147       break;
1148     case Callback:
1149       // Forward to the subclass's implementation.
1150       static_cast<CallbackVH*>(Entry)->deleted();
1151       break;
1152     }
1153   }
1154 
1155   // All callbacks, weak references, and assertingVHs should be dropped by now.
1156   if (V->HasValueHandle) {
1157 #ifndef NDEBUG      // Only in +Asserts mode...
1158     dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1159            << "\n";
1160     if (pImpl->ValueHandles[V]->getKind() == Assert)
1161       llvm_unreachable("An asserting value handle still pointed to this"
1162                        " value!");
1163 
1164 #endif
1165     llvm_unreachable("All references to V were not removed?");
1166   }
1167 }
1168 
1169 void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1170   assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1171   assert(Old != New && "Changing value into itself!");
1172   assert(Old->getType() == New->getType() &&
1173          "replaceAllUses of value with new value of different type!");
1174 
1175   // Get the linked list base, which is guaranteed to exist since the
1176   // HasValueHandle flag is set.
1177   LLVMContextImpl *pImpl = Old->getContext().pImpl;
1178   ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1179 
1180   assert(Entry && "Value bit set but no entries exist");
1181 
1182   // We use a local ValueHandleBase as an iterator so that
1183   // ValueHandles can add and remove themselves from the list without
1184   // breaking our iteration.  This is not really an AssertingVH; we
1185   // just have to give ValueHandleBase some kind.
1186   for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1187     Iterator.RemoveFromUseList();
1188     Iterator.AddToExistingUseListAfter(Entry);
1189     assert(Entry->Next == &Iterator && "Loop invariant broken.");
1190 
1191     switch (Entry->getKind()) {
1192     case Assert:
1193     case Weak:
1194       // Asserting and Weak handles do not follow RAUW implicitly.
1195       break;
1196     case WeakTracking:
1197       // Weak goes to the new value, which will unlink it from Old's list.
1198       Entry->operator=(New);
1199       break;
1200     case Callback:
1201       // Forward to the subclass's implementation.
1202       static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1203       break;
1204     }
1205   }
1206 
1207 #ifndef NDEBUG
1208   // If any new weak value handles were added while processing the
1209   // list, then complain about it now.
1210   if (Old->HasValueHandle)
1211     for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1212       switch (Entry->getKind()) {
1213       case WeakTracking:
1214         dbgs() << "After RAUW from " << *Old->getType() << " %"
1215                << Old->getName() << " to " << *New->getType() << " %"
1216                << New->getName() << "\n";
1217         llvm_unreachable(
1218             "A weak tracking value handle still pointed to the old value!\n");
1219       default:
1220         break;
1221       }
1222 #endif
1223 }
1224 
1225 // Pin the vtable to this file.
1226 void CallbackVH::anchor() {}
1227