LLVM 24.0.0git
Value.cpp
Go to the documentation of this file.
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/STLExtras.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"
23#include "llvm/IR/DerivedUser.h"
25#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Module.h"
29#include "llvm/IR/Operator.h"
31#include "llvm/IR/ValueHandle.h"
36#include <algorithm>
37
38using namespace llvm;
39
41 "use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(true),
42 cl::desc("Deref attributes and metadata infer facts at definition only"));
43
44//===----------------------------------------------------------------------===//
45// Value Class
46//===----------------------------------------------------------------------===//
47static inline Type *checkType(Type *Ty) {
48 assert(Ty && "Value defined with a null type: Error!");
49 assert(!isa<TypedPointerType>(Ty->getScalarType()) &&
50 "Cannot have values with typed pointer types");
51 return Ty;
52}
53
54Value::Value(Type *ty, unsigned scid)
55 : SubclassID(scid), HasValueHandle(0), SubclassOptionalData(0),
56 SubclassData(0), NumUserOperands(0), IsUsedByMD(false), HasName(false),
57 VTy(checkType(ty)) {
58 static_assert(ConstantFirstVal == 0, "!(SubclassID < ConstantFirstVal)");
59 // FIXME: Why isn't this in the subclass gunk??
60 // Note, we cannot call isa<CallInst> before the CallInst has been
61 // constructed.
62 unsigned OpCode = 0;
63 if (SubclassID >= InstructionVal)
64 OpCode = SubclassID - InstructionVal;
65 if (OpCode == Instruction::Call || OpCode == Instruction::Invoke ||
66 OpCode == Instruction::CallBr)
67 assert((VTy->isFirstClassType() || VTy->isVoidTy() || VTy->isStructTy()) &&
68 "invalid CallBase type!");
69 else if (SubclassID != BasicBlockVal &&
70 (/*SubclassID < ConstantFirstVal ||*/ SubclassID > ConstantLastVal))
71 assert((VTy->isFirstClassType() || VTy->isVoidTy()) &&
72 "Cannot create non-first-class values except for constants!");
73 static_assert(sizeof(Value) == 2 * sizeof(void *) + 2 * sizeof(unsigned),
74 "Value too big");
75}
76
78 // Notify all ValueHandles (if present) that this value is going away.
79 if (HasValueHandle)
80 ValueHandleBase::ValueIsDeleted(this);
81 if (isUsedByMetadata())
82 ValueAsMetadata::handleDeletion(this);
83
84#ifndef NDEBUG // Only in -g mode...
85 // Check to make sure that there are no uses of this value that are still
86 // around when the value is destroyed. If there are, then we have a dangling
87 // reference and something is wrong. This code is here to print out where
88 // the value is still being referenced.
89 //
90 // Note that use_empty() cannot be called here, as it eventually downcasts
91 // 'this' to GlobalValue (derived class of Value), but GlobalValue has already
92 // been destructed, so accessing it is UB.
93 //
94 if (!materialized_use_empty()) {
95 dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
96 for (auto *U : users())
97 dbgs() << "Use still stuck around after Def is destroyed:" << *U << "\n";
98
99 llvm_unreachable("Uses remain when a value is destroyed!");
100 }
101#endif
102
103 // If this value is named, destroy the name. This should not be in a symtab
104 // at this point.
105 destroyValueName();
106}
107
108void Value::deleteValue() {
109 switch (getValueID()) {
110#define HANDLE_VALUE(Name) \
111 case Value::Name##Val: \
112 delete static_cast<Name *>(this); \
113 break;
114#define HANDLE_MEMORY_VALUE(Name) \
115 case Value::Name##Val: \
116 static_cast<DerivedUser *>(this)->DeleteValue( \
117 static_cast<DerivedUser *>(this)); \
118 break;
119#define HANDLE_CONSTANT(Name) \
120 case Value::Name##Val: \
121 llvm_unreachable("constants should be destroyed with destroyConstant"); \
122 break;
123#define HANDLE_INSTRUCTION(Name) /* nothing */
124#include "llvm/IR/Value.def"
125
126#define HANDLE_INST(N, OPC, CLASS) \
127 case addEnumValues(Value::InstructionVal, Instruction::OPC): \
128 delete static_cast<CLASS *>(this); \
129 break;
130#define HANDLE_USER_INST(N, OPC, CLASS)
131#include "llvm/IR/Instruction.def"
132
133 default:
134 llvm_unreachable("attempting to delete unknown value kind");
135 }
136}
137
138void Value::destroyValueName() {
139 ValueName *Name = getValueName();
140 if (Name) {
141 MallocAllocator Allocator;
142 Name->Destroy(Allocator);
143 }
144 setValueName(nullptr);
145}
146
147bool Value::hasNUses(unsigned N) const {
148 if (!UseList)
149 return N == 0;
150
151 // TODO: Disallow for ConstantData and remove !UseList check?
152 return hasNItems(use_begin(), use_end(), N);
153}
154
155bool Value::hasNUsesOrMore(unsigned N) const {
156 // TODO: Disallow for ConstantData and remove !UseList check?
157 if (!UseList)
158 return N == 0;
159
160 return hasNItemsOrMore(use_begin(), use_end(), N);
161}
162
163bool Value::hasOneUser() const {
164 if (use_empty())
165 return false;
166 if (hasOneUse())
167 return true;
168 return std::equal(++user_begin(), user_end(), user_begin());
169}
170
171static bool isUnDroppableUser(const User *U) { return !U->isDroppable(); }
172
173Use *Value::getSingleUndroppableUse() {
174 Use *Result = nullptr;
175 for (Use &U : uses()) {
176 if (!U.getUser()->isDroppable()) {
177 if (Result)
178 return nullptr;
179 Result = &U;
180 }
181 }
182 return Result;
183}
184
185User *Value::getUniqueUndroppableUser() {
186 User *Result = nullptr;
187 for (auto *U : users()) {
188 if (!U->isDroppable()) {
189 if (Result && Result != U)
190 return nullptr;
191 Result = U;
192 }
193 }
194 return Result;
195}
196
197bool Value::hasNUndroppableUses(unsigned int N) const {
198 return hasNItems(user_begin(), user_end(), N, isUnDroppableUser);
199}
200
201bool Value::hasNUndroppableUsesOrMore(unsigned int N) const {
202 return hasNItemsOrMore(user_begin(), user_end(), N, isUnDroppableUser);
203}
204
205void Value::dropDroppableUses(
206 llvm::function_ref<bool(const Use *)> ShouldDrop) {
207 SmallVector<Use *, 8> ToBeEdited;
208 for (Use &U : uses())
209 if (U.getUser()->isDroppable() && ShouldDrop(&U))
210 ToBeEdited.push_back(&U);
211 for (Use *U : ToBeEdited)
212 dropDroppableUse(*U);
213}
214
215void Value::dropDroppableUsesIn(User &Usr) {
216 assert(Usr.isDroppable() && "Expected a droppable user!");
217 for (Use &UsrOp : Usr.operands()) {
218 if (UsrOp.get() == this)
219 dropDroppableUse(UsrOp);
220 }
221}
222
223void Value::dropDroppableUse(Use &U) {
224 if (auto *Assume = dyn_cast<AssumeInst>(U.getUser())) {
225 unsigned OpNo = U.getOperandNo();
226 if (OpNo == 0)
227 U.set(ConstantInt::getTrue(Assume->getContext()));
228 else {
229 U.set(PoisonValue::get(U.get()->getType()));
230 CallInst::BundleOpInfo &BOI = Assume->getBundleOpInfoForOperand(OpNo);
231 BOI.Tag = Assume->getContext().pImpl->getOrInsertBundleTag("ignore");
232 }
233 return;
234 }
235
236 llvm_unreachable("unknown droppable use");
237}
238
239bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
240 assert(hasUseList() && "ConstantData has no use-list");
241
242 // This can be computed either by scanning the instructions in BB, or by
243 // scanning the use list of this Value. Both lists can be very long, but
244 // usually one is quite short.
245 //
246 // Scan both lists simultaneously until one is exhausted. This limits the
247 // search to the shorter list.
248 BasicBlock::const_iterator BI = BB->begin(), BE = BB->end();
249 const_user_iterator UI = user_begin(), UE = user_end();
250 for (; BI != BE && UI != UE; ++BI, ++UI) {
251 // Scan basic block: Check if this Value is used by the instruction at BI.
252 if (is_contained(BI->operands(), this))
253 return true;
254 // Scan use list: Check if the use at UI is in BB.
255 const auto *User = dyn_cast<Instruction>(*UI);
256 if (User && User->getParent() == BB)
257 return true;
258 }
259 return false;
260}
261
262unsigned Value::getNumUses() const {
263 // TODO: Disallow for ConstantData and remove !UseList check?
264 if (!UseList)
265 return 0;
266 return (unsigned)std::distance(use_begin(), use_end());
267}
268
269static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
270 ST = nullptr;
271 if (Instruction *I = dyn_cast<Instruction>(V)) {
272 if (BasicBlock *P = I->getParent())
273 if (Function *PP = P->getParent())
274 ST = PP->getValueSymbolTable();
275 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
276 if (Function *P = BB->getParent())
277 ST = P->getValueSymbolTable();
278 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
279 if (Module *P = GV->getParent())
280 ST = &P->getValueSymbolTable();
281 } else if (Argument *A = dyn_cast<Argument>(V)) {
282 if (Function *P = A->getParent())
283 ST = P->getValueSymbolTable();
284 } else {
285 assert(isa<Constant>(V) && "Unknown value type!");
286 return true; // no name is setable for this.
287 }
288 return false;
289}
290
291ValueName *Value::getValueName() const {
292 if (!HasName) return nullptr;
293
294 LLVMContext &Ctx = getContext();
295 auto I = Ctx.pImpl->ValueNames.find(this);
296 assert(I != Ctx.pImpl->ValueNames.end() &&
297 "No name entry found!");
298
299 return I->second;
300}
301
302void Value::setValueName(ValueName *VN) {
303 LLVMContext &Ctx = getContext();
304
305 assert(HasName == Ctx.pImpl->ValueNames.count(this) &&
306 "HasName bit out of sync!");
307
308 if (!VN) {
309 if (HasName)
310 Ctx.pImpl->ValueNames.erase(this);
311 HasName = false;
312 return;
313 }
314
315 HasName = true;
316 Ctx.pImpl->ValueNames[this] = VN;
317}
318
319StringRef Value::getName() const {
320 // Make sure the empty string is still a C string. For historical reasons,
321 // some clients want to call .data() on the result and expect it to be null
322 // terminated.
323 if (!hasName())
324 return StringRef("", 0);
325 return getValueName()->getKey();
326}
327
328void Value::setNameImpl(const Twine &NewName) {
329 bool NeedNewName =
330 !getContext().shouldDiscardValueNames() || isa<GlobalValue>(this);
331
332 // Fast-path: LLVMContext can be set to strip out non-GlobalValue names
333 // and there is no need to delete the old name.
334 if (!NeedNewName && !hasName())
335 return;
336
337 // Fast path for common IRBuilder case of setName("") when there is no name.
338 if (NewName.isTriviallyEmpty() && !hasName())
339 return;
340
341 SmallString<256> NameData;
342 StringRef NameRef = NeedNewName ? NewName.toStringRef(NameData) : "";
343 assert(!NameRef.contains(0) && "Null bytes are not allowed in names");
344
345 // Name isn't changing?
346 if (getName() == NameRef)
347 return;
348
349 assert(!getType()->isVoidTy() && "Cannot assign a name to void values!");
350
351 // Get the symbol table to update for this object.
352 ValueSymbolTable *ST;
353 if (getSymTab(this, ST))
354 return; // Cannot set a name on this value (e.g. constant).
355
356 ValueName *NewValueName = nullptr;
357 if (!ST) { // No symbol table to update? Just do the change.
358 if (!NameRef.empty()) {
359 // Create the new name.
360 MallocAllocator Allocator;
361 NewValueName = ValueName::create(NameRef, Allocator);
362 }
363 // NOTE: Could optimize for the case the name is shrinking to not deallocate
364 // then reallocated.
365 destroyValueName();
366
367 if (NewValueName) {
368 assert(NeedNewName);
369 setValueName(NewValueName);
370 getValueName()->setValue(this);
371 }
372 return;
373 }
374
375 if (!NameRef.empty())
376 NewValueName = ST->createValueName(NameRef, this);
377
378 // NOTE: Could optimize for the case the name is shrinking to not deallocate
379 // then reallocated.
380 if (hasName()) {
381 // Remove old name.
382 ST->removeValueName(getValueName());
383 destroyValueName();
384
385 if (NameRef.empty())
386 return;
387 }
388
389 // Name is changing to something new.
390 assert(NeedNewName && NewValueName != nullptr);
391 setValueName(NewValueName);
392}
393
394void Value::setName(const Twine &NewName) {
395 setNameImpl(NewName);
396 if (Function *F = dyn_cast<Function>(this))
397 F->updateAfterNameChange();
398}
399
400void Value::takeName(Value *V) {
401 assert(V != this && "Illegal call to this->takeName(this)!");
402 ValueSymbolTable *ST = nullptr;
403 // If this value has a name, drop it.
404 if (hasName()) {
405 // Get the symtab this is in.
406 if (getSymTab(this, ST)) {
407 // We can't set a name on this value, but we need to clear V's name if
408 // it has one.
409 if (V->hasName()) V->setName("");
410 return; // Cannot set a name on this value (e.g. constant).
411 }
412
413 // Remove old name.
414 if (ST)
415 ST->removeValueName(getValueName());
416 destroyValueName();
417 }
418
419 // Now we know that this has no name.
420
421 // If V has no name either, we're done.
422 if (!V->hasName()) return;
423
424 // Get this's symtab if we didn't before.
425 if (!ST) {
426 if (getSymTab(this, ST)) {
427 // Clear V's name.
428 V->setName("");
429 return; // Cannot set a name on this value (e.g. constant).
430 }
431 }
432
433 // Get V's ST, this should always succeed, because V has a name.
434 ValueSymbolTable *VST;
435 bool Failure = getSymTab(V, VST);
436 assert(!Failure && "V has a name, so it should have a ST!"); (void)Failure;
437
438 // If these values are both in the same symtab, we can do this very fast.
439 // This works even if both values have no symtab yet.
440 if (ST == VST) {
441 // Take the name!
442 setValueName(V->getValueName());
443 V->setValueName(nullptr);
444 getValueName()->setValue(this);
445 return;
446 }
447
448 // Otherwise, things are slightly more complex. Remove V's name from VST and
449 // then reinsert it into ST.
450
451 if (VST)
452 VST->removeValueName(V->getValueName());
453 setValueName(V->getValueName());
454 V->setValueName(nullptr);
455 getValueName()->setValue(this);
456
457 if (ST)
458 ST->reinsertValue(this);
459}
460
461std::string Value::getNameOrAsOperand() const {
462 if (!getName().empty())
463 return std::string(getName());
464
465 std::string BBName;
466 raw_string_ostream OS(BBName);
467 printAsOperand(OS, false);
468 return OS.str();
469}
470
471void Value::assertModuleIsMaterializedImpl() const {
472#ifndef NDEBUG
473 const GlobalValue *GV = dyn_cast<GlobalValue>(this);
474 if (!GV)
475 return;
476 const Module *M = GV->getParent();
477 if (!M)
478 return;
479 assert(M->isMaterialized());
480#endif
481}
482
483#ifndef NDEBUG
484static bool contains(SmallPtrSetImpl<ConstantExpr *> &Cache, ConstantExpr *Expr,
485 Constant *C) {
486 if (!Cache.insert(Expr).second)
487 return false;
488
489 for (auto &O : Expr->operands()) {
490 if (O == C)
491 return true;
492 auto *CE = dyn_cast<ConstantExpr>(O);
493 if (!CE)
494 continue;
495 if (contains(Cache, CE, C))
496 return true;
497 }
498 return false;
499}
500
501static bool contains(Value *Expr, Value *V) {
502 if (Expr == V)
503 return true;
504
505 auto *C = dyn_cast<Constant>(V);
506 if (!C)
507 return false;
508
509 auto *CE = dyn_cast<ConstantExpr>(Expr);
510 if (!CE)
511 return false;
512
513 SmallPtrSet<ConstantExpr *, 4> Cache;
514 return contains(Cache, CE, C);
515}
516#endif // NDEBUG
517
518void Value::doRAUW(Value *New, ReplaceMetadataUses ReplaceMetaUses) {
519 assert(hasUseList() && "Cannot replace constant data");
520 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
521 assert(!contains(New, this) &&
522 "this->replaceAllUsesWith(expr(this)) is NOT valid!");
523 assert(New->getType() == getType() &&
524 "replaceAllUses of value with new value of different type!");
525
526 // Notify all ValueHandles (if present) that this value is going away.
527 if (HasValueHandle)
528 ValueHandleBase::ValueIsRAUWd(this, New);
529 if (ReplaceMetaUses == ReplaceMetadataUses::Yes && isUsedByMetadata())
530 ValueAsMetadata::handleRAUW(this, New);
531
532 while (!materialized_use_empty()) {
533 Use &U = *UseList;
534 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
535 // constant because they are uniqued.
536 if (auto *C = dyn_cast<Constant>(U.getUser())) {
537 if (!isa<GlobalValue>(C)) {
538 C->handleOperandChange(this, New);
539 continue;
540 }
541 }
542
543 U.set(New);
544 }
545
546 if (BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
547 BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
548 if (BB->hasAddressTaken())
549 BlockAddress::lookup(BB)->handleOperandChange(this, New);
550 }
551}
552
553void Value::replaceAllUsesWith(Value *New) {
554 doRAUW(New, ReplaceMetadataUses::Yes);
555}
556
557void Value::replaceNonMetadataUsesWith(Value *New) {
558 doRAUW(New, ReplaceMetadataUses::No);
559}
560
561bool Value::replaceUsesWithIf(Value *New,
562 llvm::function_ref<bool(Use &U)> ShouldReplace) {
563 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!");
564 assert(New->getType() == getType() &&
565 "replaceUses of value with new value of different type!");
566
567 SmallVector<TrackingVH<Constant>, 8> Consts;
568 SmallPtrSet<Constant *, 8> Visited;
569
570 bool Changed = false;
571 for (Use &U : llvm::make_early_inc_range(uses())) {
572 if (!ShouldReplace(U))
573 continue;
574 Changed = true;
575
576 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
577 // constant because they are uniqued.
578 if (auto *C = dyn_cast<Constant>(U.getUser())) {
579 if (!isa<GlobalValue>(C)) {
580 if (Visited.insert(C).second)
581 Consts.push_back(TrackingVH<Constant>(C));
582 continue;
583 }
584 }
585 U.set(New);
586 }
587
588 while (!Consts.empty()) {
589 // FIXME: handleOperandChange() updates all the uses in a given Constant,
590 // not just the one passed to ShouldReplace
591 Consts.pop_back_val()->handleOperandChange(this, New);
592 }
593
594 return Changed;
595}
596
597/// Replace debug record uses of MetadataAsValue(ValueAsMetadata(V)) outside BB
598/// with New.
599static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB) {
600 SmallVector<DbgVariableRecord *> DPUsers;
601 findDbgUsers(V, DPUsers);
602 for (auto *DVR : DPUsers) {
603 DbgMarker *Marker = DVR->getMarker();
604 if (Marker->getParent() != BB)
605 DVR->replaceVariableLocationOp(V, New);
606 }
607}
608
609// Like replaceAllUsesWith except it does not handle constants or basic blocks.
610// This routine leaves uses within BB.
611void Value::replaceUsesOutsideBlock(Value *New, BasicBlock *BB) {
612 assert(New && "Value::replaceUsesOutsideBlock(<null>, BB) is invalid!");
613 assert(!contains(New, this) &&
614 "this->replaceUsesOutsideBlock(expr(this), BB) is NOT valid!");
615 assert(New->getType() == getType() &&
616 "replaceUses of value with new value of different type!");
617 assert(BB && "Basic block that may contain a use of 'New' must be defined\n");
618
619 replaceDbgUsesOutsideBlock(this, New, BB);
620 replaceUsesWithIf(New, [BB](Use &U) {
621 auto *I = dyn_cast<Instruction>(U.getUser());
622 // Don't replace if it's an instruction in the BB basic block.
623 return !I || I->getParent() != BB;
624 });
625}
626
627namespace {
628// Various metrics for how much to strip off of pointers.
629enum PointerStripKind {
630 PSK_ZeroIndices,
631 PSK_ZeroIndicesAndAliases,
632 PSK_ZeroIndicesSameRepresentation,
633 PSK_ForAliasAnalysis,
634 PSK_InBoundsConstantIndices,
635 PSK_InBounds
636};
637} // end anonymous namespace
638
639template <PointerStripKind StripKind> static void NoopCallback(const Value *) {}
640
641template <PointerStripKind StripKind>
643 const Value *V,
644 function_ref<void(const Value *)> Func = NoopCallback<StripKind>) {
645 if (!V->getType()->isPointerTy())
646 return V;
647
648 // Even though we don't look through PHI nodes, we could be called on an
649 // instruction in an unreachable block, which may be on a cycle.
650 SmallPtrSet<const Value *, 4> Visited;
651
652 Visited.insert(V);
653 do {
654 Func(V);
655 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
656 switch (StripKind) {
657 case PSK_ZeroIndices:
658 case PSK_ZeroIndicesAndAliases:
659 case PSK_ZeroIndicesSameRepresentation:
660 case PSK_ForAliasAnalysis:
661 if (!GEP->hasAllZeroIndices())
662 return V;
663 break;
664 case PSK_InBoundsConstantIndices:
665 if (!GEP->hasAllConstantIndices())
666 return V;
667 [[fallthrough]];
668 case PSK_InBounds:
669 if (!GEP->isInBounds())
670 return V;
671 break;
672 }
673 V = GEP->getPointerOperand();
674 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
675 Value *NewV = cast<Operator>(V)->getOperand(0);
676 if (!NewV->getType()->isPointerTy())
677 return V;
678 V = NewV;
679 } else if (StripKind != PSK_ZeroIndicesSameRepresentation &&
680 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
681 // TODO: If we know an address space cast will not change the
682 // representation we could look through it here as well.
683 V = cast<Operator>(V)->getOperand(0);
684 } else if (StripKind == PSK_ZeroIndicesAndAliases && isa<GlobalAlias>(V)) {
685 V = cast<GlobalAlias>(V)->getAliasee();
686 } else if (StripKind == PSK_ForAliasAnalysis && isa<PHINode>(V) &&
687 cast<PHINode>(V)->getNumIncomingValues() == 1) {
688 V = cast<PHINode>(V)->getIncomingValue(0);
689 } else {
690 if (const auto *Call = dyn_cast<CallBase>(V)) {
691 if (const Value *RV = Call->getReturnedArgOperand()) {
692 V = RV;
693 continue;
694 }
695 // The result of launder.invariant.group must alias it's argument,
696 // but it can't be marked with returned attribute, that's why it needs
697 // special case.
698 if (StripKind == PSK_ForAliasAnalysis &&
699 (Call->getIntrinsicID() == Intrinsic::launder_invariant_group ||
700 Call->getIntrinsicID() == Intrinsic::strip_invariant_group)) {
701 V = Call->getArgOperand(0);
702 continue;
703 }
704 }
705 return V;
706 }
707 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
708 } while (Visited.insert(V).second);
709
710 return V;
711}
712
713const Value *Value::stripPointerCasts() const {
715}
716
717const Value *Value::stripPointerCastsAndAliases() const {
719}
720
721const Value *Value::stripPointerCastsSameRepresentation() const {
723}
724
725const Value *Value::stripInBoundsConstantOffsets() const {
727}
728
729const Value *Value::stripPointerCastsForAliasAnalysis() const {
731}
732
733const Value *Value::stripAndAccumulateConstantOffsets(
734 const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
735 bool AllowInvariantGroup,
736 function_ref<bool(Value &, APInt &)> ExternalAnalysis,
737 bool LookThroughIntToPtr) const {
738 if (!getType()->isPtrOrPtrVectorTy())
739 return this;
740
741 unsigned BitWidth = Offset.getBitWidth();
742 assert(BitWidth == DL.getIndexTypeSizeInBits(getType()) &&
743 "The offset bit width does not match the DL specification.");
744
745 // Even though we don't look through PHI nodes, we could be called on an
746 // instruction in an unreachable block, which may be on a cycle.
747 SmallPtrSet<const Value *, 4> Visited;
748 Visited.insert(this);
749 const Value *V = this;
750 do {
751 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
752 // If in-bounds was requested, we do not strip non-in-bounds GEPs.
753 if (!AllowNonInbounds && !GEP->isInBounds())
754 return V;
755
756 // If one of the values we have visited is an addrspacecast, then
757 // the pointer type of this GEP may be different from the type
758 // of the Ptr parameter which was passed to this function. This
759 // means when we construct GEPOffset, we need to use the size
760 // of GEP's pointer type rather than the size of the original
761 // pointer type.
762 APInt GEPOffset(DL.getIndexTypeSizeInBits(V->getType()), 0);
763 if (!GEP->accumulateConstantOffset(DL, GEPOffset, ExternalAnalysis))
764 return V;
765
766 // Stop traversal if the pointer offset wouldn't fit in the bit-width
767 // provided by the Offset argument. This can happen due to AddrSpaceCast
768 // stripping.
769 if (GEPOffset.getSignificantBits() > BitWidth)
770 return V;
771
772 // External Analysis can return a result higher/lower than the value
773 // represents. We need to detect overflow/underflow.
774 APInt GEPOffsetST = GEPOffset.sextOrTrunc(BitWidth);
775 if (!ExternalAnalysis) {
776 Offset += GEPOffsetST;
777 } else {
778 bool Overflow = false;
779 APInt OldOffset = Offset;
780 Offset = Offset.sadd_ov(GEPOffsetST, Overflow);
781 if (Overflow) {
782 Offset = std::move(OldOffset);
783 return V;
784 }
785 }
786 V = GEP->getPointerOperand();
787 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
788 const Value *Src = cast<Operator>(V)->getOperand(0);
789 if (!Src->getType()->isPtrOrPtrVectorTy())
790 return V;
791 V = Src;
792 } else if (Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
793 V = cast<Operator>(V)->getOperand(0);
794 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
795 if (!GA->isInterposable())
796 V = GA->getAliasee();
797 } else if (const auto *Call = dyn_cast<CallBase>(V)) {
798 if (const Value *RV = Call->getReturnedArgOperand())
799 V = RV;
800 if (AllowInvariantGroup && Call->isLaunderOrStripInvariantGroup())
801 V = Call->getArgOperand(0);
802 } else if (auto *Int2Ptr = dyn_cast<Operator>(V)) {
803 // Try to accumulate across (inttoptr (add (ptrtoint p), off)).
804 if (!AllowNonInbounds || !LookThroughIntToPtr || !Int2Ptr ||
805 Int2Ptr->getOpcode() != Instruction::IntToPtr ||
806 Int2Ptr->getOperand(0)->getType()->getScalarSizeInBits() != BitWidth)
807 return V;
808
809 auto *Add = dyn_cast<AddOperator>(Int2Ptr->getOperand(0));
810 if (!Add)
811 return V;
812
813 auto *Ptr2Int = dyn_cast<PtrToIntOperator>(Add->getOperand(0));
814 auto *CI = dyn_cast<ConstantInt>(Add->getOperand(1));
815 if (!Ptr2Int || !CI)
816 return V;
817
818 Offset += CI->getValue();
819 V = Ptr2Int->getOperand(0);
820 }
821 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
822 } while (Visited.insert(V).second);
823
824 return V;
825}
826
827const Value *
828Value::stripInBoundsOffsets(function_ref<void(const Value *)> Func) const {
830}
831
832bool Value::canBeFreed() const {
834
835 // Cases that can simply never be deallocated
836 // *) Constants aren't allocated per se, thus not deallocated either.
837 if (isa<Constant>(this))
838 return false;
839
840 // Allocas cannot be freed: They remain dereferenceable after lifetime.end,
841 // in the sense that they can be loaded from without UB. They only become
842 // non-writable, which is not tracked by this API.
843 if (isa<AllocaInst>(this))
844 return false;
845
846 // Handle byval/byref/sret/inalloca/preallocated arguments. The storage
847 // lifetime is guaranteed to be longer than the callee's lifetime.
848 if (auto *A = dyn_cast<Argument>(this)) {
849 if (A->hasPointeeInMemoryValueAttr())
850 return false;
851 // A nofree function can not free (including via synchronization) any
852 // allocations that existed prior to the call, but may free allocations
853 // created inside the function. This logic is limited to argument pointers,
854 // as they definitely exist prior to the call.
855 const Function *F = A->getParent();
856 if (F->doesNotFreeMemory())
857 return false;
858
859 // nofree on the argument ensures that it cannot be freed through that
860 // pointer. noalias additionally ensures that it can't be freed through
861 // another pointer to the same allocation. Readonly implies nofree.
862 if ((A->hasNoFreeAttr() || A->onlyReadsMemory()) && A->hasNoAliasAttr())
863 return false;
864
865 // nofreeobj means that the underlying object cannot be freed, even
866 // through a different pointer.
867 if (A->hasAttribute(Attribute::NoFreeObj))
868 return false;
869 }
870
871 if (auto *ITP = dyn_cast<IntToPtrInst>(this);
872 ITP && ITP->hasMetadata(LLVMContext::MD_nofreeobj))
873 return false;
874
875 if (auto *CB = dyn_cast<CallBase>(this))
876 if (CB->hasRetAttr(Attribute::NoFreeObj))
877 return false;
878
879 const Function *F = nullptr;
880 if (auto *I = dyn_cast<Instruction>(this))
881 F = I->getFunction();
882 if (auto *A = dyn_cast<Argument>(this))
883 F = A->getParent();
884
885 if (!F)
886 return true;
887
888 // With garbage collection, deallocation typically occurs solely at or after
889 // safepoints. If we're compiling for a collector which uses the
890 // gc.statepoint infrastructure, safepoints aren't explicitly present
891 // in the IR until after lowering from abstract to physical machine model.
892 // The collector could chose to mix explicit deallocation and gc'd objects
893 // which is why we need the explicit opt in on a per collector basis.
894 if (!F->hasGC())
895 return true;
896
897 const auto &GCName = F->getGC();
898 if (GCName == "statepoint-example") {
899 auto *PT = cast<PointerType>(this->getType());
900 if (PT->getAddressSpace() != 1)
901 // For the sake of this example GC, we arbitrarily pick addrspace(1) as
902 // our GC managed heap. This must match the same check in
903 // RewriteStatepointsForGC (and probably needs better factored.)
904 return true;
905
906 // It is cheaper to scan for a declaration than to scan for a use in this
907 // function. Note that gc.statepoint is a type overloaded function so the
908 // usual trick of requesting declaration of the intrinsic from the module
909 // doesn't work.
910 for (auto &Fn : *F->getParent())
911 if (Fn.getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
912 return true;
913 return false;
914 }
915 return true;
916}
917
918uint64_t Value::getPointerDereferenceableBytes(const DataLayout &DL,
919 bool &CanBeNull,
920 bool *CanBeFreed) const {
921 assert(getType()->isPointerTy() && "must be pointer");
922
923 uint64_t DerefBytes = 0;
924 CanBeNull = false;
925 bool CanNotBeFreed = false;
926 if (const Argument *A = dyn_cast<Argument>(this)) {
927 DerefBytes = A->getDereferenceableBytes();
928 if (DerefBytes == 0) {
929 // Handle byval/byref/inalloca/preallocated arguments
930 if (Type *ArgMemTy = A->getPointeeInMemoryValueType()) {
931 if (ArgMemTy->isSized()) {
932 // FIXME: Why isn't this the type alloc size?
933 DerefBytes = DL.getTypeStoreSize(ArgMemTy).getKnownMinValue();
934 }
935 }
936 }
937
938 if (DerefBytes == 0) {
939 DerefBytes = A->getDereferenceableOrNullBytes();
940 CanBeNull = true;
941 }
942 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
943 DerefBytes = Call->getRetDereferenceableBytes();
944 if (DerefBytes == 0) {
945 DerefBytes = Call->getRetDereferenceableOrNullBytes();
946 CanBeNull = true;
947 }
948 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
949 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
950 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
951 DerefBytes = CI->getLimitedValue();
952 }
953 if (DerefBytes == 0) {
954 if (MDNode *MD =
955 LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
956 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
957 DerefBytes = CI->getLimitedValue();
958 }
959 CanBeNull = true;
960 }
961 } else if (auto *IP = dyn_cast<IntToPtrInst>(this)) {
962 if (MDNode *MD = IP->getMetadata(LLVMContext::MD_dereferenceable)) {
963 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
964 DerefBytes = CI->getLimitedValue();
965 }
966 if (DerefBytes == 0) {
967 if (MDNode *MD =
968 IP->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
969 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
970 DerefBytes = CI->getLimitedValue();
971 }
972 CanBeNull = true;
973 }
974 } else if (auto *AI = dyn_cast<AllocaInst>(this)) {
975 if (std::optional<TypeSize> Size = AI->getAllocationSize(DL)) {
976 DerefBytes = Size->getKnownMinValue();
977 CanBeNull = false;
978 CanNotBeFreed = true;
979 }
980 } else if (auto *GV = dyn_cast<GlobalVariable>(this)) {
981 if (GV->getValueType()->isSized() && !GV->hasExternalWeakLinkage()) {
982 // TODO: Don't outright reject hasExternalWeakLinkage but set the
983 // CanBeNull flag.
984 DerefBytes = DL.getTypeStoreSize(GV->getValueType()).getFixedValue();
985 CanBeNull = false;
986 CanNotBeFreed = true;
987 }
988 }
989
990 if (CanBeFreed) {
991 // Call canBeFreed() only if there are dereferenceable bytes and it's not
992 // one of the cases that can never be freed.
993 if (!CanNotBeFreed && DerefBytes != 0)
994 *CanBeFreed = UseDerefAtPointSemantics && canBeFreed();
995 else
996 *CanBeFreed = false;
997 }
998
999 return DerefBytes;
1000}
1001
1002Align Value::getPointerAlignment(const DataLayout &DL) const {
1003 assert(getType()->isPointerTy() && "must be pointer");
1004 if (const Function *F = dyn_cast<Function>(this)) {
1005 Align FunctionPtrAlign = DL.getFunctionPtrAlign().valueOrOne();
1006 switch (DL.getFunctionPtrAlignType()) {
1007 case DataLayout::FunctionPtrAlignType::Independent:
1008 return FunctionPtrAlign;
1009 case DataLayout::FunctionPtrAlignType::MultipleOfFunctionAlign:
1010 return std::max(FunctionPtrAlign, F->getAlign().valueOrOne());
1011 }
1012 llvm_unreachable("Unhandled FunctionPtrAlignType");
1013 } else if (auto *GVar = dyn_cast<GlobalVariable>(this)) {
1014 const MaybeAlign Alignment(GVar->getAlign());
1015 if (!Alignment) {
1016 Type *ObjectType = GVar->getValueType();
1017 if (ObjectType->isSized()) {
1018 // If the object is defined in the current Module, we'll be giving
1019 // it the preferred alignment. Otherwise, we have to assume that it
1020 // may only have the minimum ABI alignment.
1021 if (GVar->isStrongDefinitionForLinker())
1022 return DL.getPreferredAlign(GVar);
1023 else
1024 return DL.getABITypeAlign(ObjectType);
1025 }
1026 }
1027 return Alignment.valueOrOne();
1028 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1029 const MaybeAlign Alignment = A->getParamAlign();
1030 if (!Alignment && A->hasStructRetAttr()) {
1031 // An sret parameter has at least the ABI alignment of the return type.
1032 Type *EltTy = A->getParamStructRetType();
1033 if (EltTy->isSized())
1034 return DL.getABITypeAlign(EltTy);
1035 }
1036 return Alignment.valueOrOne();
1037 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(this)) {
1038 return AI->getAlign();
1039 } else if (const auto *Call = dyn_cast<CallBase>(this)) {
1040 MaybeAlign Alignment = Call->getRetAlign();
1041 if (!Alignment && Call->getCalledFunction())
1042 Alignment = Call->getCalledFunction()->getAttributes().getRetAlignment();
1043 return Alignment.valueOrOne();
1044 } else if (const LoadInst *LI = dyn_cast<LoadInst>(this)) {
1045 if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
1046 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
1047 return Align(CI->getLimitedValue());
1048 }
1049 } else if (auto *CE = dyn_cast<ConstantExpr>(this)) {
1050 // Determine the alignment of inttoptr(C).
1051 if (CE->getOpcode() == Instruction::IntToPtr &&
1052 isa<ConstantInt>(CE->getOperand(0))) {
1053 ConstantInt *IntPtr = cast<ConstantInt>(CE->getOperand(0));
1054 size_t TrailingZeros = IntPtr->getValue().countr_zero();
1055 // While the actual alignment may be large, elsewhere we have
1056 // an arbitrary upper alignmet limit, so let's clamp to it.
1057 return Align(TrailingZeros < Value::MaxAlignmentExponent
1058 ? uint64_t(1) << TrailingZeros
1059 : Value::MaximumAlignment);
1060 }
1061 }
1062 return Align(1);
1063}
1064
1065static std::optional<int64_t>
1066getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
1067 // Skip over the first indices.
1069 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1070 /*skip along*/;
1071
1072 // Compute the offset implied by the rest of the indices.
1073 int64_t Offset = 0;
1074 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1075 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1076 if (!OpC)
1077 return std::nullopt;
1078 if (OpC->isZero())
1079 continue; // No offset.
1080
1081 // Handle struct indices, which add their field offset to the pointer.
1082 if (StructType *STy = GTI.getStructTypeOrNull()) {
1083 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1084 continue;
1085 }
1086
1087 // Otherwise, we have a sequential type like an array or fixed-length
1088 // vector. Multiply the index by the ElementSize.
1089 TypeSize Size = GTI.getSequentialElementStride(DL);
1090 if (Size.isScalable())
1091 return std::nullopt;
1092 Offset += Size.getFixedValue() * OpC->getSExtValue();
1093 }
1094
1095 return Offset;
1096}
1097
1098std::optional<int64_t> Value::getPointerOffsetFrom(const Value *Other,
1099 const DataLayout &DL) const {
1100 const Value *Ptr1 = Other;
1101 const Value *Ptr2 = this;
1102 APInt Offset1(DL.getIndexTypeSizeInBits(Ptr1->getType()), 0);
1103 APInt Offset2(DL.getIndexTypeSizeInBits(Ptr2->getType()), 0);
1104 Ptr1 = Ptr1->stripAndAccumulateConstantOffsets(DL, Offset1, true);
1105 Ptr2 = Ptr2->stripAndAccumulateConstantOffsets(DL, Offset2, true);
1106
1107 // Handle the trivial case first.
1108 if (Ptr1 == Ptr2)
1109 return Offset2.getSExtValue() - Offset1.getSExtValue();
1110
1111 const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
1112 const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
1113
1114 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1115 // base. After that base, they may have some number of common (and
1116 // potentially variable) indices. After that they handle some constant
1117 // offset, which determines their offset from each other. At this point, we
1118 // handle no other case.
1119 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0) ||
1120 GEP1->getSourceElementType() != GEP2->getSourceElementType())
1121 return std::nullopt;
1122
1123 // Skip any common indices and track the GEP types.
1124 unsigned Idx = 1;
1125 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1126 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1127 break;
1128
1129 auto IOffset1 = getOffsetFromIndex(GEP1, Idx, DL);
1130 auto IOffset2 = getOffsetFromIndex(GEP2, Idx, DL);
1131 if (!IOffset1 || !IOffset2)
1132 return std::nullopt;
1133 return *IOffset2 - *IOffset1 + Offset2.getSExtValue() -
1134 Offset1.getSExtValue();
1135}
1136
1137const Value *Value::DoPHITranslation(const BasicBlock *CurBB,
1138 const BasicBlock *PredBB) const {
1139 auto *PN = dyn_cast<PHINode>(this);
1140 if (PN && PN->getParent() == CurBB)
1141 return PN->getIncomingValueForBlock(PredBB);
1142 return this;
1143}
1144
1145void Value::reverseUseList() {
1146 if (!UseList || !UseList->Next)
1147 // No need to reverse 0 or 1 uses.
1148 return;
1149
1150 Use *Head = UseList;
1151 Use *Current = UseList->Next;
1152 Head->Next = nullptr;
1153 while (Current) {
1154 Use *Next = Current->Next;
1155 Current->Next = Head;
1156 Head->Prev = &Current->Next;
1157 Head = Current;
1158 Current = Next;
1159 }
1160 UseList = Head;
1161 Head->Prev = &UseList;
1162}
1163
1164bool Value::isSwiftError() const {
1165 auto *Arg = dyn_cast<Argument>(this);
1166 if (Arg)
1167 return Arg->hasSwiftErrorAttr();
1168 auto *Alloca = dyn_cast<AllocaInst>(this);
1169 if (!Alloca)
1170 return false;
1171 return Alloca->isSwiftError();
1172}
1173
1174//===----------------------------------------------------------------------===//
1175// ValueHandleBase Class
1176//===----------------------------------------------------------------------===//
1177
1178void ValueHandleBase::AddToExistingUseList(ValueHandleBase **List) {
1179 assert(List && "Handle list is null?");
1180
1181 // Splice ourselves into the list.
1182 Next = *List;
1183 *List = this;
1184 setPrevPtr(List);
1185 if (Next) {
1186 Next->setPrevPtr(&Next);
1187 assert(getValPtr() == Next->getValPtr() && "Added to wrong list?");
1188 }
1189}
1190
1191void ValueHandleBase::AddToExistingUseListAfter(ValueHandleBase *List) {
1192 assert(List && "Must insert after existing node");
1193
1194 Next = List->Next;
1195 setPrevPtr(&List->Next);
1196 List->Next = this;
1197 if (Next)
1198 Next->setPrevPtr(&Next);
1199}
1200
1201void ValueHandleBase::AddToUseList() {
1202 assert(getValPtr() && "Null pointer doesn't have a use list!");
1203
1204 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1205
1206 if (getValPtr()->HasValueHandle) {
1207 // If this value already has a ValueHandle, then it must be in the
1208 // ValueHandles map already.
1209 ValueHandleBase *&Entry = pImpl->ValueHandles[getValPtr()];
1210 assert(Entry && "Value doesn't have any handles?");
1211 AddToExistingUseList(&Entry);
1212 return;
1213 }
1214
1215 // Ok, it doesn't have any handles yet, so we must insert it into the
1216 // DenseMap. However, doing this insertion could cause the DenseMap to
1217 // reallocate itself, which would invalidate all of the PrevP pointers that
1218 // point into the old table. Handle this by checking for reallocation and
1219 // updating the stale pointers only if needed.
1220 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1221 const void *OldBucketPtr = Handles.getPointerIntoBucketsArray();
1222
1223 ValueHandleBase *&Entry = Handles[getValPtr()];
1224 assert(!Entry && "Value really did already have handles?");
1225 AddToExistingUseList(&Entry);
1226 getValPtr()->HasValueHandle = true;
1227
1228 // If reallocation didn't happen or if this was the first insertion, don't
1229 // walk the table.
1230 if (Handles.isPointerIntoBucketsArray(OldBucketPtr) ||
1231 Handles.size() == 1) {
1232 return;
1233 }
1234
1235 // Okay, reallocation did happen. Fix the Prev Pointers.
1236 for (auto I = Handles.begin(), E = Handles.end(); I != E; ++I) {
1237 assert(I->second && I->first == I->second->getValPtr() &&
1238 "List invariant broken!");
1239 I->second->setPrevPtr(&I->second);
1240 }
1241}
1242
1243void ValueHandleBase::RemoveFromUseList() {
1244 assert(getValPtr() && getValPtr()->HasValueHandle &&
1245 "Pointer doesn't have a use list!");
1246
1247 // Unlink this from its use list.
1248 ValueHandleBase **PrevPtr = getPrevPtr();
1249 assert(*PrevPtr == this && "List invariant broken");
1250
1251 *PrevPtr = Next;
1252 if (Next) {
1253 assert(Next->getPrevPtr() == &Next && "List invariant broken");
1254 Next->setPrevPtr(PrevPtr);
1255 return;
1256 }
1257
1258 // If the Next pointer was null, then it is possible that this was the last
1259 // ValueHandle watching VP. If so, delete its entry from the ValueHandles
1260 // map.
1261 LLVMContextImpl *pImpl = getValPtr()->getContext().pImpl;
1262 DenseMap<Value*, ValueHandleBase*> &Handles = pImpl->ValueHandles;
1263 if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
1264 // TODO: Remove the only user of DenseMap's callback erase.
1265 Handles.erase(getValPtr(), [](auto &Bucket) {
1266 Bucket.second->setPrevPtr(&Bucket.second);
1267 });
1268 getValPtr()->HasValueHandle = false;
1269 }
1270}
1271
1272void ValueHandleBase::ValueIsDeleted(Value *V) {
1273 assert(V->HasValueHandle && "Should only be called if ValueHandles present");
1274
1275 // Get the linked list base, which is guaranteed to exist since the
1276 // HasValueHandle flag is set.
1277 LLVMContextImpl *pImpl = V->getContext().pImpl;
1278 ValueHandleBase *Entry = pImpl->ValueHandles[V];
1279 assert(Entry && "Value bit set but no entries exist");
1280
1281 // We use a local ValueHandleBase as an iterator so that ValueHandles can add
1282 // and remove themselves from the list without breaking our iteration. This
1283 // is not really an AssertingVH; we just have to give ValueHandleBase a kind.
1284 // Note that we deliberately do not the support the case when dropping a value
1285 // handle results in a new value handle being permanently added to the list
1286 // (as might occur in theory for CallbackVH's): the new value handle will not
1287 // be processed and the checking code will mete out righteous punishment if
1288 // the handle is still present once we have finished processing all the other
1289 // value handles (it is fine to momentarily add then remove a value handle).
1290 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1291 Iterator.RemoveFromUseList();
1292 Iterator.AddToExistingUseListAfter(Entry);
1293 assert(Entry->Next == &Iterator && "Loop invariant broken.");
1294
1295 switch (Entry->getKind()) {
1296 case Assert:
1297 break;
1298 case Weak:
1299 case WeakTracking:
1300 // WeakTracking and Weak just go to null, which unlinks them
1301 // from the list.
1302 Entry->operator=(nullptr);
1303 break;
1304 case Callback:
1305 // Forward to the subclass's implementation.
1306 static_cast<CallbackVH*>(Entry)->deleted();
1307 break;
1308 }
1309 }
1310
1311 // All callbacks, weak references, and assertingVHs should be dropped by now.
1312 if (V->HasValueHandle) {
1313#ifndef NDEBUG // Only in +Asserts mode...
1314 dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
1315 << "\n";
1316 if (pImpl->ValueHandles[V]->getKind() == Assert)
1317 llvm_unreachable("An asserting value handle still pointed to this"
1318 " value!");
1319
1320#endif
1321 llvm_unreachable("All references to V were not removed?");
1322 }
1323}
1324
1325void ValueHandleBase::ValueIsRAUWd(Value *Old, Value *New) {
1326 assert(Old->HasValueHandle &&"Should only be called if ValueHandles present");
1327 assert(Old != New && "Changing value into itself!");
1328 assert(Old->getType() == New->getType() &&
1329 "replaceAllUses of value with new value of different type!");
1330
1331 // Get the linked list base, which is guaranteed to exist since the
1332 // HasValueHandle flag is set.
1333 LLVMContextImpl *pImpl = Old->getContext().pImpl;
1334 ValueHandleBase *Entry = pImpl->ValueHandles[Old];
1335
1336 assert(Entry && "Value bit set but no entries exist");
1337
1338 // We use a local ValueHandleBase as an iterator so that
1339 // ValueHandles can add and remove themselves from the list without
1340 // breaking our iteration. This is not really an AssertingVH; we
1341 // just have to give ValueHandleBase some kind.
1342 for (ValueHandleBase Iterator(Assert, *Entry); Entry; Entry = Iterator.Next) {
1343 Iterator.RemoveFromUseList();
1344 Iterator.AddToExistingUseListAfter(Entry);
1345 assert(Entry->Next == &Iterator && "Loop invariant broken.");
1346
1347 switch (Entry->getKind()) {
1348 case Assert:
1349 case Weak:
1350 // Asserting and Weak handles do not follow RAUW implicitly.
1351 break;
1352 case WeakTracking:
1353 // Weak goes to the new value, which will unlink it from Old's list.
1354 Entry->operator=(New);
1355 break;
1356 case Callback:
1357 // Forward to the subclass's implementation.
1358 static_cast<CallbackVH*>(Entry)->allUsesReplacedWith(New);
1359 break;
1360 }
1361 }
1362
1363#ifndef NDEBUG
1364 // If any new weak value handles were added while processing the
1365 // list, then complain about it now.
1366 if (Old->HasValueHandle)
1367 for (Entry = pImpl->ValueHandles[Old]; Entry; Entry = Entry->Next)
1368 switch (Entry->getKind()) {
1369 case WeakTracking:
1370 dbgs() << "After RAUW from " << *Old->getType() << " %"
1371 << Old->getName() << " to " << *New->getType() << " %"
1372 << New->getName() << "\n";
1374 "A weak tracking value handle still pointed to the old value!\n");
1375 default:
1376 break;
1377 }
1378#endif
1379}
1380
1381// Pin the vtable to this file.
1382void CallbackVH::anchor() {}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
iv users
Definition IVUsers.cpp:48
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
const uint64_t BitWidth
#define P(N)
if(PassOpts->AAPipeline)
static StringRef getName(Value *V)
Basic Register Allocator
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
static std::optional< int64_t > getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL)
Definition Value.cpp:1066
static void NoopCallback(const Value *)
Definition Value.cpp:639
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
static Type * checkType(Type *Ty)
Definition Value.cpp:47
static bool getSymTab(Value *V, ValueSymbolTable *&ST)
Definition Value.cpp:269
static const Value * stripPointerCastsAndOffsets(const Value *V, function_ref< void(const Value *)> Func=NoopCallback< StripKind >)
Definition Value.cpp:642
static void replaceDbgUsesOutsideBlock(Value *V, Value *New, BasicBlock *BB)
Replace debug record uses of MetadataAsValue(ValueAsMetadata(V)) outside BB with New.
Definition Value.cpp:599
static cl::opt< bool > UseDerefAtPointSemantics("use-dereferenceable-at-point-semantics", cl::Hidden, cl::init(true), cl::desc("Deref attributes and metadata infer facts at definition only"))
static bool isUnDroppableUser(const User *U)
Definition Value.cpp:171
This file defines the SmallString class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
LLVM_ABI const BasicBlock * getParent() const
bool erase(const KeyT &Val)
Definition DenseMap.h:377
unsigned size() const
Definition DenseMap.h:172
iterator begin()
Definition DenseMap.h:137
iterator end()
Definition DenseMap.h:141
bool isPointerIntoBucketsArray(const void *Ptr) const
Return true if the specified pointer points somewhere into the DenseMap's array of buckets (i....
Definition DenseMap.h:426
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition DenseMap.h:433
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:82
bool hasExternalWeakLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
Type * getValueType() const
DenseMap< const Value *, ValueName * > ValueNames
ValueHandlesTy ValueHandles
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
static StringMapEntry * create(StringRef key, AllocatorTy &allocator, InitTy &&...initVals)
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition Twine.h:398
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition Twine.h:461
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
op_range operands()
Definition User.h:267
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
Definition User.cpp:119
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:54
LLVM_ABI ~Value()
Value's destructor should be virtual by design, but that would require that Value and all of its subc...
Definition Value.cpp:77
TypeSize getSequentialElementStride(const DataLayout &DL) const
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:139
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
This is an optimization pass for GlobalISel generic memory operations.
StringMapEntry< Value * > ValueName
Definition Value.h:56
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
Definition STLExtras.h:2638
bool hasNItems(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has exactly N items.
Definition STLExtras.h:2613
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
generic_gep_type_iterator<> gep_type_iterator
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
gep_type_iterator gep_type_begin(const User *GEP)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
#define N
StringMapEntry< uint32_t > * Tag
The operand bundle tag, interned by LLVMContextImpl::getOrInsertBundleTag.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130