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