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