LLVM 20.0.0git
MemoryProfileInfo.cpp
Go to the documentation of this file.
1//===-- MemoryProfileInfo.cpp - memory profile info ------------------------==//
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 contains utilities to analyze memory profile information.
10//
11//===----------------------------------------------------------------------===//
12
15
16using namespace llvm;
17using namespace llvm::memprof;
18
19#define DEBUG_TYPE "memory-profile-info"
20
21// Upper bound on lifetime access density (accesses per byte per lifetime sec)
22// for marking an allocation cold.
24 "memprof-lifetime-access-density-cold-threshold", cl::init(0.05),
26 cl::desc("The threshold the lifetime access density (accesses per byte per "
27 "lifetime sec) must be under to consider an allocation cold"));
28
29// Lower bound on lifetime to mark an allocation cold (in addition to accesses
30// per byte per sec above). This is to avoid pessimizing short lived objects.
32 "memprof-ave-lifetime-cold-threshold", cl::init(200), cl::Hidden,
33 cl::desc("The average lifetime (s) for an allocation to be considered "
34 "cold"));
35
36// Lower bound on average lifetime accesses density (total life time access
37// density / alloc count) for marking an allocation hot.
39 "memprof-min-ave-lifetime-access-density-hot-threshold", cl::init(1000),
41 cl::desc("The minimum TotalLifetimeAccessDensity / AllocCount for an "
42 "allocation to be considered hot"));
43
45 "memprof-report-hinted-sizes", cl::init(false), cl::Hidden,
46 cl::desc("Report total allocation sizes of hinted allocations"));
47
49 uint64_t AllocCount,
50 uint64_t TotalLifetime) {
51 // The access densities are multiplied by 100 to hold 2 decimal places of
52 // precision, so need to divide by 100.
53 if (((float)TotalLifetimeAccessDensity) / AllocCount / 100 <
55 // Lifetime is expected to be in ms, so convert the threshold to ms.
56 && ((float)TotalLifetime) / AllocCount >=
58 return AllocationType::Cold;
59
60 // The access densities are multiplied by 100 to hold 2 decimal places of
61 // precision, so need to divide by 100.
62 if (((float)TotalLifetimeAccessDensity) / AllocCount / 100 >
64 return AllocationType::Hot;
65
66 return AllocationType::NotCold;
67}
68
70 LLVMContext &Ctx) {
71 std::vector<Metadata *> StackVals;
72 for (auto Id : CallStack) {
73 auto *StackValMD =
74 ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id));
75 StackVals.push_back(StackValMD);
76 }
77 return MDNode::get(Ctx, StackVals);
78}
79
81 assert(MIB->getNumOperands() >= 2);
82 // The stack metadata is the first operand of each memprof MIB metadata.
83 return cast<MDNode>(MIB->getOperand(0));
84}
85
87 assert(MIB->getNumOperands() >= 2);
88 // The allocation type is currently the second operand of each memprof
89 // MIB metadata. This will need to change as we add additional allocation
90 // types that can be applied based on the allocation profile data.
91 auto *MDS = dyn_cast<MDString>(MIB->getOperand(1));
92 assert(MDS);
93 if (MDS->getString() == "cold") {
94 return AllocationType::Cold;
95 } else if (MDS->getString() == "hot") {
96 return AllocationType::Hot;
97 }
98 return AllocationType::NotCold;
99}
100
102 if (MIB->getNumOperands() < 3)
103 return 0;
104 return mdconst::dyn_extract<ConstantInt>(MIB->getOperand(2))->getZExtValue();
105}
106
108 switch (Type) {
109 case AllocationType::NotCold:
110 return "notcold";
111 break;
112 case AllocationType::Cold:
113 return "cold";
114 break;
115 case AllocationType::Hot:
116 return "hot";
117 break;
118 default:
119 assert(false && "Unexpected alloc type");
120 }
121 llvm_unreachable("invalid alloc type");
122}
123
126 auto AllocTypeString = getAllocTypeAttributeString(AllocType);
127 auto A = llvm::Attribute::get(Ctx, "memprof", AllocTypeString);
128 CI->addFnAttr(A);
129}
130
131bool llvm::memprof::hasSingleAllocType(uint8_t AllocTypes) {
132 const unsigned NumAllocTypes = llvm::popcount(AllocTypes);
133 assert(NumAllocTypes != 0);
134 return NumAllocTypes == 1;
135}
136
138 ArrayRef<uint64_t> StackIds,
139 uint64_t TotalSize) {
140 bool First = true;
141 CallStackTrieNode *Curr = nullptr;
142 for (auto StackId : StackIds) {
143 // If this is the first stack frame, add or update alloc node.
144 if (First) {
145 First = false;
146 if (Alloc) {
147 assert(AllocStackId == StackId);
148 Alloc->AllocTypes |= static_cast<uint8_t>(AllocType);
149 Alloc->TotalSize += TotalSize;
150 } else {
151 AllocStackId = StackId;
152 Alloc = new CallStackTrieNode(AllocType, TotalSize);
153 }
154 Curr = Alloc;
155 continue;
156 }
157 // Update existing caller node if it exists.
158 auto Next = Curr->Callers.find(StackId);
159 if (Next != Curr->Callers.end()) {
160 Curr = Next->second;
161 Curr->AllocTypes |= static_cast<uint8_t>(AllocType);
162 Curr->TotalSize += TotalSize;
163 continue;
164 }
165 // Otherwise add a new caller node.
166 auto *New = new CallStackTrieNode(AllocType, TotalSize);
167 Curr->Callers[StackId] = New;
168 Curr = New;
169 }
170 assert(Curr);
171}
172
174 MDNode *StackMD = getMIBStackNode(MIB);
175 assert(StackMD);
176 std::vector<uint64_t> CallStack;
177 CallStack.reserve(StackMD->getNumOperands());
178 for (const auto &MIBStackIter : StackMD->operands()) {
179 auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter);
180 assert(StackId);
181 CallStack.push_back(StackId->getZExtValue());
182 }
184}
185
187 std::vector<uint64_t> &MIBCallStack,
188 AllocationType AllocType, uint64_t TotalSize) {
189 std::vector<Metadata *> MIBPayload(
190 {buildCallstackMetadata(MIBCallStack, Ctx)});
191 MIBPayload.push_back(
193 if (TotalSize)
194 MIBPayload.push_back(ValueAsMetadata::get(
195 ConstantInt::get(Type::getInt64Ty(Ctx), TotalSize)));
196 return MDNode::get(Ctx, MIBPayload);
197}
198
199// Recursive helper to trim contexts and create metadata nodes.
200// Caller should have pushed Node's loc to MIBCallStack. Doing this in the
201// caller makes it simpler to handle the many early returns in this method.
202bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
203 std::vector<uint64_t> &MIBCallStack,
204 std::vector<Metadata *> &MIBNodes,
205 bool CalleeHasAmbiguousCallerContext) {
206 // Trim context below the first node in a prefix with a single alloc type.
207 // Add an MIB record for the current call stack prefix.
208 if (hasSingleAllocType(Node->AllocTypes)) {
209 MIBNodes.push_back(createMIBNode(
210 Ctx, MIBCallStack, (AllocationType)Node->AllocTypes, Node->TotalSize));
211 return true;
212 }
213
214 // We don't have a single allocation for all the contexts sharing this prefix,
215 // so recursively descend into callers in trie.
216 if (!Node->Callers.empty()) {
217 bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1;
218 bool AddedMIBNodesForAllCallerContexts = true;
219 for (auto &Caller : Node->Callers) {
220 MIBCallStack.push_back(Caller.first);
221 AddedMIBNodesForAllCallerContexts &=
222 buildMIBNodes(Caller.second, Ctx, MIBCallStack, MIBNodes,
223 NodeHasAmbiguousCallerContext);
224 // Remove Caller.
225 MIBCallStack.pop_back();
226 }
227 if (AddedMIBNodesForAllCallerContexts)
228 return true;
229 // We expect that the callers should be forced to add MIBs to disambiguate
230 // the context in this case (see below).
231 assert(!NodeHasAmbiguousCallerContext);
232 }
233
234 // If we reached here, then this node does not have a single allocation type,
235 // and we didn't add metadata for a longer call stack prefix including any of
236 // Node's callers. That means we never hit a single allocation type along all
237 // call stacks with this prefix. This can happen due to recursion collapsing
238 // or the stack being deeper than tracked by the profiler runtime, leading to
239 // contexts with different allocation types being merged. In that case, we
240 // trim the context just below the deepest context split, which is this
241 // node if the callee has an ambiguous caller context (multiple callers),
242 // since the recursive calls above returned false. Conservatively give it
243 // non-cold allocation type.
244 if (!CalleeHasAmbiguousCallerContext)
245 return false;
246 MIBNodes.push_back(createMIBNode(Ctx, MIBCallStack, AllocationType::NotCold,
247 Node->TotalSize));
248 return true;
249}
250
251// Build and attach the minimal necessary MIB metadata. If the alloc has a
252// single allocation type, add a function attribute instead. Returns true if
253// memprof metadata attached, false if not (attribute added).
255 auto &Ctx = CI->getContext();
256 if (hasSingleAllocType(Alloc->AllocTypes)) {
257 addAllocTypeAttribute(Ctx, CI, (AllocationType)Alloc->AllocTypes);
259 assert(Alloc->TotalSize);
260 errs() << "Total size for allocation with location hash " << AllocStackId
261 << " and single alloc type "
262 << getAllocTypeAttributeString((AllocationType)Alloc->AllocTypes)
263 << ": " << Alloc->TotalSize << "\n";
264 }
265 return false;
266 }
267 std::vector<uint64_t> MIBCallStack;
268 MIBCallStack.push_back(AllocStackId);
269 std::vector<Metadata *> MIBNodes;
270 assert(!Alloc->Callers.empty() && "addCallStack has not been called yet");
271 // The last parameter is meant to say whether the callee of the given node
272 // has more than one caller. Here the node being passed in is the alloc
273 // and it has no callees. So it's false.
274 if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes, false)) {
275 assert(MIBCallStack.size() == 1 &&
276 "Should only be left with Alloc's location in stack");
277 CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes));
278 return true;
279 }
280 // If there exists corner case that CallStackTrie has one chain to leaf
281 // and all node in the chain have multi alloc type, conservatively give
282 // it non-cold allocation type.
283 // FIXME: Avoid this case before memory profile created.
285 return false;
286}
287
288template <>
290 const MDNode *N, bool End)
291 : N(N) {
292 if (!N)
293 return;
294 Iter = End ? N->op_end() : N->op_begin();
295}
296
297template <>
300 assert(Iter != N->op_end());
301 ConstantInt *StackIdCInt = mdconst::dyn_extract<ConstantInt>(*Iter);
302 assert(StackIdCInt);
303 return StackIdCInt->getZExtValue();
304}
305
307 assert(N);
308 return mdconst::dyn_extract<ConstantInt>(N->operands().back())
309 ->getZExtValue();
310}
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
bool End
Definition: ELF_riscv.cpp:480
AllocType
cl::opt< float > MemProfLifetimeAccessDensityColdThreshold("memprof-lifetime-access-density-cold-threshold", cl::init(0.05), cl::Hidden, cl::desc("The threshold the lifetime access density (accesses per byte per " "lifetime sec) must be under to consider an allocation cold"))
cl::opt< unsigned > MemProfMinAveLifetimeAccessDensityHotThreshold("memprof-min-ave-lifetime-access-density-hot-threshold", cl::init(1000), cl::Hidden, cl::desc("The minimum TotalLifetimeAccessDensity / AllocCount for an " "allocation to be considered hot"))
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
cl::opt< unsigned > MemProfAveLifetimeColdThreshold("memprof-ave-lifetime-cold-threshold", cl::init(200), cl::Hidden, cl::desc("The average lifetime (s) for an allocation to be considered " "cold"))
static MDNode * createMIBNode(LLVMContext &Ctx, std::vector< uint64_t > &MIBCallStack, AllocationType AllocType, uint64_t TotalSize)
static void addAllocTypeAttribute(LLVMContext &Ctx, CallBase *CI, AllocationType AllocType)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Definition: Attributes.cpp:94
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1236
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
Definition: InstrTypes.h:1574
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
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:155
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1635
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Metadata node.
Definition: Metadata.h:1067
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1428
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1426
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1434
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:600
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt64Ty(LLVMContext &C)
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:495
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
void addCallStack(AllocationType AllocType, ArrayRef< uint64_t > StackIds, uint64_t TotalSize=0)
Add a call stack context with the given allocation type to the Trie.
bool buildAndAttachMIBMetadata(CallBase *CI)
Build and attach the minimal necessary MIB metadata.
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
MDNode * buildCallstackMetadata(ArrayRef< uint64_t > CallStack, LLVMContext &Ctx)
Build callstack metadata from the provided list of call stack ids.
AllocationType getAllocType(uint64_t TotalLifetimeAccessDensity, uint64_t AllocCount, uint64_t TotalLifetime)
Return the allocation type for a given set of memory profile values.
AllocationType getMIBAllocType(const MDNode *MIB)
Returns the allocation type from an MIB metadata node.
uint64_t getMIBTotalSize(const MDNode *MIB)
Returns the total size from an MIB metadata node, or 0 if it was not recorded.
bool hasSingleAllocType(uint8_t AllocTypes)
True if the AllocTypes bitmask contains just a single type.
std::string getAllocTypeAttributeString(AllocationType Type)
Returns the string to use in attributes with the given type.
MDNode * getMIBStackNode(const MDNode *MIB)
Returns the stack node from an MIB metadata node.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition: bit.h:385
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
#define N