LLVM 24.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 for
10// profile-guided memory optimization (MemPGO).
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_MEMORYPROFILEINFO_H
15#define LLVM_ANALYSIS_MEMORYPROFILEINFO_H
16
17#include "llvm/IR/Metadata.h"
20#include <map>
21
22namespace llvm {
23
25
26namespace memprof {
27
28/// Whether the alloc memeprof metadata will include context size info for all
29/// MIBs.
31
32/// Whether the alloc memprof metadata may include context size info for some
33/// MIBs (but possibly not all).
35
36/// Whether we need to record the context size info in the alloc trie used to
37/// build metadata.
39
40/// Build callstack metadata from the provided list of call stack ids. Returns
41/// the resulting metadata node.
43 LLVMContext &Ctx);
44
45/// Returns the stack node from an MIB metadata node.
47
48/// Returns the allocation type from an MIB metadata node.
50
51/// Returns the string to use in attributes with the given type. The combination
52/// of NotCold and Cold (see isAmbiguousAllocType) maps to "ambiguous".
54
55/// True if the AllocTypes bitmask contains just a single type.
56LLVM_ABI bool hasSingleAllocType(uint8_t AllocTypes);
57
58/// True if the AllocTypes bitmask contains both NotCold and Cold, i.e. the
59/// allocation reaches contexts of both types that could not be disambiguated
60/// (e.g. via cloning).
62
63/// Removes any existing "ambiguous" memprof attribute. Called before we apply a
64/// specific allocation type such as "cold", "notcold", or "hot".
66
67/// Adds an "ambiguous" memprof attribute to call with a matched allocation
68/// profile but that we haven't yet been able to disambiguate.
70
71// During matching we also keep the AllocationType along with the
72// ContextTotalSize in the Trie for the most accurate reporting when we decide
73// to hint unambiguously where there is a dominant type. We don't put the
74// AllocationType in the ContextTotalSize struct as it isn't needed there
75// during the LTO step, because due to context trimming a summarized
76// context with its allocation type can correspond to multiple context/size
77// pairs. Here the redundancy is a short-lived convenience.
78using ContextSizeTypePair = std::pair<ContextTotalSize, AllocationType>;
79
80/// Class to build a trie of call stack contexts for a particular profiled
81/// allocation call, along with their associated allocation types.
82/// The allocation will be at the root of the trie, which is then used to
83/// compute the minimum lists of context ids needed to associate a call context
84/// with a single allocation type.
86private:
87 struct CallStackTrieNode {
88 // Allocation types for call context sharing the context prefix at this
89 // node.
90 uint8_t AllocTypes;
91 // If the user has requested reporting of hinted sizes, keep track of the
92 // associated full stack id and profiled sizes. Can have more than one
93 // after trimming (e.g. when building from metadata). This is only placed on
94 // the last (root-most) trie node for each allocation context. Also
95 // track the original allocation type of the context.
96 std::vector<ContextSizeTypePair> ContextInfo;
97 // Map of caller stack id to the corresponding child Trie node.
98 std::map<uint64_t, CallStackTrieNode *> Callers;
99 CallStackTrieNode(AllocationType Type)
100 : AllocTypes(static_cast<uint8_t>(Type)) {}
101 void addAllocType(AllocationType AllocType) {
102 AllocTypes |= static_cast<uint8_t>(AllocType);
103 }
104 void removeAllocType(AllocationType AllocType) {
105 AllocTypes &= ~static_cast<uint8_t>(AllocType);
106 }
107 bool hasAllocType(AllocationType AllocType) const {
108 return AllocTypes & static_cast<uint8_t>(AllocType);
109 }
110 };
111
112 // The node for the allocation at the root.
113 CallStackTrieNode *Alloc = nullptr;
114 // The allocation's leaf stack id.
115 uint64_t AllocStackId = 0;
116
117 // If the client provides a remarks emitter object, we will emit remarks on
118 // allocations for which we apply non-context sensitive allocation hints.
120
121 // The maximum size of a cold allocation context, from the profile summary.
122 uint64_t MaxColdSize;
123
124 // Tracks whether we have built the Trie from existing MD_memprof metadata. We
125 // apply different heuristics for determining whether to discard non-cold
126 // contexts when rebuilding as we have lost information available during the
127 // original profile match.
128 bool BuiltFromExistingMetadata = false;
129
130 void deleteTrieNode(CallStackTrieNode *Node) {
131 if (!Node)
132 return;
133 for (auto C : Node->Callers)
134 deleteTrieNode(C.second);
135 delete Node;
136 }
137
138 // Recursively build up a complete list of context information from the
139 // trie nodes reached form the given Node, including each context's
140 // ContextTotalSize and AllocationType, for hint size reporting.
141 void collectContextInfo(CallStackTrieNode *Node,
142 std::vector<ContextSizeTypePair> &ContextInfo);
143
144 // Recursively convert hot allocation types to notcold, since we don't
145 // actually do any cloning for hot contexts, to facilitate more aggressive
146 // trimming of contexts.
147 void convertHotToNotCold(CallStackTrieNode *Node);
148
149 // Recursive helper to trim contexts and create metadata nodes.
150 bool buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
151 std::vector<uint64_t> &MIBCallStack,
152 std::vector<Metadata *> &MIBNodes,
153 bool CalleeHasAmbiguousCallerContext, uint64_t &TotalBytes,
154 uint64_t &ColdBytes);
155
156public:
158 uint64_t MaxColdSize = 0)
159 : ORE(ORE), MaxColdSize(MaxColdSize) {}
160 ~CallStackTrie() { deleteTrieNode(Alloc); }
161
162 bool empty() const { return Alloc == nullptr; }
163
164 /// Add a call stack context with the given allocation type to the Trie.
165 /// The context is represented by the list of stack ids (computed during
166 /// matching via a debug location hash), expected to be in order from the
167 /// allocation call down to the bottom of the call stack (i.e. callee to
168 /// caller order).
169 LLVM_ABI void
171 std::vector<ContextTotalSize> ContextSizeInfo = {});
172
173 /// Add the call stack context along with its allocation type from the MIB
174 /// metadata to the Trie.
175 LLVM_ABI void addCallStack(MDNode *MIB);
176
177 /// Build and attach the minimal necessary MIB metadata. If the alloc has a
178 /// single allocation type, add a function attribute instead. The reason for
179 /// adding an attribute in this case is that it matches how the behavior for
180 /// allocation calls will be communicated to lib call simplification after
181 /// cloning or another optimization to distinguish the allocation types,
182 /// which is lower overhead and more direct than maintaining this metadata.
183 /// Returns true if memprof metadata attached, false if not (attribute added).
185
186 /// Add an attribute for the given allocation type to the call instruction.
187 /// If hinted by reporting is enabled, a message is emitted with the given
188 /// descriptor used to identify the category of single allocation type.
190 StringRef Descriptor);
191};
192
193/// Helper class to iterate through stack ids in both metadata (memprof MIB and
194/// callsite) and the corresponding ThinLTO summary data structures
195/// (CallsiteInfo and MIBInfo). This simplifies implementation of client code
196/// which doesn't need to worry about whether we are operating with IR (Regular
197/// LTO), or summary (ThinLTO).
198template <class NodeT, class IteratorT> class CallStack {
199public:
200 CallStack(const NodeT *N = nullptr) : N(N) {}
201
202 // Implement minimum required methods for range-based for loop.
203 // The default implementation assumes we are operating on ThinLTO data
204 // structures, which have a vector of StackIdIndices. There are specialized
205 // versions provided to iterate through metadata.
207 const NodeT *N = nullptr;
208 IteratorT Iter;
209 CallStackIterator(const NodeT *N, bool End);
211 bool operator==(const CallStackIterator &rhs) { return Iter == rhs.Iter; }
212 bool operator!=(const CallStackIterator &rhs) { return !(*this == rhs); }
213 void operator++() { ++Iter; }
214 };
215
216 bool empty() const { return N == nullptr; }
217
218 CallStackIterator begin() const;
219 CallStackIterator end() const { return CallStackIterator(N, /*End*/ true); }
220 CallStackIterator beginAfterSharedPrefix(const CallStack &Other);
221 uint64_t back() const;
222
223private:
224 const NodeT *N = nullptr;
225};
226
227template <class NodeT, class IteratorT>
229 const NodeT *N, bool End)
230 : N(N) {
231 if (!N) {
232 Iter = nullptr;
233 return;
234 }
235 Iter = End ? N->StackIdIndices.end() : N->StackIdIndices.begin();
236}
237
238template <class NodeT, class IteratorT>
240 assert(Iter != N->StackIdIndices.end());
241 return *Iter;
242}
243
244template <class NodeT, class IteratorT>
246 assert(N);
247 return N->StackIdIndices.back();
248}
249
250template <class NodeT, class IteratorT>
253 return CallStackIterator(N, /*End*/ false);
254}
255
256template <class NodeT, class IteratorT>
259 CallStackIterator Cur = begin();
260 for (CallStackIterator OtherCur = Other.begin();
261 Cur != end() && OtherCur != Other.end(); ++Cur, ++OtherCur)
262 assert(*Cur == *OtherCur);
263 return Cur;
264}
265
266/// Specializations for iterating through IR metadata stack contexts.
267template <>
270 const MDNode *N, bool End);
271template <>
274template <>
276
277} // end namespace memprof
278} // end namespace llvm
279
280#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
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...
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1081
The optimization diagnostic interface.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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
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.
std::pair< ContextTotalSize, AllocationType > ContextSizeTypePair
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
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 bool isAmbiguousAllocType(uint8_t AllocTypes)
True if the AllocTypes bitmask contains both NotCold and Cold, i.e.
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.
LLVM_ABI void removeAnyExistingAmbiguousAttribute(CallBase *CB)
Removes any existing "ambiguous" memprof attribute.
LLVM_ABI void addAmbiguousAttribute(CallBase *CB)
Adds an "ambiguous" memprof attribute to call with a matched allocation profile but that we haven't y...
This is an optimization pass for GlobalISel generic memory operations.
@ Other
Any other memory.
Definition ModRef.h:68
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
#define N
bool operator!=(const CallStackIterator &rhs)
bool operator==(const CallStackIterator &rhs)