xref: /freebsd-src/contrib/llvm-project/llvm/lib/Analysis/MemoryProfileInfo.cpp (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
1*fcaf7f86SDimitry Andric //===-- MemoryProfileInfo.cpp - memory profile info ------------------------==//
2*fcaf7f86SDimitry Andric //
3*fcaf7f86SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*fcaf7f86SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*fcaf7f86SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*fcaf7f86SDimitry Andric //
7*fcaf7f86SDimitry Andric //===----------------------------------------------------------------------===//
8*fcaf7f86SDimitry Andric //
9*fcaf7f86SDimitry Andric // This file contains utilities to analyze memory profile information.
10*fcaf7f86SDimitry Andric //
11*fcaf7f86SDimitry Andric //===----------------------------------------------------------------------===//
12*fcaf7f86SDimitry Andric 
13*fcaf7f86SDimitry Andric #include "llvm/Analysis/MemoryProfileInfo.h"
14*fcaf7f86SDimitry Andric #include "llvm/Support/CommandLine.h"
15*fcaf7f86SDimitry Andric 
16*fcaf7f86SDimitry Andric using namespace llvm;
17*fcaf7f86SDimitry Andric using namespace llvm::memprof;
18*fcaf7f86SDimitry Andric 
19*fcaf7f86SDimitry Andric #define DEBUG_TYPE "memory-profile-info"
20*fcaf7f86SDimitry Andric 
21*fcaf7f86SDimitry Andric // Upper bound on accesses per byte for marking an allocation cold.
22*fcaf7f86SDimitry Andric cl::opt<float> MemProfAccessesPerByteColdThreshold(
23*fcaf7f86SDimitry Andric     "memprof-accesses-per-byte-cold-threshold", cl::init(10.0), cl::Hidden,
24*fcaf7f86SDimitry Andric     cl::desc("The threshold the accesses per byte must be under to consider "
25*fcaf7f86SDimitry Andric              "an allocation cold"));
26*fcaf7f86SDimitry Andric 
27*fcaf7f86SDimitry Andric // Lower bound on lifetime to mark an allocation cold (in addition to accesses
28*fcaf7f86SDimitry Andric // per byte above). This is to avoid pessimizing short lived objects.
29*fcaf7f86SDimitry Andric cl::opt<unsigned> MemProfMinLifetimeColdThreshold(
30*fcaf7f86SDimitry Andric     "memprof-min-lifetime-cold-threshold", cl::init(200), cl::Hidden,
31*fcaf7f86SDimitry Andric     cl::desc("The minimum lifetime (s) for an allocation to be considered "
32*fcaf7f86SDimitry Andric              "cold"));
33*fcaf7f86SDimitry Andric 
34*fcaf7f86SDimitry Andric AllocationType llvm::memprof::getAllocType(uint64_t MaxAccessCount,
35*fcaf7f86SDimitry Andric                                            uint64_t MinSize,
36*fcaf7f86SDimitry Andric                                            uint64_t MinLifetime) {
37*fcaf7f86SDimitry Andric   if (((float)MaxAccessCount) / MinSize < MemProfAccessesPerByteColdThreshold &&
38*fcaf7f86SDimitry Andric       // MinLifetime is expected to be in ms, so convert the threshold to ms.
39*fcaf7f86SDimitry Andric       MinLifetime >= MemProfMinLifetimeColdThreshold * 1000)
40*fcaf7f86SDimitry Andric     return AllocationType::Cold;
41*fcaf7f86SDimitry Andric   return AllocationType::NotCold;
42*fcaf7f86SDimitry Andric }
43*fcaf7f86SDimitry Andric 
44*fcaf7f86SDimitry Andric MDNode *llvm::memprof::buildCallstackMetadata(ArrayRef<uint64_t> CallStack,
45*fcaf7f86SDimitry Andric                                               LLVMContext &Ctx) {
46*fcaf7f86SDimitry Andric   std::vector<Metadata *> StackVals;
47*fcaf7f86SDimitry Andric   for (auto Id : CallStack) {
48*fcaf7f86SDimitry Andric     auto *StackValMD =
49*fcaf7f86SDimitry Andric         ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id));
50*fcaf7f86SDimitry Andric     StackVals.push_back(StackValMD);
51*fcaf7f86SDimitry Andric   }
52*fcaf7f86SDimitry Andric   return MDNode::get(Ctx, StackVals);
53*fcaf7f86SDimitry Andric }
54*fcaf7f86SDimitry Andric 
55*fcaf7f86SDimitry Andric MDNode *llvm::memprof::getMIBStackNode(const MDNode *MIB) {
56*fcaf7f86SDimitry Andric   assert(MIB->getNumOperands() == 2);
57*fcaf7f86SDimitry Andric   // The stack metadata is the first operand of each memprof MIB metadata.
58*fcaf7f86SDimitry Andric   return cast<MDNode>(MIB->getOperand(0));
59*fcaf7f86SDimitry Andric }
60*fcaf7f86SDimitry Andric 
61*fcaf7f86SDimitry Andric AllocationType llvm::memprof::getMIBAllocType(const MDNode *MIB) {
62*fcaf7f86SDimitry Andric   assert(MIB->getNumOperands() == 2);
63*fcaf7f86SDimitry Andric   // The allocation type is currently the second operand of each memprof
64*fcaf7f86SDimitry Andric   // MIB metadata. This will need to change as we add additional allocation
65*fcaf7f86SDimitry Andric   // types that can be applied based on the allocation profile data.
66*fcaf7f86SDimitry Andric   auto *MDS = dyn_cast<MDString>(MIB->getOperand(1));
67*fcaf7f86SDimitry Andric   assert(MDS);
68*fcaf7f86SDimitry Andric   if (MDS->getString().equals("cold"))
69*fcaf7f86SDimitry Andric     return AllocationType::Cold;
70*fcaf7f86SDimitry Andric   return AllocationType::NotCold;
71*fcaf7f86SDimitry Andric }
72*fcaf7f86SDimitry Andric 
73*fcaf7f86SDimitry Andric static std::string getAllocTypeAttributeString(AllocationType Type) {
74*fcaf7f86SDimitry Andric   switch (Type) {
75*fcaf7f86SDimitry Andric   case AllocationType::NotCold:
76*fcaf7f86SDimitry Andric     return "notcold";
77*fcaf7f86SDimitry Andric     break;
78*fcaf7f86SDimitry Andric   case AllocationType::Cold:
79*fcaf7f86SDimitry Andric     return "cold";
80*fcaf7f86SDimitry Andric     break;
81*fcaf7f86SDimitry Andric   default:
82*fcaf7f86SDimitry Andric     assert(false && "Unexpected alloc type");
83*fcaf7f86SDimitry Andric   }
84*fcaf7f86SDimitry Andric   llvm_unreachable("invalid alloc type");
85*fcaf7f86SDimitry Andric }
86*fcaf7f86SDimitry Andric 
87*fcaf7f86SDimitry Andric static void addAllocTypeAttribute(LLVMContext &Ctx, CallBase *CI,
88*fcaf7f86SDimitry Andric                                   AllocationType AllocType) {
89*fcaf7f86SDimitry Andric   auto AllocTypeString = getAllocTypeAttributeString(AllocType);
90*fcaf7f86SDimitry Andric   auto A = llvm::Attribute::get(Ctx, "memprof", AllocTypeString);
91*fcaf7f86SDimitry Andric   CI->addFnAttr(A);
92*fcaf7f86SDimitry Andric }
93*fcaf7f86SDimitry Andric 
94*fcaf7f86SDimitry Andric static bool hasSingleAllocType(uint8_t AllocTypes) {
95*fcaf7f86SDimitry Andric   const unsigned NumAllocTypes = countPopulation(AllocTypes);
96*fcaf7f86SDimitry Andric   assert(NumAllocTypes != 0);
97*fcaf7f86SDimitry Andric   return NumAllocTypes == 1;
98*fcaf7f86SDimitry Andric }
99*fcaf7f86SDimitry Andric 
100*fcaf7f86SDimitry Andric void CallStackTrie::addCallStack(AllocationType AllocType,
101*fcaf7f86SDimitry Andric                                  ArrayRef<uint64_t> StackIds) {
102*fcaf7f86SDimitry Andric   bool First = true;
103*fcaf7f86SDimitry Andric   CallStackTrieNode *Curr = nullptr;
104*fcaf7f86SDimitry Andric   for (auto StackId : StackIds) {
105*fcaf7f86SDimitry Andric     // If this is the first stack frame, add or update alloc node.
106*fcaf7f86SDimitry Andric     if (First) {
107*fcaf7f86SDimitry Andric       First = false;
108*fcaf7f86SDimitry Andric       if (Alloc) {
109*fcaf7f86SDimitry Andric         assert(AllocStackId == StackId);
110*fcaf7f86SDimitry Andric         Alloc->AllocTypes |= static_cast<uint8_t>(AllocType);
111*fcaf7f86SDimitry Andric       } else {
112*fcaf7f86SDimitry Andric         AllocStackId = StackId;
113*fcaf7f86SDimitry Andric         Alloc = new CallStackTrieNode(AllocType);
114*fcaf7f86SDimitry Andric       }
115*fcaf7f86SDimitry Andric       Curr = Alloc;
116*fcaf7f86SDimitry Andric       continue;
117*fcaf7f86SDimitry Andric     }
118*fcaf7f86SDimitry Andric     // Update existing caller node if it exists.
119*fcaf7f86SDimitry Andric     auto Next = Curr->Callers.find(StackId);
120*fcaf7f86SDimitry Andric     if (Next != Curr->Callers.end()) {
121*fcaf7f86SDimitry Andric       Curr = Next->second;
122*fcaf7f86SDimitry Andric       Curr->AllocTypes |= static_cast<uint8_t>(AllocType);
123*fcaf7f86SDimitry Andric       continue;
124*fcaf7f86SDimitry Andric     }
125*fcaf7f86SDimitry Andric     // Otherwise add a new caller node.
126*fcaf7f86SDimitry Andric     auto *New = new CallStackTrieNode(AllocType);
127*fcaf7f86SDimitry Andric     Curr->Callers[StackId] = New;
128*fcaf7f86SDimitry Andric     Curr = New;
129*fcaf7f86SDimitry Andric   }
130*fcaf7f86SDimitry Andric   assert(Curr);
131*fcaf7f86SDimitry Andric }
132*fcaf7f86SDimitry Andric 
133*fcaf7f86SDimitry Andric void CallStackTrie::addCallStack(MDNode *MIB) {
134*fcaf7f86SDimitry Andric   MDNode *StackMD = getMIBStackNode(MIB);
135*fcaf7f86SDimitry Andric   assert(StackMD);
136*fcaf7f86SDimitry Andric   std::vector<uint64_t> CallStack;
137*fcaf7f86SDimitry Andric   CallStack.reserve(StackMD->getNumOperands());
138*fcaf7f86SDimitry Andric   for (auto &MIBStackIter : StackMD->operands()) {
139*fcaf7f86SDimitry Andric     auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter);
140*fcaf7f86SDimitry Andric     assert(StackId);
141*fcaf7f86SDimitry Andric     CallStack.push_back(StackId->getZExtValue());
142*fcaf7f86SDimitry Andric   }
143*fcaf7f86SDimitry Andric   addCallStack(getMIBAllocType(MIB), CallStack);
144*fcaf7f86SDimitry Andric }
145*fcaf7f86SDimitry Andric 
146*fcaf7f86SDimitry Andric static MDNode *createMIBNode(LLVMContext &Ctx,
147*fcaf7f86SDimitry Andric                              std::vector<uint64_t> &MIBCallStack,
148*fcaf7f86SDimitry Andric                              AllocationType AllocType) {
149*fcaf7f86SDimitry Andric   std::vector<Metadata *> MIBPayload(
150*fcaf7f86SDimitry Andric       {buildCallstackMetadata(MIBCallStack, Ctx)});
151*fcaf7f86SDimitry Andric   MIBPayload.push_back(
152*fcaf7f86SDimitry Andric       MDString::get(Ctx, getAllocTypeAttributeString(AllocType)));
153*fcaf7f86SDimitry Andric   return MDNode::get(Ctx, MIBPayload);
154*fcaf7f86SDimitry Andric }
155*fcaf7f86SDimitry Andric 
156*fcaf7f86SDimitry Andric // Recursive helper to trim contexts and create metadata nodes.
157*fcaf7f86SDimitry Andric // Caller should have pushed Node's loc to MIBCallStack. Doing this in the
158*fcaf7f86SDimitry Andric // caller makes it simpler to handle the many early returns in this method.
159*fcaf7f86SDimitry Andric bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
160*fcaf7f86SDimitry Andric                                   std::vector<uint64_t> &MIBCallStack,
161*fcaf7f86SDimitry Andric                                   std::vector<Metadata *> &MIBNodes,
162*fcaf7f86SDimitry Andric                                   bool CalleeHasAmbiguousCallerContext) {
163*fcaf7f86SDimitry Andric   // Trim context below the first node in a prefix with a single alloc type.
164*fcaf7f86SDimitry Andric   // Add an MIB record for the current call stack prefix.
165*fcaf7f86SDimitry Andric   if (hasSingleAllocType(Node->AllocTypes)) {
166*fcaf7f86SDimitry Andric     MIBNodes.push_back(
167*fcaf7f86SDimitry Andric         createMIBNode(Ctx, MIBCallStack, (AllocationType)Node->AllocTypes));
168*fcaf7f86SDimitry Andric     return true;
169*fcaf7f86SDimitry Andric   }
170*fcaf7f86SDimitry Andric 
171*fcaf7f86SDimitry Andric   // We don't have a single allocation for all the contexts sharing this prefix,
172*fcaf7f86SDimitry Andric   // so recursively descend into callers in trie.
173*fcaf7f86SDimitry Andric   if (!Node->Callers.empty()) {
174*fcaf7f86SDimitry Andric     bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1;
175*fcaf7f86SDimitry Andric     bool AddedMIBNodesForAllCallerContexts = true;
176*fcaf7f86SDimitry Andric     for (auto &Caller : Node->Callers) {
177*fcaf7f86SDimitry Andric       MIBCallStack.push_back(Caller.first);
178*fcaf7f86SDimitry Andric       AddedMIBNodesForAllCallerContexts &=
179*fcaf7f86SDimitry Andric           buildMIBNodes(Caller.second, Ctx, MIBCallStack, MIBNodes,
180*fcaf7f86SDimitry Andric                         NodeHasAmbiguousCallerContext);
181*fcaf7f86SDimitry Andric       // Remove Caller.
182*fcaf7f86SDimitry Andric       MIBCallStack.pop_back();
183*fcaf7f86SDimitry Andric     }
184*fcaf7f86SDimitry Andric     if (AddedMIBNodesForAllCallerContexts)
185*fcaf7f86SDimitry Andric       return true;
186*fcaf7f86SDimitry Andric     // We expect that the callers should be forced to add MIBs to disambiguate
187*fcaf7f86SDimitry Andric     // the context in this case (see below).
188*fcaf7f86SDimitry Andric     assert(!NodeHasAmbiguousCallerContext);
189*fcaf7f86SDimitry Andric   }
190*fcaf7f86SDimitry Andric 
191*fcaf7f86SDimitry Andric   // If we reached here, then this node does not have a single allocation type,
192*fcaf7f86SDimitry Andric   // and we didn't add metadata for a longer call stack prefix including any of
193*fcaf7f86SDimitry Andric   // Node's callers. That means we never hit a single allocation type along all
194*fcaf7f86SDimitry Andric   // call stacks with this prefix. This can happen due to recursion collapsing
195*fcaf7f86SDimitry Andric   // or the stack being deeper than tracked by the profiler runtime, leading to
196*fcaf7f86SDimitry Andric   // contexts with different allocation types being merged. In that case, we
197*fcaf7f86SDimitry Andric   // trim the context just below the deepest context split, which is this
198*fcaf7f86SDimitry Andric   // node if the callee has an ambiguous caller context (multiple callers),
199*fcaf7f86SDimitry Andric   // since the recursive calls above returned false. Conservatively give it
200*fcaf7f86SDimitry Andric   // non-cold allocation type.
201*fcaf7f86SDimitry Andric   if (!CalleeHasAmbiguousCallerContext)
202*fcaf7f86SDimitry Andric     return false;
203*fcaf7f86SDimitry Andric   MIBNodes.push_back(createMIBNode(Ctx, MIBCallStack, AllocationType::NotCold));
204*fcaf7f86SDimitry Andric   return true;
205*fcaf7f86SDimitry Andric }
206*fcaf7f86SDimitry Andric 
207*fcaf7f86SDimitry Andric // Build and attach the minimal necessary MIB metadata. If the alloc has a
208*fcaf7f86SDimitry Andric // single allocation type, add a function attribute instead. Returns true if
209*fcaf7f86SDimitry Andric // memprof metadata attached, false if not (attribute added).
210*fcaf7f86SDimitry Andric bool CallStackTrie::buildAndAttachMIBMetadata(CallBase *CI) {
211*fcaf7f86SDimitry Andric   auto &Ctx = CI->getContext();
212*fcaf7f86SDimitry Andric   if (hasSingleAllocType(Alloc->AllocTypes)) {
213*fcaf7f86SDimitry Andric     addAllocTypeAttribute(Ctx, CI, (AllocationType)Alloc->AllocTypes);
214*fcaf7f86SDimitry Andric     return false;
215*fcaf7f86SDimitry Andric   }
216*fcaf7f86SDimitry Andric   std::vector<uint64_t> MIBCallStack;
217*fcaf7f86SDimitry Andric   MIBCallStack.push_back(AllocStackId);
218*fcaf7f86SDimitry Andric   std::vector<Metadata *> MIBNodes;
219*fcaf7f86SDimitry Andric   assert(!Alloc->Callers.empty() && "addCallStack has not been called yet");
220*fcaf7f86SDimitry Andric   buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes,
221*fcaf7f86SDimitry Andric                 /*CalleeHasAmbiguousCallerContext=*/true);
222*fcaf7f86SDimitry Andric   assert(MIBCallStack.size() == 1 &&
223*fcaf7f86SDimitry Andric          "Should only be left with Alloc's location in stack");
224*fcaf7f86SDimitry Andric   CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes));
225*fcaf7f86SDimitry Andric   return true;
226*fcaf7f86SDimitry Andric }
227