1fcaf7f86SDimitry Andric //===-- MemoryProfileInfo.cpp - memory profile info ------------------------==// 2fcaf7f86SDimitry Andric // 3fcaf7f86SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4fcaf7f86SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5fcaf7f86SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6fcaf7f86SDimitry Andric // 7fcaf7f86SDimitry Andric //===----------------------------------------------------------------------===// 8fcaf7f86SDimitry Andric // 9fcaf7f86SDimitry Andric // This file contains utilities to analyze memory profile information. 10fcaf7f86SDimitry Andric // 11fcaf7f86SDimitry Andric //===----------------------------------------------------------------------===// 12fcaf7f86SDimitry Andric 13fcaf7f86SDimitry Andric #include "llvm/Analysis/MemoryProfileInfo.h" 14fcaf7f86SDimitry Andric #include "llvm/Support/CommandLine.h" 15fcaf7f86SDimitry Andric 16fcaf7f86SDimitry Andric using namespace llvm; 17fcaf7f86SDimitry Andric using namespace llvm::memprof; 18fcaf7f86SDimitry Andric 19fcaf7f86SDimitry Andric #define DEBUG_TYPE "memory-profile-info" 20fcaf7f86SDimitry Andric 2106c3fb27SDimitry Andric // Upper bound on lifetime access density (accesses per byte per lifetime sec) 2206c3fb27SDimitry Andric // for marking an allocation cold. 2306c3fb27SDimitry Andric cl::opt<float> MemProfLifetimeAccessDensityColdThreshold( 2406c3fb27SDimitry Andric "memprof-lifetime-access-density-cold-threshold", cl::init(0.05), 2506c3fb27SDimitry Andric cl::Hidden, 2606c3fb27SDimitry Andric cl::desc("The threshold the lifetime access density (accesses per byte per " 2706c3fb27SDimitry Andric "lifetime sec) must be under to consider an allocation cold")); 28fcaf7f86SDimitry Andric 29fcaf7f86SDimitry Andric // Lower bound on lifetime to mark an allocation cold (in addition to accesses 3006c3fb27SDimitry Andric // per byte per sec above). This is to avoid pessimizing short lived objects. 3106c3fb27SDimitry Andric cl::opt<unsigned> MemProfAveLifetimeColdThreshold( 3206c3fb27SDimitry Andric "memprof-ave-lifetime-cold-threshold", cl::init(200), cl::Hidden, 3306c3fb27SDimitry Andric cl::desc("The average lifetime (s) for an allocation to be considered " 34fcaf7f86SDimitry Andric "cold")); 35fcaf7f86SDimitry Andric 3606c3fb27SDimitry Andric // Lower bound on average lifetime accesses density (total life time access 3706c3fb27SDimitry Andric // density / alloc count) for marking an allocation hot. 3806c3fb27SDimitry Andric cl::opt<unsigned> MemProfMinAveLifetimeAccessDensityHotThreshold( 3906c3fb27SDimitry Andric "memprof-min-ave-lifetime-access-density-hot-threshold", cl::init(1000), 4006c3fb27SDimitry Andric cl::Hidden, 4106c3fb27SDimitry Andric cl::desc("The minimum TotalLifetimeAccessDensity / AllocCount for an " 4206c3fb27SDimitry Andric "allocation to be considered hot")); 4306c3fb27SDimitry Andric 44*0fca6ea1SDimitry Andric cl::opt<bool> MemProfReportHintedSizes( 45*0fca6ea1SDimitry Andric "memprof-report-hinted-sizes", cl::init(false), cl::Hidden, 46*0fca6ea1SDimitry Andric cl::desc("Report total allocation sizes of hinted allocations")); 47*0fca6ea1SDimitry Andric 4806c3fb27SDimitry Andric AllocationType llvm::memprof::getAllocType(uint64_t TotalLifetimeAccessDensity, 4906c3fb27SDimitry Andric uint64_t AllocCount, 5006c3fb27SDimitry Andric uint64_t TotalLifetime) { 5106c3fb27SDimitry Andric // The access densities are multiplied by 100 to hold 2 decimal places of 5206c3fb27SDimitry Andric // precision, so need to divide by 100. 5306c3fb27SDimitry Andric if (((float)TotalLifetimeAccessDensity) / AllocCount / 100 < 5406c3fb27SDimitry Andric MemProfLifetimeAccessDensityColdThreshold 5506c3fb27SDimitry Andric // Lifetime is expected to be in ms, so convert the threshold to ms. 5606c3fb27SDimitry Andric && ((float)TotalLifetime) / AllocCount >= 5706c3fb27SDimitry Andric MemProfAveLifetimeColdThreshold * 1000) 58fcaf7f86SDimitry Andric return AllocationType::Cold; 5906c3fb27SDimitry Andric 6006c3fb27SDimitry Andric // The access densities are multiplied by 100 to hold 2 decimal places of 6106c3fb27SDimitry Andric // precision, so need to divide by 100. 6206c3fb27SDimitry Andric if (((float)TotalLifetimeAccessDensity) / AllocCount / 100 > 6306c3fb27SDimitry Andric MemProfMinAveLifetimeAccessDensityHotThreshold) 6406c3fb27SDimitry Andric return AllocationType::Hot; 6506c3fb27SDimitry Andric 66fcaf7f86SDimitry Andric return AllocationType::NotCold; 67fcaf7f86SDimitry Andric } 68fcaf7f86SDimitry Andric 69fcaf7f86SDimitry Andric MDNode *llvm::memprof::buildCallstackMetadata(ArrayRef<uint64_t> CallStack, 70fcaf7f86SDimitry Andric LLVMContext &Ctx) { 71fcaf7f86SDimitry Andric std::vector<Metadata *> StackVals; 72fcaf7f86SDimitry Andric for (auto Id : CallStack) { 73fcaf7f86SDimitry Andric auto *StackValMD = 74fcaf7f86SDimitry Andric ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id)); 75fcaf7f86SDimitry Andric StackVals.push_back(StackValMD); 76fcaf7f86SDimitry Andric } 77fcaf7f86SDimitry Andric return MDNode::get(Ctx, StackVals); 78fcaf7f86SDimitry Andric } 79fcaf7f86SDimitry Andric 80fcaf7f86SDimitry Andric MDNode *llvm::memprof::getMIBStackNode(const MDNode *MIB) { 81*0fca6ea1SDimitry Andric assert(MIB->getNumOperands() >= 2); 82fcaf7f86SDimitry Andric // The stack metadata is the first operand of each memprof MIB metadata. 83fcaf7f86SDimitry Andric return cast<MDNode>(MIB->getOperand(0)); 84fcaf7f86SDimitry Andric } 85fcaf7f86SDimitry Andric 86fcaf7f86SDimitry Andric AllocationType llvm::memprof::getMIBAllocType(const MDNode *MIB) { 87*0fca6ea1SDimitry Andric assert(MIB->getNumOperands() >= 2); 88fcaf7f86SDimitry Andric // The allocation type is currently the second operand of each memprof 89fcaf7f86SDimitry Andric // MIB metadata. This will need to change as we add additional allocation 90fcaf7f86SDimitry Andric // types that can be applied based on the allocation profile data. 91fcaf7f86SDimitry Andric auto *MDS = dyn_cast<MDString>(MIB->getOperand(1)); 92fcaf7f86SDimitry Andric assert(MDS); 93*0fca6ea1SDimitry Andric if (MDS->getString() == "cold") { 94fcaf7f86SDimitry Andric return AllocationType::Cold; 95*0fca6ea1SDimitry Andric } else if (MDS->getString() == "hot") { 9606c3fb27SDimitry Andric return AllocationType::Hot; 9706c3fb27SDimitry Andric } 98fcaf7f86SDimitry Andric return AllocationType::NotCold; 99fcaf7f86SDimitry Andric } 100fcaf7f86SDimitry Andric 101*0fca6ea1SDimitry Andric uint64_t llvm::memprof::getMIBTotalSize(const MDNode *MIB) { 102*0fca6ea1SDimitry Andric if (MIB->getNumOperands() < 3) 103*0fca6ea1SDimitry Andric return 0; 104*0fca6ea1SDimitry Andric return mdconst::dyn_extract<ConstantInt>(MIB->getOperand(2))->getZExtValue(); 105*0fca6ea1SDimitry Andric } 106*0fca6ea1SDimitry Andric 10706c3fb27SDimitry Andric std::string llvm::memprof::getAllocTypeAttributeString(AllocationType Type) { 108fcaf7f86SDimitry Andric switch (Type) { 109fcaf7f86SDimitry Andric case AllocationType::NotCold: 110fcaf7f86SDimitry Andric return "notcold"; 111fcaf7f86SDimitry Andric break; 112fcaf7f86SDimitry Andric case AllocationType::Cold: 113fcaf7f86SDimitry Andric return "cold"; 114fcaf7f86SDimitry Andric break; 11506c3fb27SDimitry Andric case AllocationType::Hot: 11606c3fb27SDimitry Andric return "hot"; 11706c3fb27SDimitry Andric break; 118fcaf7f86SDimitry Andric default: 119fcaf7f86SDimitry Andric assert(false && "Unexpected alloc type"); 120fcaf7f86SDimitry Andric } 121fcaf7f86SDimitry Andric llvm_unreachable("invalid alloc type"); 122fcaf7f86SDimitry Andric } 123fcaf7f86SDimitry Andric 124fcaf7f86SDimitry Andric static void addAllocTypeAttribute(LLVMContext &Ctx, CallBase *CI, 125fcaf7f86SDimitry Andric AllocationType AllocType) { 126fcaf7f86SDimitry Andric auto AllocTypeString = getAllocTypeAttributeString(AllocType); 127fcaf7f86SDimitry Andric auto A = llvm::Attribute::get(Ctx, "memprof", AllocTypeString); 128fcaf7f86SDimitry Andric CI->addFnAttr(A); 129fcaf7f86SDimitry Andric } 130fcaf7f86SDimitry Andric 13106c3fb27SDimitry Andric bool llvm::memprof::hasSingleAllocType(uint8_t AllocTypes) { 132bdd1243dSDimitry Andric const unsigned NumAllocTypes = llvm::popcount(AllocTypes); 133fcaf7f86SDimitry Andric assert(NumAllocTypes != 0); 134fcaf7f86SDimitry Andric return NumAllocTypes == 1; 135fcaf7f86SDimitry Andric } 136fcaf7f86SDimitry Andric 137fcaf7f86SDimitry Andric void CallStackTrie::addCallStack(AllocationType AllocType, 138*0fca6ea1SDimitry Andric ArrayRef<uint64_t> StackIds, 139*0fca6ea1SDimitry Andric uint64_t TotalSize) { 140fcaf7f86SDimitry Andric bool First = true; 141fcaf7f86SDimitry Andric CallStackTrieNode *Curr = nullptr; 142fcaf7f86SDimitry Andric for (auto StackId : StackIds) { 143fcaf7f86SDimitry Andric // If this is the first stack frame, add or update alloc node. 144fcaf7f86SDimitry Andric if (First) { 145fcaf7f86SDimitry Andric First = false; 146fcaf7f86SDimitry Andric if (Alloc) { 147fcaf7f86SDimitry Andric assert(AllocStackId == StackId); 148fcaf7f86SDimitry Andric Alloc->AllocTypes |= static_cast<uint8_t>(AllocType); 149*0fca6ea1SDimitry Andric Alloc->TotalSize += TotalSize; 150fcaf7f86SDimitry Andric } else { 151fcaf7f86SDimitry Andric AllocStackId = StackId; 152*0fca6ea1SDimitry Andric Alloc = new CallStackTrieNode(AllocType, TotalSize); 153fcaf7f86SDimitry Andric } 154fcaf7f86SDimitry Andric Curr = Alloc; 155fcaf7f86SDimitry Andric continue; 156fcaf7f86SDimitry Andric } 157fcaf7f86SDimitry Andric // Update existing caller node if it exists. 158fcaf7f86SDimitry Andric auto Next = Curr->Callers.find(StackId); 159fcaf7f86SDimitry Andric if (Next != Curr->Callers.end()) { 160fcaf7f86SDimitry Andric Curr = Next->second; 161fcaf7f86SDimitry Andric Curr->AllocTypes |= static_cast<uint8_t>(AllocType); 162*0fca6ea1SDimitry Andric Curr->TotalSize += TotalSize; 163fcaf7f86SDimitry Andric continue; 164fcaf7f86SDimitry Andric } 165fcaf7f86SDimitry Andric // Otherwise add a new caller node. 166*0fca6ea1SDimitry Andric auto *New = new CallStackTrieNode(AllocType, TotalSize); 167fcaf7f86SDimitry Andric Curr->Callers[StackId] = New; 168fcaf7f86SDimitry Andric Curr = New; 169fcaf7f86SDimitry Andric } 170fcaf7f86SDimitry Andric assert(Curr); 171fcaf7f86SDimitry Andric } 172fcaf7f86SDimitry Andric 173fcaf7f86SDimitry Andric void CallStackTrie::addCallStack(MDNode *MIB) { 174fcaf7f86SDimitry Andric MDNode *StackMD = getMIBStackNode(MIB); 175fcaf7f86SDimitry Andric assert(StackMD); 176fcaf7f86SDimitry Andric std::vector<uint64_t> CallStack; 177fcaf7f86SDimitry Andric CallStack.reserve(StackMD->getNumOperands()); 178bdd1243dSDimitry Andric for (const auto &MIBStackIter : StackMD->operands()) { 179fcaf7f86SDimitry Andric auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter); 180fcaf7f86SDimitry Andric assert(StackId); 181fcaf7f86SDimitry Andric CallStack.push_back(StackId->getZExtValue()); 182fcaf7f86SDimitry Andric } 183*0fca6ea1SDimitry Andric addCallStack(getMIBAllocType(MIB), CallStack, getMIBTotalSize(MIB)); 184fcaf7f86SDimitry Andric } 185fcaf7f86SDimitry Andric 186fcaf7f86SDimitry Andric static MDNode *createMIBNode(LLVMContext &Ctx, 187fcaf7f86SDimitry Andric std::vector<uint64_t> &MIBCallStack, 188*0fca6ea1SDimitry Andric AllocationType AllocType, uint64_t TotalSize) { 189fcaf7f86SDimitry Andric std::vector<Metadata *> MIBPayload( 190fcaf7f86SDimitry Andric {buildCallstackMetadata(MIBCallStack, Ctx)}); 191fcaf7f86SDimitry Andric MIBPayload.push_back( 192fcaf7f86SDimitry Andric MDString::get(Ctx, getAllocTypeAttributeString(AllocType))); 193*0fca6ea1SDimitry Andric if (TotalSize) 194*0fca6ea1SDimitry Andric MIBPayload.push_back(ValueAsMetadata::get( 195*0fca6ea1SDimitry Andric ConstantInt::get(Type::getInt64Ty(Ctx), TotalSize))); 196fcaf7f86SDimitry Andric return MDNode::get(Ctx, MIBPayload); 197fcaf7f86SDimitry Andric } 198fcaf7f86SDimitry Andric 199fcaf7f86SDimitry Andric // Recursive helper to trim contexts and create metadata nodes. 200fcaf7f86SDimitry Andric // Caller should have pushed Node's loc to MIBCallStack. Doing this in the 201fcaf7f86SDimitry Andric // caller makes it simpler to handle the many early returns in this method. 202fcaf7f86SDimitry Andric bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx, 203fcaf7f86SDimitry Andric std::vector<uint64_t> &MIBCallStack, 204fcaf7f86SDimitry Andric std::vector<Metadata *> &MIBNodes, 205fcaf7f86SDimitry Andric bool CalleeHasAmbiguousCallerContext) { 206fcaf7f86SDimitry Andric // Trim context below the first node in a prefix with a single alloc type. 207fcaf7f86SDimitry Andric // Add an MIB record for the current call stack prefix. 208fcaf7f86SDimitry Andric if (hasSingleAllocType(Node->AllocTypes)) { 209*0fca6ea1SDimitry Andric MIBNodes.push_back(createMIBNode( 210*0fca6ea1SDimitry Andric Ctx, MIBCallStack, (AllocationType)Node->AllocTypes, Node->TotalSize)); 211fcaf7f86SDimitry Andric return true; 212fcaf7f86SDimitry Andric } 213fcaf7f86SDimitry Andric 214fcaf7f86SDimitry Andric // We don't have a single allocation for all the contexts sharing this prefix, 215fcaf7f86SDimitry Andric // so recursively descend into callers in trie. 216fcaf7f86SDimitry Andric if (!Node->Callers.empty()) { 217fcaf7f86SDimitry Andric bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1; 218fcaf7f86SDimitry Andric bool AddedMIBNodesForAllCallerContexts = true; 219fcaf7f86SDimitry Andric for (auto &Caller : Node->Callers) { 220fcaf7f86SDimitry Andric MIBCallStack.push_back(Caller.first); 221fcaf7f86SDimitry Andric AddedMIBNodesForAllCallerContexts &= 222fcaf7f86SDimitry Andric buildMIBNodes(Caller.second, Ctx, MIBCallStack, MIBNodes, 223fcaf7f86SDimitry Andric NodeHasAmbiguousCallerContext); 224fcaf7f86SDimitry Andric // Remove Caller. 225fcaf7f86SDimitry Andric MIBCallStack.pop_back(); 226fcaf7f86SDimitry Andric } 227fcaf7f86SDimitry Andric if (AddedMIBNodesForAllCallerContexts) 228fcaf7f86SDimitry Andric return true; 229fcaf7f86SDimitry Andric // We expect that the callers should be forced to add MIBs to disambiguate 230fcaf7f86SDimitry Andric // the context in this case (see below). 231fcaf7f86SDimitry Andric assert(!NodeHasAmbiguousCallerContext); 232fcaf7f86SDimitry Andric } 233fcaf7f86SDimitry Andric 234fcaf7f86SDimitry Andric // If we reached here, then this node does not have a single allocation type, 235fcaf7f86SDimitry Andric // and we didn't add metadata for a longer call stack prefix including any of 236fcaf7f86SDimitry Andric // Node's callers. That means we never hit a single allocation type along all 237fcaf7f86SDimitry Andric // call stacks with this prefix. This can happen due to recursion collapsing 238fcaf7f86SDimitry Andric // or the stack being deeper than tracked by the profiler runtime, leading to 239fcaf7f86SDimitry Andric // contexts with different allocation types being merged. In that case, we 240fcaf7f86SDimitry Andric // trim the context just below the deepest context split, which is this 241fcaf7f86SDimitry Andric // node if the callee has an ambiguous caller context (multiple callers), 242fcaf7f86SDimitry Andric // since the recursive calls above returned false. Conservatively give it 243fcaf7f86SDimitry Andric // non-cold allocation type. 244fcaf7f86SDimitry Andric if (!CalleeHasAmbiguousCallerContext) 245fcaf7f86SDimitry Andric return false; 246*0fca6ea1SDimitry Andric MIBNodes.push_back(createMIBNode(Ctx, MIBCallStack, AllocationType::NotCold, 247*0fca6ea1SDimitry Andric Node->TotalSize)); 248fcaf7f86SDimitry Andric return true; 249fcaf7f86SDimitry Andric } 250fcaf7f86SDimitry Andric 251fcaf7f86SDimitry Andric // Build and attach the minimal necessary MIB metadata. If the alloc has a 252fcaf7f86SDimitry Andric // single allocation type, add a function attribute instead. Returns true if 253fcaf7f86SDimitry Andric // memprof metadata attached, false if not (attribute added). 254fcaf7f86SDimitry Andric bool CallStackTrie::buildAndAttachMIBMetadata(CallBase *CI) { 255fcaf7f86SDimitry Andric auto &Ctx = CI->getContext(); 256fcaf7f86SDimitry Andric if (hasSingleAllocType(Alloc->AllocTypes)) { 257fcaf7f86SDimitry Andric addAllocTypeAttribute(Ctx, CI, (AllocationType)Alloc->AllocTypes); 258*0fca6ea1SDimitry Andric if (MemProfReportHintedSizes) { 259*0fca6ea1SDimitry Andric assert(Alloc->TotalSize); 260*0fca6ea1SDimitry Andric errs() << "Total size for allocation with location hash " << AllocStackId 261*0fca6ea1SDimitry Andric << " and single alloc type " 262*0fca6ea1SDimitry Andric << getAllocTypeAttributeString((AllocationType)Alloc->AllocTypes) 263*0fca6ea1SDimitry Andric << ": " << Alloc->TotalSize << "\n"; 264*0fca6ea1SDimitry Andric } 265fcaf7f86SDimitry Andric return false; 266fcaf7f86SDimitry Andric } 267fcaf7f86SDimitry Andric std::vector<uint64_t> MIBCallStack; 268fcaf7f86SDimitry Andric MIBCallStack.push_back(AllocStackId); 269fcaf7f86SDimitry Andric std::vector<Metadata *> MIBNodes; 270fcaf7f86SDimitry Andric assert(!Alloc->Callers.empty() && "addCallStack has not been called yet"); 271*0fca6ea1SDimitry Andric // The last parameter is meant to say whether the callee of the given node 272*0fca6ea1SDimitry Andric // has more than one caller. Here the node being passed in is the alloc 273*0fca6ea1SDimitry Andric // and it has no callees. So it's false. 274*0fca6ea1SDimitry Andric if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes, false)) { 275fcaf7f86SDimitry Andric assert(MIBCallStack.size() == 1 && 276fcaf7f86SDimitry Andric "Should only be left with Alloc's location in stack"); 277fcaf7f86SDimitry Andric CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes)); 278fcaf7f86SDimitry Andric return true; 279fcaf7f86SDimitry Andric } 280*0fca6ea1SDimitry Andric // If there exists corner case that CallStackTrie has one chain to leaf 281*0fca6ea1SDimitry Andric // and all node in the chain have multi alloc type, conservatively give 282*0fca6ea1SDimitry Andric // it non-cold allocation type. 283*0fca6ea1SDimitry Andric // FIXME: Avoid this case before memory profile created. 284*0fca6ea1SDimitry Andric addAllocTypeAttribute(Ctx, CI, AllocationType::NotCold); 285*0fca6ea1SDimitry Andric return false; 286*0fca6ea1SDimitry Andric } 287bdd1243dSDimitry Andric 288bdd1243dSDimitry Andric template <> 289bdd1243dSDimitry Andric CallStack<MDNode, MDNode::op_iterator>::CallStackIterator::CallStackIterator( 290bdd1243dSDimitry Andric const MDNode *N, bool End) 291bdd1243dSDimitry Andric : N(N) { 292bdd1243dSDimitry Andric if (!N) 293bdd1243dSDimitry Andric return; 294bdd1243dSDimitry Andric Iter = End ? N->op_end() : N->op_begin(); 295bdd1243dSDimitry Andric } 296bdd1243dSDimitry Andric 297bdd1243dSDimitry Andric template <> 298bdd1243dSDimitry Andric uint64_t 299bdd1243dSDimitry Andric CallStack<MDNode, MDNode::op_iterator>::CallStackIterator::operator*() { 300bdd1243dSDimitry Andric assert(Iter != N->op_end()); 301bdd1243dSDimitry Andric ConstantInt *StackIdCInt = mdconst::dyn_extract<ConstantInt>(*Iter); 302bdd1243dSDimitry Andric assert(StackIdCInt); 303bdd1243dSDimitry Andric return StackIdCInt->getZExtValue(); 304bdd1243dSDimitry Andric } 30506c3fb27SDimitry Andric 30606c3fb27SDimitry Andric template <> uint64_t CallStack<MDNode, MDNode::op_iterator>::back() const { 30706c3fb27SDimitry Andric assert(N); 30806c3fb27SDimitry Andric return mdconst::dyn_extract<ConstantInt>(N->operands().back()) 30906c3fb27SDimitry Andric ->getZExtValue(); 31006c3fb27SDimitry Andric } 311