LLVM 24.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 for
10// profile-guided memory optimization (MemPGO).
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/IR/Constants.h"
19#include "llvm/Support/Format.h"
20
21using namespace llvm;
22using namespace llvm::memprof;
23
24#define DEBUG_TYPE "memory-profile-info"
25
26namespace llvm {
27
29 "memprof-report-hinted-sizes", cl::init(false), cl::Hidden,
30 cl::desc("Report total allocation sizes of hinted allocations"));
31
32// This is useful if we have enabled reporting of hinted sizes, and want to get
33// information from the indexing step for all contexts (especially for testing),
34// or have specified a value less than 100% for -memprof-cloning-cold-threshold.
36 "memprof-keep-all-not-cold-contexts", cl::init(false), cl::Hidden,
37 cl::desc("Keep all non-cold contexts (increases cloning overheads)"));
38
40 "memprof-cloning-cold-threshold", cl::init(100), cl::Hidden,
41 cl::desc("Min percent of cold bytes to hint alloc cold during cloning"));
42
43// Discard non-cold contexts if they overlap with much larger cold contexts,
44// specifically, if all contexts reaching a given callsite are at least this
45// percent cold byte allocations. This reduces the amount of cloning required
46// to expose the cold contexts when they greatly dominate non-cold contexts.
48 "memprof-callsite-cold-threshold", cl::init(100), cl::Hidden,
49 cl::desc("Min percent of cold bytes at a callsite to discard non-cold "
50 "contexts"));
51
52// Enable saving context size information for largest cold contexts, which can
53// be used to flag contexts for more aggressive cloning and reporting.
55 "memprof-min-percent-max-cold-size", cl::init(100), cl::Hidden,
56 cl::desc("Min percent of max cold bytes for critical cold context"));
57
58// Use this to keep the context size information in the memprof metadata for use
59// in remarks.
61 "memprof-keep-context-size-info", cl::init(false), cl::Hidden,
62 cl::desc("Keep context size information in memprof metadata"));
63
65 "memprof-ambiguous-attributes", cl::init(true), cl::Hidden,
66 cl::desc("Apply ambiguous memprof attribute to ambiguous allocations"));
67
68} // end namespace llvm
69
74
78
83
85 LLVMContext &Ctx) {
87 StackVals.reserve(CallStack.size());
88 for (auto Id : CallStack) {
89 auto *StackValMD =
90 ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id));
91 StackVals.push_back(StackValMD);
92 }
93 return MDNode::get(Ctx, StackVals);
94}
95
97 assert(MIB->getNumOperands() >= 2);
98 // The stack metadata is the first operand of each memprof MIB metadata.
99 return cast<MDNode>(MIB->getOperand(0));
100}
101
103 assert(MIB->getNumOperands() >= 2);
104 // The allocation type is currently the second operand of each memprof
105 // MIB metadata. This will need to change as we add additional allocation
106 // types that can be applied based on the allocation profile data.
107 auto *MDS = dyn_cast<MDString>(MIB->getOperand(1));
108 assert(MDS);
109 if (MDS->getString() == "cold") {
111 } else if (MDS->getString() == "hot") {
112 return AllocationType::Hot;
113 }
115}
116
119 return "ambiguous";
120 switch (Type) {
122 return "notcold";
123 break;
125 return "cold";
126 break;
128 return "hot";
129 break;
130 default:
131 assert(false && "Unexpected alloc type");
132 }
133 llvm_unreachable("invalid alloc type");
134}
135
137 const unsigned NumAllocTypes = llvm::popcount(AllocTypes);
138 assert(NumAllocTypes != 0);
139 return NumAllocTypes == 1;
140}
141
143 const uint8_t BothTypes =
145 return (AllocTypes & BothTypes) == BothTypes;
146}
147
149 if (!CB->hasFnAttr("memprof"))
150 return;
151 assert(CB->getFnAttr("memprof").getValueAsString() == "ambiguous");
152 CB->removeFnAttr("memprof");
153}
154
157 return;
158 // We may have an existing ambiguous attribute if we are reanalyzing
159 // after inlining.
160 if (CB->hasFnAttr("memprof")) {
161 assert(CB->getFnAttr("memprof").getValueAsString() == "ambiguous");
162 } else {
163 auto A = llvm::Attribute::get(CB->getContext(), "memprof", "ambiguous");
164 CB->addFnAttr(A);
165 }
166}
167
169 AllocationType AllocType, ArrayRef<uint64_t> StackIds,
170 std::vector<ContextTotalSize> ContextSizeInfo) {
171 bool First = true;
172 CallStackTrieNode *Curr = nullptr;
173 for (auto StackId : StackIds) {
174 // If this is the first stack frame, add or update alloc node.
175 if (First) {
176 First = false;
177 if (Alloc) {
178 assert(AllocStackId == StackId);
179 Alloc->addAllocType(AllocType);
180 } else {
181 AllocStackId = StackId;
182 Alloc = new CallStackTrieNode(AllocType);
183 }
184 Curr = Alloc;
185 continue;
186 }
187 // Update existing caller node if it exists.
188 auto [Next, Inserted] = Curr->Callers.try_emplace(StackId);
189 if (!Inserted) {
190 Curr = Next->second;
191 Curr->addAllocType(AllocType);
192 continue;
193 }
194 // Otherwise add a new caller node.
195 auto *New = new CallStackTrieNode(AllocType);
196 Next->second = New;
197 Curr = New;
198 }
199 assert(Curr);
200 // Append all of the ContextSizeInfo, along with their original AllocType.
201 llvm::append_range(Curr->ContextInfo,
202 llvm::map_range(ContextSizeInfo,
203 [AllocType](const ContextTotalSize &CTS) {
204 return ContextSizeTypePair(CTS,
205 AllocType);
206 }));
207}
208
210 // Note that we are building this from existing MD_memprof metadata.
211 BuiltFromExistingMetadata = true;
212 MDNode *StackMD = getMIBStackNode(MIB);
213 assert(StackMD);
214 std::vector<uint64_t> CallStack;
215 CallStack.reserve(StackMD->getNumOperands());
216 for (const auto &MIBStackIter : StackMD->operands()) {
217 auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter);
218 assert(StackId);
219 CallStack.push_back(StackId->getZExtValue());
220 }
221 std::vector<ContextTotalSize> ContextSizeInfo;
222 // Collect the context size information if it exists.
223 if (MIB->getNumOperands() > 2) {
224 for (unsigned I = 2; I < MIB->getNumOperands(); I++) {
225 MDNode *ContextSizePair = dyn_cast<MDNode>(MIB->getOperand(I));
226 assert(ContextSizePair->getNumOperands() == 2);
227 uint64_t FullStackId =
229 ->getZExtValue();
230 uint64_t TotalSize =
232 ->getZExtValue();
233 ContextSizeInfo.push_back({FullStackId, TotalSize});
234 }
235 }
236 addCallStack(getMIBAllocType(MIB), CallStack, std::move(ContextSizeInfo));
237}
238
242 const uint64_t MaxColdSize,
243 bool BuiltFromExistingMetadata,
244 uint64_t &TotalBytes, uint64_t &ColdBytes) {
245 SmallVector<Metadata *> MIBPayload(
246 {buildCallstackMetadata(MIBCallStack, Ctx)});
247 MIBPayload.push_back(
249
250 if (ContextInfo.empty()) {
251 // The profile matcher should have provided context size info if there was a
252 // MinCallsiteColdBytePercent < 100. Here we check >=100 to gracefully
253 // handle a user-provided percent larger than 100. However, we may not have
254 // this information if we built the Trie from existing MD_memprof metadata.
255 assert(BuiltFromExistingMetadata || MinCallsiteColdBytePercent >= 100);
256 return MDNode::get(Ctx, MIBPayload);
257 }
258
259 for (const auto &[CSI, AT] : ContextInfo) {
260 const auto &[FullStackId, TotalSize] = CSI;
261 TotalBytes += TotalSize;
262 bool LargeColdContext = false;
264 ColdBytes += TotalSize;
265 // If we have the max cold context size from summary information and have
266 // requested identification of contexts above a percentage of the max, see
267 // if this context qualifies. We should assume this is large if we rebuilt
268 // the trie from existing metadata (i.e. to update after inlining), in
269 // which case we don't have a MaxSize from the profile - we assume any
270 // context size info in existence on the metadata should be propagated.
271 if (BuiltFromExistingMetadata ||
272 (MaxColdSize > 0 && MinPercentMaxColdSize < 100 &&
273 TotalSize * 100 >= MaxColdSize * MinPercentMaxColdSize))
274 LargeColdContext = true;
275 }
276 // Only add the context size info as metadata if we need it in the thin
277 // link (currently if reporting of hinted sizes is enabled, we have
278 // specified a threshold for marking allocations cold after cloning, or we
279 // have identified this as a large cold context of interest above).
280 if (metadataIncludesAllContextSizeInfo() || LargeColdContext) {
281 auto *FullStackIdMD = ValueAsMetadata::get(
282 ConstantInt::get(Type::getInt64Ty(Ctx), FullStackId));
283 auto *TotalSizeMD = ValueAsMetadata::get(
284 ConstantInt::get(Type::getInt64Ty(Ctx), TotalSize));
285 auto *ContextSizeMD = MDNode::get(Ctx, {FullStackIdMD, TotalSizeMD});
286 MIBPayload.push_back(ContextSizeMD);
287 }
288 }
289 assert(TotalBytes > 0);
290 return MDNode::get(Ctx, MIBPayload);
291}
292
293void CallStackTrie::collectContextInfo(
294 CallStackTrieNode *Node, std::vector<ContextSizeTypePair> &ContextInfo) {
295 llvm::append_range(ContextInfo, Node->ContextInfo);
296 for (auto &Caller : Node->Callers)
297 collectContextInfo(Caller.second, ContextInfo);
298}
299
300void CallStackTrie::convertHotToNotCold(CallStackTrieNode *Node) {
301 if (Node->hasAllocType(AllocationType::Hot)) {
302 Node->removeAllocType(AllocationType::Hot);
303 Node->addAllocType(AllocationType::NotCold);
304 }
305 for (auto &Caller : Node->Callers)
306 convertHotToNotCold(Caller.second);
307}
308
309// Helper to emit messages for non-cold contexts that are ignored for various
310// reasons when reporting of hinted bytes is enabled.
312 uint64_t FullStackId,
313 StringRef Extra,
314 uint64_t TotalSize) {
315 errs() << "MemProf hinting: Total size for " << Tag
316 << " non-cold full allocation context hash " << FullStackId << Extra
317 << ": " << TotalSize << "\n";
318}
319
320// Copy over some or all of NewMIBNodes to the SavedMIBNodes vector, depending
321// on options that enable filtering out some NotCold contexts.
322static void saveFilteredNewMIBNodes(std::vector<Metadata *> &NewMIBNodes,
323 std::vector<Metadata *> &SavedMIBNodes,
324 unsigned CallerContextLength,
325 uint64_t TotalBytes, uint64_t ColdBytes,
326 bool BuiltFromExistingMetadata) {
327 const bool MostlyCold =
328 // If we have built the Trie from existing MD_memprof metadata, we may or
329 // may not have context size information (in which case ColdBytes and
330 // TotalBytes are 0, which is not also guarded against below). Even if we
331 // do have some context size information from the the metadata, we have
332 // already gone through a round of discarding of small non-cold contexts
333 // during matching, and it would be overly aggressive to do it again, and
334 // we also want to maintain the same behavior with and without reporting
335 // of hinted bytes enabled.
336 !BuiltFromExistingMetadata && MinCallsiteColdBytePercent < 100 &&
337 ColdBytes > 0 &&
338 ColdBytes * 100 >= MinCallsiteColdBytePercent * TotalBytes;
339
340 // In the simplest case, with pruning disabled, keep all the new MIB nodes.
341 if (MemProfKeepAllNotColdContexts && !MostlyCold) {
342 append_range(SavedMIBNodes, NewMIBNodes);
343 return;
344 }
345
346 auto EmitMessageForRemovedContexts = [](const MDNode *MIBMD, StringRef Tag,
347 StringRef Extra) {
348 assert(MIBMD->getNumOperands() > 2);
349 for (unsigned I = 2; I < MIBMD->getNumOperands(); I++) {
350 MDNode *ContextSizePair = dyn_cast<MDNode>(MIBMD->getOperand(I));
351 assert(ContextSizePair->getNumOperands() == 2);
352 uint64_t FullStackId =
354 ->getZExtValue();
355 uint64_t TS =
357 ->getZExtValue();
358 emitIgnoredNonColdContextMessage(Tag, FullStackId, Extra, TS);
359 }
360 };
361
362 // If the cold bytes at the current callsite exceed the given threshold, we
363 // discard all non-cold contexts so do not need any of the later pruning
364 // handling. We can simply copy over all the cold contexts and return early.
365 if (MostlyCold) {
366 auto NewColdMIBNodes =
367 make_filter_range(NewMIBNodes, [&](const Metadata *M) {
368 auto MIBMD = cast<MDNode>(M);
369 // Only append cold contexts.
371 return true;
373 const float PercentCold = ColdBytes * 100.0 / TotalBytes;
374 std::string PercentStr;
375 llvm::raw_string_ostream OS(PercentStr);
376 OS << format(" for %5.2f%% cold bytes", PercentCold);
377 EmitMessageForRemovedContexts(MIBMD, "discarded", OS.str());
378 }
379 return false;
380 });
381 for (auto *M : NewColdMIBNodes)
382 SavedMIBNodes.push_back(M);
383 return;
384 }
385
386 // Prune unneeded NotCold contexts, taking advantage of the fact
387 // that we later will only clone Cold contexts, as NotCold is the allocation
388 // default. We only need to keep as metadata the NotCold contexts that
389 // overlap the longest with Cold allocations, so that we know how deeply we
390 // need to clone. For example, assume we add the following contexts to the
391 // trie:
392 // 1 3 (notcold)
393 // 1 2 4 (cold)
394 // 1 2 5 (notcold)
395 // 1 2 6 (notcold)
396 // the trie looks like:
397 // 1
398 // / \
399 // 2 3
400 // /|\
401 // 4 5 6
402 //
403 // It is sufficient to prune all but one not-cold contexts (either 1,2,5 or
404 // 1,2,6, we arbitrarily keep the first one we encounter which will be
405 // 1,2,5).
406 //
407 // To do this pruning, we first check if there were any not-cold
408 // contexts kept for a deeper caller, which will have a context length larger
409 // than the CallerContextLength being handled here (i.e. kept by a deeper
410 // recursion step). If so, none of the not-cold MIB nodes added for the
411 // immediate callers need to be kept. If not, we keep the first (created
412 // for the immediate caller) not-cold MIB node.
413 bool LongerNotColdContextKept = false;
414 for (auto *MIB : NewMIBNodes) {
415 auto MIBMD = cast<MDNode>(MIB);
417 continue;
418 MDNode *StackMD = getMIBStackNode(MIBMD);
419 assert(StackMD);
420 if (StackMD->getNumOperands() > CallerContextLength) {
421 LongerNotColdContextKept = true;
422 break;
423 }
424 }
425 // Don't need to emit any for the immediate caller if we already have
426 // longer overlapping contexts;
427 bool KeepFirstNewNotCold = !LongerNotColdContextKept;
428 auto NewColdMIBNodes = make_filter_range(NewMIBNodes, [&](const Metadata *M) {
429 auto MIBMD = cast<MDNode>(M);
430 // Only keep cold contexts and first (longest non-cold context).
432 MDNode *StackMD = getMIBStackNode(MIBMD);
433 assert(StackMD);
434 // Keep any already kept for longer contexts.
435 if (StackMD->getNumOperands() > CallerContextLength)
436 return true;
437 // Otherwise keep the first one added by the immediate caller if there
438 // were no longer contexts.
439 if (KeepFirstNewNotCold) {
440 KeepFirstNewNotCold = false;
441 return true;
442 }
444 EmitMessageForRemovedContexts(MIBMD, "pruned", "");
445 return false;
446 }
447 return true;
448 });
449 for (auto *M : NewColdMIBNodes)
450 SavedMIBNodes.push_back(M);
451}
452
453// Recursive helper to trim contexts and create metadata nodes.
454// Caller should have pushed Node's loc to MIBCallStack. Doing this in the
455// caller makes it simpler to handle the many early returns in this method.
456// Updates the total and cold profiled bytes in the subtrie rooted at this node.
457bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
458 std::vector<uint64_t> &MIBCallStack,
459 std::vector<Metadata *> &MIBNodes,
460 bool CalleeHasAmbiguousCallerContext,
461 uint64_t &TotalBytes, uint64_t &ColdBytes) {
462 // Trim context below the first node in a prefix with a single alloc type.
463 // Add an MIB record for the current call stack prefix.
464 if (hasSingleAllocType(Node->AllocTypes)) {
465 std::vector<ContextSizeTypePair> ContextInfo;
466 collectContextInfo(Node, ContextInfo);
467 MIBNodes.push_back(createMIBNode(
468 Ctx, MIBCallStack, (AllocationType)Node->AllocTypes, ContextInfo,
469 MaxColdSize, BuiltFromExistingMetadata, TotalBytes, ColdBytes));
470 return true;
471 }
472
473 // We don't have a single allocation for all the contexts sharing this prefix,
474 // so recursively descend into callers in trie.
475 if (!Node->Callers.empty()) {
476 bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1;
477 bool AddedMIBNodesForAllCallerContexts = true;
478 // Accumulate all new MIB nodes by the recursive calls below into a vector
479 // that will later be filtered before adding to the caller's MIBNodes
480 // vector.
481 std::vector<Metadata *> NewMIBNodes;
482 // Determine the total and cold byte counts for all callers, then add to the
483 // caller's counts further below.
484 uint64_t CallerTotalBytes = 0;
485 uint64_t CallerColdBytes = 0;
486 for (auto &Caller : Node->Callers) {
487 MIBCallStack.push_back(Caller.first);
488 AddedMIBNodesForAllCallerContexts &= buildMIBNodes(
489 Caller.second, Ctx, MIBCallStack, NewMIBNodes,
490 NodeHasAmbiguousCallerContext, CallerTotalBytes, CallerColdBytes);
491 // Remove Caller.
492 MIBCallStack.pop_back();
493 }
494 // Pass in the stack length of the MIB nodes added for the immediate caller,
495 // which is the current stack length plus 1.
496 saveFilteredNewMIBNodes(NewMIBNodes, MIBNodes, MIBCallStack.size() + 1,
497 CallerTotalBytes, CallerColdBytes,
498 BuiltFromExistingMetadata);
499 TotalBytes += CallerTotalBytes;
500 ColdBytes += CallerColdBytes;
501
502 if (AddedMIBNodesForAllCallerContexts)
503 return true;
504 // We expect that the callers should be forced to add MIBs to disambiguate
505 // the context in this case (see below).
506 assert(!NodeHasAmbiguousCallerContext);
507 }
508
509 // If we reached here, then this node does not have a single allocation type,
510 // and we didn't add metadata for a longer call stack prefix including any of
511 // Node's callers. That means we never hit a single allocation type along all
512 // call stacks with this prefix. This can happen due to recursion collapsing
513 // or the stack being deeper than tracked by the profiler runtime, leading to
514 // contexts with different allocation types being merged. In that case, we
515 // trim the context just below the deepest context split, which is this
516 // node if the callee has an ambiguous caller context (multiple callers),
517 // since the recursive calls above returned false. Conservatively give it
518 // non-cold allocation type.
519 if (!CalleeHasAmbiguousCallerContext)
520 return false;
521 std::vector<ContextSizeTypePair> ContextInfo;
522 collectContextInfo(Node, ContextInfo);
523 MIBNodes.push_back(createMIBNode(
524 Ctx, MIBCallStack, AllocationType::NotCold, ContextInfo, MaxColdSize,
525 BuiltFromExistingMetadata, TotalBytes, ColdBytes));
526 return true;
527}
528
530 StringRef Descriptor) {
531 auto AllocTypeString = getAllocTypeAttributeString(AT);
532 auto A = llvm::Attribute::get(CI->getContext(), "memprof", AllocTypeString);
533 // After inlining we may be able to convert an existing ambiguous allocation
534 // to an unambiguous one.
536 CI->addFnAttr(A);
537
538 std::vector<ContextSizeTypePair> ContextInfo;
539 collectContextInfo(Alloc, ContextInfo);
540
541 // If we don't have context size info, just emit a single remark for this
542 // allocation.
543 if (ContextInfo.empty()) {
544 if (ORE)
545 ORE->emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", CI)
546 << ore::NV("AllocationCall", CI) << " in function "
547 << ore::NV("Caller", CI->getFunction())
548 << " marked with memprof allocation attribute "
549 << ore::NV("Attribute", AllocTypeString));
550 return;
551 }
552
553 // Emit remarks or stderr reporting if requested.
554 for (const auto &[CSI, OrigAT] : ContextInfo) {
555 const auto &[FullStackId, TotalSize] = CSI;
556 // If the original alloc type is not the one being applied as the hint,
557 // then don't report that it was hinted. Optionally report that we ignored
558 // this context.
559 if (AT != OrigAT) {
561 emitIgnoredNonColdContextMessage("ignored", FullStackId, "", TotalSize);
562 continue;
563 }
565 errs() << "MemProf hinting: Total size for full allocation context hash "
566 << FullStackId << " and " << Descriptor << " alloc type "
567 << getAllocTypeAttributeString(AT) << ": " << TotalSize << "\n";
568 if (ORE)
569 ORE->emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", CI)
570 << ore::NV("AllocationCall", CI) << " in function "
571 << ore::NV("Caller", CI->getFunction())
572 << " marked with memprof allocation attribute "
573 << ore::NV("Attribute", AllocTypeString)
574 << " for full allocation context hash "
575 << ore::NV("FullStackId", FullStackId) << " with total size "
576 << ore::NV("TotalSize", TotalSize));
577 }
578}
579
580// Build and attach the minimal necessary MIB metadata. If the alloc has a
581// single allocation type, add a function attribute instead. Returns true if
582// memprof metadata attached, false if not (attribute added).
584 if (hasSingleAllocType(Alloc->AllocTypes)) {
585 addSingleAllocTypeAttribute(CI, (AllocationType)Alloc->AllocTypes,
586 "single");
587 return false;
588 }
589 // If there were any hot allocation contexts, the Alloc trie node would have
590 // the Hot type set. If so, because we don't currently support cloning for hot
591 // contexts, they should be converted to NotCold. This happens in the cloning
592 // support anyway, however, doing this now enables more aggressive context
593 // trimming when building the MIB metadata (and possibly may make the
594 // allocation have a single NotCold allocation type), greatly reducing
595 // overheads in bitcode, cloning memory and cloning time.
596 if (Alloc->hasAllocType(AllocationType::Hot)) {
597 convertHotToNotCold(Alloc);
598 // Check whether we now have a single alloc type.
599 if (hasSingleAllocType(Alloc->AllocTypes)) {
600 addSingleAllocTypeAttribute(CI, (AllocationType)Alloc->AllocTypes,
601 "single");
602 return false;
603 }
604 }
605 auto &Ctx = CI->getContext();
606 std::vector<uint64_t> MIBCallStack;
607 MIBCallStack.push_back(AllocStackId);
608 std::vector<Metadata *> MIBNodes;
609 uint64_t TotalBytes = 0;
610 uint64_t ColdBytes = 0;
611 assert(!Alloc->Callers.empty() && "addCallStack has not been called yet");
612 // The CalleeHasAmbiguousCallerContext flag is meant to say whether the
613 // callee of the given node has more than one caller. Here the node being
614 // passed in is the alloc and it has no callees. So it's false.
615 if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes,
616 /*CalleeHasAmbiguousCallerContext=*/false, TotalBytes,
617 ColdBytes)) {
618 assert(MIBCallStack.size() == 1 &&
619 "Should only be left with Alloc's location in stack");
620 CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes));
622 return true;
623 }
624 // If there exists corner case that CallStackTrie has one chain to leaf
625 // and all node in the chain have multi alloc type, conservatively give
626 // it non-cold allocation type.
627 // FIXME: Avoid this case before memory profile created. Alternatively, select
628 // hint based on fraction cold.
630 return false;
631}
632
633template <>
635 const MDNode *N, bool End)
636 : N(N) {
637 if (!N)
638 return;
639 Iter = End ? N->op_end() : N->op_begin();
640}
641
642template <>
643uint64_t
645 assert(Iter != N->op_end());
647 assert(StackIdCInt);
648 return StackIdCInt->getZExtValue();
649}
650
652 assert(N);
653 return mdconst::dyn_extract<ConstantInt>(N->operands().back())
654 ->getZExtValue();
655}
656
658 // TODO: Support more sophisticated merging, such as selecting the one with
659 // more bytes allocated, or implement support for carrying multiple allocation
660 // leaf contexts. For now, keep the first one.
661 if (A)
662 return A;
663 return B;
664}
665
667 // TODO: Support more sophisticated merging, which will require support for
668 // carrying multiple contexts. For now, keep the first one.
669 if (A)
670 return A;
671 return B;
672}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
static void emitIgnoredNonColdContextMessage(StringRef Tag, uint64_t FullStackId, StringRef Extra, uint64_t TotalSize)
static void saveFilteredNewMIBNodes(std::vector< Metadata * > &NewMIBNodes, std::vector< Metadata * > &SavedMIBNodes, unsigned CallerContextLength, uint64_t TotalBytes, uint64_t ColdBytes, bool BuiltFromExistingMetadata)
static MDNode * createMIBNode(LLVMContext &Ctx, ArrayRef< uint64_t > MIBCallStack, AllocationType AllocType, ArrayRef< ContextSizeTypePair > ContextInfo, const uint64_t MaxColdSize, bool BuiltFromExistingMetadata, uint64_t &TotalBytes, uint64_t &ColdBytes)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
void removeFnAttr(Attribute::AttrKind Kind)
Removes the attribute from the function.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
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:168
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1081
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:649
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition Metadata.h:1554
Root of the metadata hierarchy.
Definition Metadata.h:64
Diagnostic information for applied optimization remarks.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
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.
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
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 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...
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< unsigned > MinClonedColdBytePercent("memprof-cloning-cold-threshold", cl::init(100), cl::Hidden, cl::desc("Min percent of cold bytes to hint alloc cold during cloning"))
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
cl::opt< bool > MemProfUseAmbiguousAttributes
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
LLVM_ABI cl::opt< bool > MemProfKeepAllNotColdContexts("memprof-keep-all-not-cold-contexts", cl::init(false), cl::Hidden, cl::desc("Keep all non-cold contexts (increases cloning overheads)"))
cl::opt< unsigned > MinCallsiteColdBytePercent("memprof-callsite-cold-threshold", cl::init(100), cl::Hidden, cl::desc("Min percent of cold bytes at a callsite to discard non-cold " "contexts"))
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ABI 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.
Definition ModRef.h:74
cl::opt< bool > MemProfKeepContextSizeInfo("memprof-keep-context-size-info", cl::init(false), cl::Hidden, cl::desc("Keep context size information in memprof metadata"))
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
cl::opt< unsigned > MinPercentMaxColdSize("memprof-min-percent-max-cold-size", cl::init(100), cl::Hidden, cl::desc("Min percent of max cold bytes for critical cold context"))
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
#define N