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.
10//
11//===----------------------------------------------------------------------===//
12
15#include "llvm/IR/Constants.h"
18#include "llvm/Support/Format.h"
19
20using namespace llvm;
21using namespace llvm::memprof;
22
23#define DEBUG_TYPE "memory-profile-info"
24
25namespace llvm {
26
28 "memprof-report-hinted-sizes", cl::init(false), cl::Hidden,
29 cl::desc("Report total allocation sizes of hinted allocations"));
30
31// This is useful if we have enabled reporting of hinted sizes, and want to get
32// information from the indexing step for all contexts (especially for testing),
33// or have specified a value less than 100% for -memprof-cloning-cold-threshold.
35 "memprof-keep-all-not-cold-contexts", cl::init(false), cl::Hidden,
36 cl::desc("Keep all non-cold contexts (increases cloning overheads)"));
37
39 "memprof-cloning-cold-threshold", cl::init(100), cl::Hidden,
40 cl::desc("Min percent of cold bytes to hint alloc cold during cloning"));
41
42// Discard non-cold contexts if they overlap with much larger cold contexts,
43// specifically, if all contexts reaching a given callsite are at least this
44// percent cold byte allocations. This reduces the amount of cloning required
45// to expose the cold contexts when they greatly dominate non-cold contexts.
47 "memprof-callsite-cold-threshold", cl::init(100), cl::Hidden,
48 cl::desc("Min percent of cold bytes at a callsite to discard non-cold "
49 "contexts"));
50
51// Enable saving context size information for largest cold contexts, which can
52// be used to flag contexts for more aggressive cloning and reporting.
54 "memprof-min-percent-max-cold-size", cl::init(100), cl::Hidden,
55 cl::desc("Min percent of max cold bytes for critical cold context"));
56
57// Use this to keep the context size information in the memprof metadata for use
58// in remarks.
60 "memprof-keep-context-size-info", cl::init(false), cl::Hidden,
61 cl::desc("Keep context size information in memprof metadata"));
62
64 "memprof-ambiguous-attributes", cl::init(true), cl::Hidden,
65 cl::desc("Apply ambiguous memprof attribute to ambiguous allocations"));
66
67} // end namespace llvm
68
73
77
82
84 LLVMContext &Ctx) {
86 StackVals.reserve(CallStack.size());
87 for (auto Id : CallStack) {
88 auto *StackValMD =
89 ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id));
90 StackVals.push_back(StackValMD);
91 }
92 return MDNode::get(Ctx, StackVals);
93}
94
96 assert(MIB->getNumOperands() >= 2);
97 // The stack metadata is the first operand of each memprof MIB metadata.
98 return cast<MDNode>(MIB->getOperand(0));
99}
100
102 assert(MIB->getNumOperands() >= 2);
103 // The allocation type is currently the second operand of each memprof
104 // MIB metadata. This will need to change as we add additional allocation
105 // types that can be applied based on the allocation profile data.
106 auto *MDS = dyn_cast<MDString>(MIB->getOperand(1));
107 assert(MDS);
108 if (MDS->getString() == "cold") {
110 } else if (MDS->getString() == "hot") {
111 return AllocationType::Hot;
112 }
114}
115
118 return "ambiguous";
119 switch (Type) {
121 return "notcold";
122 break;
124 return "cold";
125 break;
127 return "hot";
128 break;
129 default:
130 assert(false && "Unexpected alloc type");
131 }
132 llvm_unreachable("invalid alloc type");
133}
134
136 const unsigned NumAllocTypes = llvm::popcount(AllocTypes);
137 assert(NumAllocTypes != 0);
138 return NumAllocTypes == 1;
139}
140
142 const uint8_t BothTypes =
144 return (AllocTypes & BothTypes) == BothTypes;
145}
146
148 if (!CB->hasFnAttr("memprof"))
149 return;
150 assert(CB->getFnAttr("memprof").getValueAsString() == "ambiguous");
151 CB->removeFnAttr("memprof");
152}
153
156 return;
157 // We may have an existing ambiguous attribute if we are reanalyzing
158 // after inlining.
159 if (CB->hasFnAttr("memprof")) {
160 assert(CB->getFnAttr("memprof").getValueAsString() == "ambiguous");
161 } else {
162 auto A = llvm::Attribute::get(CB->getContext(), "memprof", "ambiguous");
163 CB->addFnAttr(A);
164 }
165}
166
168 AllocationType AllocType, ArrayRef<uint64_t> StackIds,
169 std::vector<ContextTotalSize> ContextSizeInfo) {
170 bool First = true;
171 CallStackTrieNode *Curr = nullptr;
172 for (auto StackId : StackIds) {
173 // If this is the first stack frame, add or update alloc node.
174 if (First) {
175 First = false;
176 if (Alloc) {
177 assert(AllocStackId == StackId);
178 Alloc->addAllocType(AllocType);
179 } else {
180 AllocStackId = StackId;
181 Alloc = new CallStackTrieNode(AllocType);
182 }
183 Curr = Alloc;
184 continue;
185 }
186 // Update existing caller node if it exists.
187 auto [Next, Inserted] = Curr->Callers.try_emplace(StackId);
188 if (!Inserted) {
189 Curr = Next->second;
190 Curr->addAllocType(AllocType);
191 continue;
192 }
193 // Otherwise add a new caller node.
194 auto *New = new CallStackTrieNode(AllocType);
195 Next->second = New;
196 Curr = New;
197 }
198 assert(Curr);
199 // Append all of the ContextSizeInfo, along with their original AllocType.
200 llvm::append_range(Curr->ContextInfo,
201 llvm::map_range(ContextSizeInfo,
202 [AllocType](const ContextTotalSize &CTS) {
203 return ContextSizeTypePair(CTS,
204 AllocType);
205 }));
206}
207
209 // Note that we are building this from existing MD_memprof metadata.
210 BuiltFromExistingMetadata = true;
211 MDNode *StackMD = getMIBStackNode(MIB);
212 assert(StackMD);
213 std::vector<uint64_t> CallStack;
214 CallStack.reserve(StackMD->getNumOperands());
215 for (const auto &MIBStackIter : StackMD->operands()) {
216 auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter);
217 assert(StackId);
218 CallStack.push_back(StackId->getZExtValue());
219 }
220 std::vector<ContextTotalSize> ContextSizeInfo;
221 // Collect the context size information if it exists.
222 if (MIB->getNumOperands() > 2) {
223 for (unsigned I = 2; I < MIB->getNumOperands(); I++) {
224 MDNode *ContextSizePair = dyn_cast<MDNode>(MIB->getOperand(I));
225 assert(ContextSizePair->getNumOperands() == 2);
226 uint64_t FullStackId =
228 ->getZExtValue();
229 uint64_t TotalSize =
231 ->getZExtValue();
232 ContextSizeInfo.push_back({FullStackId, TotalSize});
233 }
234 }
235 addCallStack(getMIBAllocType(MIB), CallStack, std::move(ContextSizeInfo));
236}
237
241 const uint64_t MaxColdSize,
242 bool BuiltFromExistingMetadata,
243 uint64_t &TotalBytes, uint64_t &ColdBytes) {
244 SmallVector<Metadata *> MIBPayload(
245 {buildCallstackMetadata(MIBCallStack, Ctx)});
246 MIBPayload.push_back(
248
249 if (ContextInfo.empty()) {
250 // The profile matcher should have provided context size info if there was a
251 // MinCallsiteColdBytePercent < 100. Here we check >=100 to gracefully
252 // handle a user-provided percent larger than 100. However, we may not have
253 // this information if we built the Trie from existing MD_memprof metadata.
254 assert(BuiltFromExistingMetadata || MinCallsiteColdBytePercent >= 100);
255 return MDNode::get(Ctx, MIBPayload);
256 }
257
258 for (const auto &[CSI, AT] : ContextInfo) {
259 const auto &[FullStackId, TotalSize] = CSI;
260 TotalBytes += TotalSize;
261 bool LargeColdContext = false;
263 ColdBytes += TotalSize;
264 // If we have the max cold context size from summary information and have
265 // requested identification of contexts above a percentage of the max, see
266 // if this context qualifies. We should assume this is large if we rebuilt
267 // the trie from existing metadata (i.e. to update after inlining), in
268 // which case we don't have a MaxSize from the profile - we assume any
269 // context size info in existence on the metadata should be propagated.
270 if (BuiltFromExistingMetadata ||
271 (MaxColdSize > 0 && MinPercentMaxColdSize < 100 &&
272 TotalSize * 100 >= MaxColdSize * MinPercentMaxColdSize))
273 LargeColdContext = true;
274 }
275 // Only add the context size info as metadata if we need it in the thin
276 // link (currently if reporting of hinted sizes is enabled, we have
277 // specified a threshold for marking allocations cold after cloning, or we
278 // have identified this as a large cold context of interest above).
279 if (metadataIncludesAllContextSizeInfo() || LargeColdContext) {
280 auto *FullStackIdMD = ValueAsMetadata::get(
281 ConstantInt::get(Type::getInt64Ty(Ctx), FullStackId));
282 auto *TotalSizeMD = ValueAsMetadata::get(
283 ConstantInt::get(Type::getInt64Ty(Ctx), TotalSize));
284 auto *ContextSizeMD = MDNode::get(Ctx, {FullStackIdMD, TotalSizeMD});
285 MIBPayload.push_back(ContextSizeMD);
286 }
287 }
288 assert(TotalBytes > 0);
289 return MDNode::get(Ctx, MIBPayload);
290}
291
292void CallStackTrie::collectContextInfo(
293 CallStackTrieNode *Node, std::vector<ContextSizeTypePair> &ContextInfo) {
294 llvm::append_range(ContextInfo, Node->ContextInfo);
295 for (auto &Caller : Node->Callers)
296 collectContextInfo(Caller.second, ContextInfo);
297}
298
299void CallStackTrie::convertHotToNotCold(CallStackTrieNode *Node) {
300 if (Node->hasAllocType(AllocationType::Hot)) {
301 Node->removeAllocType(AllocationType::Hot);
302 Node->addAllocType(AllocationType::NotCold);
303 }
304 for (auto &Caller : Node->Callers)
305 convertHotToNotCold(Caller.second);
306}
307
308// Helper to emit messages for non-cold contexts that are ignored for various
309// reasons when reporting of hinted bytes is enabled.
311 uint64_t FullStackId,
312 StringRef Extra,
313 uint64_t TotalSize) {
314 errs() << "MemProf hinting: Total size for " << Tag
315 << " non-cold full allocation context hash " << FullStackId << Extra
316 << ": " << TotalSize << "\n";
317}
318
319// Copy over some or all of NewMIBNodes to the SavedMIBNodes vector, depending
320// on options that enable filtering out some NotCold contexts.
321static void saveFilteredNewMIBNodes(std::vector<Metadata *> &NewMIBNodes,
322 std::vector<Metadata *> &SavedMIBNodes,
323 unsigned CallerContextLength,
324 uint64_t TotalBytes, uint64_t ColdBytes,
325 bool BuiltFromExistingMetadata) {
326 const bool MostlyCold =
327 // If we have built the Trie from existing MD_memprof metadata, we may or
328 // may not have context size information (in which case ColdBytes and
329 // TotalBytes are 0, which is not also guarded against below). Even if we
330 // do have some context size information from the the metadata, we have
331 // already gone through a round of discarding of small non-cold contexts
332 // during matching, and it would be overly aggressive to do it again, and
333 // we also want to maintain the same behavior with and without reporting
334 // of hinted bytes enabled.
335 !BuiltFromExistingMetadata && MinCallsiteColdBytePercent < 100 &&
336 ColdBytes > 0 &&
337 ColdBytes * 100 >= MinCallsiteColdBytePercent * TotalBytes;
338
339 // In the simplest case, with pruning disabled, keep all the new MIB nodes.
340 if (MemProfKeepAllNotColdContexts && !MostlyCold) {
341 append_range(SavedMIBNodes, NewMIBNodes);
342 return;
343 }
344
345 auto EmitMessageForRemovedContexts = [](const MDNode *MIBMD, StringRef Tag,
346 StringRef Extra) {
347 assert(MIBMD->getNumOperands() > 2);
348 for (unsigned I = 2; I < MIBMD->getNumOperands(); I++) {
349 MDNode *ContextSizePair = dyn_cast<MDNode>(MIBMD->getOperand(I));
350 assert(ContextSizePair->getNumOperands() == 2);
351 uint64_t FullStackId =
353 ->getZExtValue();
354 uint64_t TS =
356 ->getZExtValue();
357 emitIgnoredNonColdContextMessage(Tag, FullStackId, Extra, TS);
358 }
359 };
360
361 // If the cold bytes at the current callsite exceed the given threshold, we
362 // discard all non-cold contexts so do not need any of the later pruning
363 // handling. We can simply copy over all the cold contexts and return early.
364 if (MostlyCold) {
365 auto NewColdMIBNodes =
366 make_filter_range(NewMIBNodes, [&](const Metadata *M) {
367 auto MIBMD = cast<MDNode>(M);
368 // Only append cold contexts.
370 return true;
372 const float PercentCold = ColdBytes * 100.0 / TotalBytes;
373 std::string PercentStr;
374 llvm::raw_string_ostream OS(PercentStr);
375 OS << format(" for %5.2f%% cold bytes", PercentCold);
376 EmitMessageForRemovedContexts(MIBMD, "discarded", OS.str());
377 }
378 return false;
379 });
380 for (auto *M : NewColdMIBNodes)
381 SavedMIBNodes.push_back(M);
382 return;
383 }
384
385 // Prune unneeded NotCold contexts, taking advantage of the fact
386 // that we later will only clone Cold contexts, as NotCold is the allocation
387 // default. We only need to keep as metadata the NotCold contexts that
388 // overlap the longest with Cold allocations, so that we know how deeply we
389 // need to clone. For example, assume we add the following contexts to the
390 // trie:
391 // 1 3 (notcold)
392 // 1 2 4 (cold)
393 // 1 2 5 (notcold)
394 // 1 2 6 (notcold)
395 // the trie looks like:
396 // 1
397 // / \
398 // 2 3
399 // /|\
400 // 4 5 6
401 //
402 // It is sufficient to prune all but one not-cold contexts (either 1,2,5 or
403 // 1,2,6, we arbitrarily keep the first one we encounter which will be
404 // 1,2,5).
405 //
406 // To do this pruning, we first check if there were any not-cold
407 // contexts kept for a deeper caller, which will have a context length larger
408 // than the CallerContextLength being handled here (i.e. kept by a deeper
409 // recursion step). If so, none of the not-cold MIB nodes added for the
410 // immediate callers need to be kept. If not, we keep the first (created
411 // for the immediate caller) not-cold MIB node.
412 bool LongerNotColdContextKept = false;
413 for (auto *MIB : NewMIBNodes) {
414 auto MIBMD = cast<MDNode>(MIB);
416 continue;
417 MDNode *StackMD = getMIBStackNode(MIBMD);
418 assert(StackMD);
419 if (StackMD->getNumOperands() > CallerContextLength) {
420 LongerNotColdContextKept = true;
421 break;
422 }
423 }
424 // Don't need to emit any for the immediate caller if we already have
425 // longer overlapping contexts;
426 bool KeepFirstNewNotCold = !LongerNotColdContextKept;
427 auto NewColdMIBNodes = make_filter_range(NewMIBNodes, [&](const Metadata *M) {
428 auto MIBMD = cast<MDNode>(M);
429 // Only keep cold contexts and first (longest non-cold context).
431 MDNode *StackMD = getMIBStackNode(MIBMD);
432 assert(StackMD);
433 // Keep any already kept for longer contexts.
434 if (StackMD->getNumOperands() > CallerContextLength)
435 return true;
436 // Otherwise keep the first one added by the immediate caller if there
437 // were no longer contexts.
438 if (KeepFirstNewNotCold) {
439 KeepFirstNewNotCold = false;
440 return true;
441 }
443 EmitMessageForRemovedContexts(MIBMD, "pruned", "");
444 return false;
445 }
446 return true;
447 });
448 for (auto *M : NewColdMIBNodes)
449 SavedMIBNodes.push_back(M);
450}
451
452// Recursive helper to trim contexts and create metadata nodes.
453// Caller should have pushed Node's loc to MIBCallStack. Doing this in the
454// caller makes it simpler to handle the many early returns in this method.
455// Updates the total and cold profiled bytes in the subtrie rooted at this node.
456bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
457 std::vector<uint64_t> &MIBCallStack,
458 std::vector<Metadata *> &MIBNodes,
459 bool CalleeHasAmbiguousCallerContext,
460 uint64_t &TotalBytes, uint64_t &ColdBytes) {
461 // Trim context below the first node in a prefix with a single alloc type.
462 // Add an MIB record for the current call stack prefix.
463 if (hasSingleAllocType(Node->AllocTypes)) {
464 std::vector<ContextSizeTypePair> ContextInfo;
465 collectContextInfo(Node, ContextInfo);
466 MIBNodes.push_back(createMIBNode(
467 Ctx, MIBCallStack, (AllocationType)Node->AllocTypes, ContextInfo,
468 MaxColdSize, BuiltFromExistingMetadata, TotalBytes, ColdBytes));
469 return true;
470 }
471
472 // We don't have a single allocation for all the contexts sharing this prefix,
473 // so recursively descend into callers in trie.
474 if (!Node->Callers.empty()) {
475 bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1;
476 bool AddedMIBNodesForAllCallerContexts = true;
477 // Accumulate all new MIB nodes by the recursive calls below into a vector
478 // that will later be filtered before adding to the caller's MIBNodes
479 // vector.
480 std::vector<Metadata *> NewMIBNodes;
481 // Determine the total and cold byte counts for all callers, then add to the
482 // caller's counts further below.
483 uint64_t CallerTotalBytes = 0;
484 uint64_t CallerColdBytes = 0;
485 for (auto &Caller : Node->Callers) {
486 MIBCallStack.push_back(Caller.first);
487 AddedMIBNodesForAllCallerContexts &= buildMIBNodes(
488 Caller.second, Ctx, MIBCallStack, NewMIBNodes,
489 NodeHasAmbiguousCallerContext, CallerTotalBytes, CallerColdBytes);
490 // Remove Caller.
491 MIBCallStack.pop_back();
492 }
493 // Pass in the stack length of the MIB nodes added for the immediate caller,
494 // which is the current stack length plus 1.
495 saveFilteredNewMIBNodes(NewMIBNodes, MIBNodes, MIBCallStack.size() + 1,
496 CallerTotalBytes, CallerColdBytes,
497 BuiltFromExistingMetadata);
498 TotalBytes += CallerTotalBytes;
499 ColdBytes += CallerColdBytes;
500
501 if (AddedMIBNodesForAllCallerContexts)
502 return true;
503 // We expect that the callers should be forced to add MIBs to disambiguate
504 // the context in this case (see below).
505 assert(!NodeHasAmbiguousCallerContext);
506 }
507
508 // If we reached here, then this node does not have a single allocation type,
509 // and we didn't add metadata for a longer call stack prefix including any of
510 // Node's callers. That means we never hit a single allocation type along all
511 // call stacks with this prefix. This can happen due to recursion collapsing
512 // or the stack being deeper than tracked by the profiler runtime, leading to
513 // contexts with different allocation types being merged. In that case, we
514 // trim the context just below the deepest context split, which is this
515 // node if the callee has an ambiguous caller context (multiple callers),
516 // since the recursive calls above returned false. Conservatively give it
517 // non-cold allocation type.
518 if (!CalleeHasAmbiguousCallerContext)
519 return false;
520 std::vector<ContextSizeTypePair> ContextInfo;
521 collectContextInfo(Node, ContextInfo);
522 MIBNodes.push_back(createMIBNode(
523 Ctx, MIBCallStack, AllocationType::NotCold, ContextInfo, MaxColdSize,
524 BuiltFromExistingMetadata, TotalBytes, ColdBytes));
525 return true;
526}
527
529 StringRef Descriptor) {
530 auto AllocTypeString = getAllocTypeAttributeString(AT);
531 auto A = llvm::Attribute::get(CI->getContext(), "memprof", AllocTypeString);
532 // After inlining we may be able to convert an existing ambiguous allocation
533 // to an unambiguous one.
535 CI->addFnAttr(A);
536
537 std::vector<ContextSizeTypePair> ContextInfo;
538 collectContextInfo(Alloc, ContextInfo);
539
540 // If we don't have context size info, just emit a single remark for this
541 // allocation.
542 if (ContextInfo.empty()) {
543 if (ORE)
544 ORE->emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", CI)
545 << ore::NV("AllocationCall", CI) << " in function "
546 << ore::NV("Caller", CI->getFunction())
547 << " marked with memprof allocation attribute "
548 << ore::NV("Attribute", AllocTypeString));
549 return;
550 }
551
552 // Emit remarks or stderr reporting if requested.
553 for (const auto &[CSI, OrigAT] : ContextInfo) {
554 const auto &[FullStackId, TotalSize] = CSI;
555 // If the original alloc type is not the one being applied as the hint,
556 // then don't report that it was hinted. Optionally report that we ignored
557 // this context.
558 if (AT != OrigAT) {
560 emitIgnoredNonColdContextMessage("ignored", FullStackId, "", TotalSize);
561 continue;
562 }
564 errs() << "MemProf hinting: Total size for full allocation context hash "
565 << FullStackId << " and " << Descriptor << " alloc type "
566 << getAllocTypeAttributeString(AT) << ": " << TotalSize << "\n";
567 if (ORE)
568 ORE->emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", CI)
569 << ore::NV("AllocationCall", CI) << " in function "
570 << ore::NV("Caller", CI->getFunction())
571 << " marked with memprof allocation attribute "
572 << ore::NV("Attribute", AllocTypeString)
573 << " for full allocation context hash "
574 << ore::NV("FullStackId", FullStackId) << " with total size "
575 << ore::NV("TotalSize", TotalSize));
576 }
577}
578
579// Build and attach the minimal necessary MIB metadata. If the alloc has a
580// single allocation type, add a function attribute instead. Returns true if
581// memprof metadata attached, false if not (attribute added).
583 if (hasSingleAllocType(Alloc->AllocTypes)) {
584 addSingleAllocTypeAttribute(CI, (AllocationType)Alloc->AllocTypes,
585 "single");
586 return false;
587 }
588 // If there were any hot allocation contexts, the Alloc trie node would have
589 // the Hot type set. If so, because we don't currently support cloning for hot
590 // contexts, they should be converted to NotCold. This happens in the cloning
591 // support anyway, however, doing this now enables more aggressive context
592 // trimming when building the MIB metadata (and possibly may make the
593 // allocation have a single NotCold allocation type), greatly reducing
594 // overheads in bitcode, cloning memory and cloning time.
595 if (Alloc->hasAllocType(AllocationType::Hot)) {
596 convertHotToNotCold(Alloc);
597 // Check whether we now have a single alloc type.
598 if (hasSingleAllocType(Alloc->AllocTypes)) {
599 addSingleAllocTypeAttribute(CI, (AllocationType)Alloc->AllocTypes,
600 "single");
601 return false;
602 }
603 }
604 auto &Ctx = CI->getContext();
605 std::vector<uint64_t> MIBCallStack;
606 MIBCallStack.push_back(AllocStackId);
607 std::vector<Metadata *> MIBNodes;
608 uint64_t TotalBytes = 0;
609 uint64_t ColdBytes = 0;
610 assert(!Alloc->Callers.empty() && "addCallStack has not been called yet");
611 // The CalleeHasAmbiguousCallerContext flag is meant to say whether the
612 // callee of the given node has more than one caller. Here the node being
613 // passed in is the alloc and it has no callees. So it's false.
614 if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes,
615 /*CalleeHasAmbiguousCallerContext=*/false, TotalBytes,
616 ColdBytes)) {
617 assert(MIBCallStack.size() == 1 &&
618 "Should only be left with Alloc's location in stack");
619 CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes));
621 return true;
622 }
623 // If there exists corner case that CallStackTrie has one chain to leaf
624 // and all node in the chain have multi alloc type, conservatively give
625 // it non-cold allocation type.
626 // FIXME: Avoid this case before memory profile created. Alternatively, select
627 // hint based on fraction cold.
629 return false;
630}
631
632template <>
634 const MDNode *N, bool End)
635 : N(N) {
636 if (!N)
637 return;
638 Iter = End ? N->op_end() : N->op_begin();
639}
640
641template <>
642uint64_t
644 assert(Iter != N->op_end());
646 assert(StackIdCInt);
647 return StackIdCInt->getZExtValue();
648}
649
651 assert(N);
652 return mdconst::dyn_extract<ConstantInt>(N->operands().back())
653 ->getZExtValue();
654}
655
657 // TODO: Support more sophisticated merging, such as selecting the one with
658 // more bytes allocated, or implement support for carrying multiple allocation
659 // leaf contexts. For now, keep the first one.
660 if (A)
661 return A;
662 return B;
663}
664
666 // TODO: Support more sophisticated merging, which will require support for
667 // carrying multiple contexts. For now, keep the first one.
668 if (A)
669 return A;
670 return B;
671}
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