LLVM 22.0.0git
MemoryProfileInfo.h
Go to the documentation of this file.
1//===- llvm/Analysis/MemoryProfileInfo.h - memory profile info ---*- C++ -*-==//
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
13#ifndef LLVM_ANALYSIS_MEMORYPROFILEINFO_H
14#define LLVM_ANALYSIS_MEMORYPROFILEINFO_H
15
16#include "llvm/IR/Metadata.h"
19#include <map>
20
21namespace llvm {
22
23class OptimizationRemarkEmitter;
24
25namespace memprof {
26
27/// Whether the alloc memeprof metadata will include context size info for all
28/// MIBs.
30
31/// Whether the alloc memprof metadata may include context size info for some
32/// MIBs (but possibly not all).
34
35/// Whether we need to record the context size info in the alloc trie used to
36/// build metadata.
38
39/// Build callstack metadata from the provided list of call stack ids. Returns
40/// the resulting metadata node.
42 LLVMContext &Ctx);
43
44/// Build metadata from the provided list of full stack id and profiled size, to
45/// use when reporting of hinted sizes is enabled.
48 LLVMContext &Ctx);
49
50/// Returns the stack node from an MIB metadata node.
52
53/// Returns the allocation type from an MIB metadata node.
55
56/// Returns the string to use in attributes with the given type.
58
59/// True if the AllocTypes bitmask contains just a single type.
60LLVM_ABI bool hasSingleAllocType(uint8_t AllocTypes);
61
62/// Class to build a trie of call stack contexts for a particular profiled
63/// allocation call, along with their associated allocation types.
64/// The allocation will be at the root of the trie, which is then used to
65/// compute the minimum lists of context ids needed to associate a call context
66/// with a single allocation type.
68private:
69 struct CallStackTrieNode {
70 // Allocation types for call context sharing the context prefix at this
71 // node.
72 uint8_t AllocTypes;
73 // If the user has requested reporting of hinted sizes, keep track of the
74 // associated full stack id and profiled sizes. Can have more than one
75 // after trimming (e.g. when building from metadata). This is only placed on
76 // the last (root-most) trie node for each allocation context.
77 std::vector<ContextTotalSize> ContextSizeInfo;
78 // Map of caller stack id to the corresponding child Trie node.
79 std::map<uint64_t, CallStackTrieNode *> Callers;
80 CallStackTrieNode(AllocationType Type)
81 : AllocTypes(static_cast<uint8_t>(Type)) {}
82 void addAllocType(AllocationType AllocType) {
83 AllocTypes |= static_cast<uint8_t>(AllocType);
84 }
85 void removeAllocType(AllocationType AllocType) {
86 AllocTypes &= ~static_cast<uint8_t>(AllocType);
87 }
88 bool hasAllocType(AllocationType AllocType) const {
89 return AllocTypes & static_cast<uint8_t>(AllocType);
90 }
91 };
92
93 // The node for the allocation at the root.
94 CallStackTrieNode *Alloc = nullptr;
95 // The allocation's leaf stack id.
96 uint64_t AllocStackId = 0;
97
98 // If the client provides a remarks emitter object, we will emit remarks on
99 // allocations for which we apply non-context sensitive allocation hints.
101
102 // The maximum size of a cold allocation context, from the profile summary.
103 uint64_t MaxColdSize;
104
105 // Tracks whether we have built the Trie from existing MD_memprof metadata. We
106 // apply different heuristics for determining whether to discard non-cold
107 // contexts when rebuilding as we have lost information available during the
108 // original profile match.
109 bool BuiltFromExistingMetadata = false;
110
111 void deleteTrieNode(CallStackTrieNode *Node) {
112 if (!Node)
113 return;
114 for (auto C : Node->Callers)
115 deleteTrieNode(C.second);
116 delete Node;
117 }
118
119 // Recursively build up a complete list of context size information from the
120 // trie nodes reached form the given Node, for hint size reporting.
121 void collectContextSizeInfo(CallStackTrieNode *Node,
122 std::vector<ContextTotalSize> &ContextSizeInfo);
123
124 // Recursively convert hot allocation types to notcold, since we don't
125 // actually do any cloning for hot contexts, to facilitate more aggressive
126 // pruning of contexts.
127 void convertHotToNotCold(CallStackTrieNode *Node);
128
129 // Recursive helper to trim contexts and create metadata nodes.
130 bool buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
131 std::vector<uint64_t> &MIBCallStack,
132 std::vector<Metadata *> &MIBNodes,
133 bool CalleeHasAmbiguousCallerContext, uint64_t &TotalBytes,
134 uint64_t &ColdBytes);
135
136public:
138 uint64_t MaxColdSize = 0)
139 : ORE(ORE), MaxColdSize(MaxColdSize) {}
140 ~CallStackTrie() { deleteTrieNode(Alloc); }
141
142 bool empty() const { return Alloc == nullptr; }
143
144 /// Add a call stack context with the given allocation type to the Trie.
145 /// The context is represented by the list of stack ids (computed during
146 /// matching via a debug location hash), expected to be in order from the
147 /// allocation call down to the bottom of the call stack (i.e. callee to
148 /// caller order).
149 LLVM_ABI void
151 std::vector<ContextTotalSize> ContextSizeInfo = {});
152
153 /// Add the call stack context along with its allocation type from the MIB
154 /// metadata to the Trie.
155 LLVM_ABI void addCallStack(MDNode *MIB);
156
157 /// Build and attach the minimal necessary MIB metadata. If the alloc has a
158 /// single allocation type, add a function attribute instead. The reason for
159 /// adding an attribute in this case is that it matches how the behavior for
160 /// allocation calls will be communicated to lib call simplification after
161 /// cloning or another optimization to distinguish the allocation types,
162 /// which is lower overhead and more direct than maintaining this metadata.
163 /// Returns true if memprof metadata attached, false if not (attribute added).
165
166 /// Add an attribute for the given allocation type to the call instruction.
167 /// If hinted by reporting is enabled, a message is emitted with the given
168 /// descriptor used to identify the category of single allocation type.
170 StringRef Descriptor);
171};
172
173/// Helper class to iterate through stack ids in both metadata (memprof MIB and
174/// callsite) and the corresponding ThinLTO summary data structures
175/// (CallsiteInfo and MIBInfo). This simplifies implementation of client code
176/// which doesn't need to worry about whether we are operating with IR (Regular
177/// LTO), or summary (ThinLTO).
178template <class NodeT, class IteratorT> class CallStack {
179public:
180 CallStack(const NodeT *N = nullptr) : N(N) {}
181
182 // Implement minimum required methods for range-based for loop.
183 // The default implementation assumes we are operating on ThinLTO data
184 // structures, which have a vector of StackIdIndices. There are specialized
185 // versions provided to iterate through metadata.
187 const NodeT *N = nullptr;
188 IteratorT Iter;
189 CallStackIterator(const NodeT *N, bool End);
191 bool operator==(const CallStackIterator &rhs) { return Iter == rhs.Iter; }
192 bool operator!=(const CallStackIterator &rhs) { return !(*this == rhs); }
193 void operator++() { ++Iter; }
194 };
195
196 bool empty() const { return N == nullptr; }
197
198 CallStackIterator begin() const;
199 CallStackIterator end() const { return CallStackIterator(N, /*End*/ true); }
200 CallStackIterator beginAfterSharedPrefix(const CallStack &Other);
201 uint64_t back() const;
202
203private:
204 const NodeT *N = nullptr;
205};
206
207template <class NodeT, class IteratorT>
209 const NodeT *N, bool End)
210 : N(N) {
211 if (!N) {
212 Iter = nullptr;
213 return;
214 }
215 Iter = End ? N->StackIdIndices.end() : N->StackIdIndices.begin();
216}
217
218template <class NodeT, class IteratorT>
220 assert(Iter != N->StackIdIndices.end());
221 return *Iter;
222}
223
224template <class NodeT, class IteratorT>
226 assert(N);
227 return N->StackIdIndices.back();
228}
229
230template <class NodeT, class IteratorT>
233 return CallStackIterator(N, /*End*/ false);
234}
235
236template <class NodeT, class IteratorT>
239 CallStackIterator Cur = begin();
240 for (CallStackIterator OtherCur = Other.begin();
241 Cur != end() && OtherCur != Other.end(); ++Cur, ++OtherCur)
242 assert(*Cur == *OtherCur);
243 return Cur;
244}
245
246/// Specializations for iterating through IR metadata stack contexts.
247template <>
250 const MDNode *N, bool End);
251template <>
254template <>
256
257} // end namespace memprof
258} // end namespace llvm
259
260#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition: Compiler.h:213
bool End
Definition: ELF_riscv.cpp:480
AllocType
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Metadata node.
Definition: Metadata.h:1077
The optimization diagnostic interface.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Class to build a trie of call stack contexts for a particular profiled allocation call,...
LLVM_ABI void addCallStack(AllocationType AllocType, ArrayRef< uint64_t > StackIds, std::vector< ContextTotalSize > ContextSizeInfo={})
Add a call stack context with the given allocation type to the Trie.
LLVM_ABI void addSingleAllocTypeAttribute(CallBase *CI, AllocationType AT, StringRef Descriptor)
Add an attribute for the given allocation type to the call instruction.
LLVM_ABI bool buildAndAttachMIBMetadata(CallBase *CI)
Build and attach the minimal necessary MIB metadata.
CallStackTrie(OptimizationRemarkEmitter *ORE=nullptr, uint64_t MaxColdSize=0)
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
CallStack(const NodeT *N=nullptr)
CallStackIterator begin() const
CallStackIterator beginAfterSharedPrefix(const CallStack &Other)
CallStackIterator end() const
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
LLVM_ABI MDNode * buildCallstackMetadata(ArrayRef< uint64_t > CallStack, LLVMContext &Ctx)
Build callstack metadata from the provided list of call stack ids.
LLVM_ABI bool recordContextSizeInfoForAnalysis()
Whether we need to record the context size info in the alloc trie used to build metadata.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
LLVM_ABI MDNode * buildContextSizeMetadata(ArrayRef< ContextTotalSize > ContextSizeInfo, LLVMContext &Ctx)
Build metadata from the provided list of full stack id and profiled size, to use when reporting of hi...
LLVM_ABI AllocationType getMIBAllocType(const MDNode *MIB)
Returns the allocation type from an MIB metadata node.
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
LLVM_ABI bool hasSingleAllocType(uint8_t AllocTypes)
True if the AllocTypes bitmask contains just a single type.
LLVM_ABI std::string getAllocTypeAttributeString(AllocationType Type)
Returns the string to use in attributes with the given type.
LLVM_ABI 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
@ Other
Any other memory.
#define N
bool operator!=(const CallStackIterator &rhs)
bool operator==(const CallStackIterator &rhs)