LLVM 24.0.0git
MemProfContextDisambiguation.cpp
Go to the documentation of this file.
1//==-- MemProfContextDisambiguation.cpp - Disambiguate contexts -------------=//
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 implements support for context disambiguation of allocation
10// calls for profile guided heap optimization. Specifically, it uses Memprof
11// profiles which indicate context specific allocation behavior (currently
12// distinguishing cold vs hot memory allocations). Cloning is performed to
13// expose the cold allocation call contexts, and the allocation calls are
14// subsequently annotated with an attribute for later transformation.
15//
16// The transformations can be performed either directly on IR (regular LTO), or
17// on a ThinLTO index (and later applied to the IR during the ThinLTO backend).
18// Both types of LTO operate on a the same base graph representation, which
19// uses CRTP to support either IR or Index formats.
20//
21//===----------------------------------------------------------------------===//
22
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/Statistic.h"
38#include "llvm/IR/Module.h"
40#include "llvm/Pass.h"
43#include "llvm/Support/SHA1.h"
45#include "llvm/Transforms/IPO.h"
49#include <deque>
50#include <sstream>
51#include <vector>
52using namespace llvm;
53using namespace llvm::memprof;
54
55#define DEBUG_TYPE "memprof-context-disambiguation"
56
57STATISTIC(FunctionClonesAnalysis,
58 "Number of function clones created during whole program analysis");
59STATISTIC(FunctionClonesThinBackend,
60 "Number of function clones created during ThinLTO backend");
61STATISTIC(FunctionsClonedThinBackend,
62 "Number of functions that had clones created during ThinLTO backend");
64 FunctionCloneDuplicatesThinBackend,
65 "Number of function clone duplicates detected during ThinLTO backend");
66STATISTIC(AllocTypeNotCold, "Number of not cold static allocations (possibly "
67 "cloned) during whole program analysis");
68STATISTIC(AllocTypeCold, "Number of cold static allocations (possibly cloned) "
69 "during whole program analysis");
70STATISTIC(AllocTypeAmbiguous,
71 "Number of ambiguous static allocations (possibly cloned) during "
72 "whole program analysis");
73STATISTIC(AllocTypeNotColdThinBackend,
74 "Number of not cold static allocations (possibly cloned) during "
75 "ThinLTO backend");
76STATISTIC(AllocTypeColdThinBackend, "Number of cold static allocations "
77 "(possibly cloned) during ThinLTO backend");
78STATISTIC(AllocTypeAmbiguousThinBackend,
79 "Number of ambiguous static allocations (possibly cloned) during "
80 "ThinLTO backend");
81STATISTIC(OrigAllocsThinBackend,
82 "Number of original (not cloned) allocations with memprof profiles "
83 "during ThinLTO backend");
85 AllocVersionsThinBackend,
86 "Number of allocation versions (including clones) during ThinLTO backend");
87STATISTIC(MaxAllocVersionsThinBackend,
88 "Maximum number of allocation versions created for an original "
89 "allocation during ThinLTO backend");
90STATISTIC(UnclonableAllocsThinBackend,
91 "Number of unclonable ambigous allocations during ThinLTO backend");
92STATISTIC(RemovedEdgesWithMismatchedCallees,
93 "Number of edges removed due to mismatched callees (profiled vs IR)");
94STATISTIC(FoundProfiledCalleeCount,
95 "Number of profiled callees found via tail calls");
96STATISTIC(FoundProfiledCalleeDepth,
97 "Aggregate depth of profiled callees found via tail calls");
98STATISTIC(FoundProfiledCalleeMaxDepth,
99 "Maximum depth of profiled callees found via tail calls");
100STATISTIC(FoundProfiledCalleeNonUniquelyCount,
101 "Number of profiled callees found via multiple tail call chains");
102STATISTIC(FoundProfiledCalleeIndirectTailCallCount,
103 "Number of tail calls in chains to profiled callees that are "
104 "indirect (thin link)");
105STATISTIC(IndirectTailCallsRecordedForICPThinBackend,
106 "Number of indirect tail calls recorded for ICP for cloning during "
107 "ThinLTO backend");
108STATISTIC(DeferredBackedges, "Number of backedges with deferred cloning");
109STATISTIC(NewMergedNodes, "Number of new nodes created during merging");
110STATISTIC(NonNewMergedNodes, "Number of non new nodes used during merging");
111STATISTIC(MissingAllocForContextId,
112 "Number of missing alloc nodes for context ids");
113STATISTIC(SkippedCallsCloning,
114 "Number of calls skipped during cloning due to unexpected operand");
115STATISTIC(MismatchedCloneAssignments,
116 "Number of callsites assigned to call multiple non-matching clones");
117STATISTIC(TotalMergeInvokes, "Number of merge invocations for nodes");
118STATISTIC(TotalMergeIters, "Number of merge iterations for nodes");
119STATISTIC(MaxMergeIters, "Max merge iterations for nodes");
120STATISTIC(NumImportantContextIds, "Number of important context ids");
121STATISTIC(NumFixupEdgeIdsInserted, "Number of fixup edge ids inserted");
122STATISTIC(NumFixupEdgesAdded, "Number of fixup edges added");
123STATISTIC(NumFixedContexts, "Number of contexts with fixed edges");
124STATISTIC(NumImplicitCallersAssigned,
125 "Number of callsite clones without an edge to a callee's clones "
126 "assigned the callee function clone of their original node");
127STATISTIC(NumImplicitCallersSourced,
128 "Number of calls in function clones whose callee was taken from a "
129 "callsite clone an implicit caller requires");
130STATISTIC(NumTrimmedContextIds,
131 "Number of context ids with call stacks trimmed at a callsite");
132STATISTIC(NumImplicitCallersUnresolved,
133 "Number of callsite clones without an edge to a callee's clones "
134 "left in a function clone calling a conflicting callee clone");
135STATISTIC(AliaseesPrevailingInDiffModuleFromAlias,
136 "Number of aliasees prevailing in a different module than its alias");
137STATISTIC(NumClonedCalleeCallsites,
138 "Number of summary callsites assigned to call a cloned callee (thin "
139 "link)");
140STATISTIC(NumClonedCalleeIndirectCallsites,
141 "Number of summary callsites assigned to call a cloned callee with "
142 "an indirect call edge (thin link)");
143STATISTIC(NumClonedCalleeEdgesMarkedRequiresDeclImport,
144 "Number of summary indirect call edges to cloned callees marked as "
145 "requiring a declaration import (thin link)");
146
148 "memprof-dot-file-path-prefix", cl::init(""), cl::Hidden,
149 cl::value_desc("filename"),
150 cl::desc("Specify the path prefix of the MemProf dot files."));
151
152static cl::opt<bool> ExportToDot("memprof-export-to-dot", cl::init(false),
154 cl::desc("Export graph to dot files."));
155
156// TODO: Remove this option once new handling is validated more widely.
158 "memprof-merge-iteration", cl::init(true), cl::Hidden,
159 cl::desc("Iteratively apply merging on a node to catch new callers"));
160
161// How much of the graph to export to dot.
163 All, // The full CCG graph.
164 Alloc, // Only contexts for the specified allocation.
165 Context, // Only the specified context.
166};
167
169 "memprof-dot-scope", cl::desc("Scope of graph to export to dot"),
172 clEnumValN(DotScope::All, "all", "Export full callsite graph"),
174 "Export only nodes with contexts feeding given "
175 "-memprof-dot-alloc-id"),
176 clEnumValN(DotScope::Context, "context",
177 "Export only nodes with given -memprof-dot-context-id")));
178
180 AllocIdForDot("memprof-dot-alloc-id", cl::init(0), cl::Hidden,
181 cl::desc("Id of alloc to export if -memprof-dot-scope=alloc "
182 "or to highlight if -memprof-dot-scope=all"));
183
185 "memprof-dot-context-id", cl::init(0), cl::Hidden,
186 cl::desc("Id of context to export if -memprof-dot-scope=context or to "
187 "highlight otherwise"));
188
189static cl::opt<bool>
190 DumpCCG("memprof-dump-ccg", cl::init(false), cl::Hidden,
191 cl::desc("Dump CallingContextGraph to stdout after each stage."));
192
193static cl::opt<bool>
194 VerifyCCG("memprof-verify-ccg", cl::init(false), cl::Hidden,
195 cl::desc("Perform verification checks on CallingContextGraph."));
196
197static cl::opt<bool>
198 VerifyNodes("memprof-verify-nodes", cl::init(false), cl::Hidden,
199 cl::desc("Perform frequent verification checks on nodes."));
200
202 "memprof-import-summary",
203 cl::desc("Import summary to use for testing the ThinLTO backend via opt"),
204 cl::Hidden);
205
207 TailCallSearchDepth("memprof-tail-call-search-depth", cl::init(5),
209 cl::desc("Max depth to recursively search for missing "
210 "frames through tail calls."));
211
212// Whether the ThinLTO search for frames missing due to tail calls should look
213// through indirect tail calls, via the summary call edges to their profiled
214// targets.
216 "memprof-indirect-tail-call-search", cl::init(true), cl::Hidden,
217 cl::desc("Search for missing frames through indirect tail calls to their "
218 "profiled targets (ThinLTO)."));
219
220// Optionally enable cloning of callsites involved with recursive cycles
222 "memprof-allow-recursive-callsites", cl::init(true), cl::Hidden,
223 cl::desc("Allow cloning of callsites involved in recursive cycles"));
224
226 "memprof-clone-recursive-contexts", cl::init(true), cl::Hidden,
227 cl::desc("Allow cloning of contexts through recursive cycles"));
228
229// Generally this is needed for correct assignment of allocation clones to
230// function clones, however, allow it to be disabled for debugging while the
231// functionality is new and being tested more widely.
232static cl::opt<bool>
233 MergeClones("memprof-merge-clones", cl::init(true), cl::Hidden,
234 cl::desc("Merge clones before assigning functions"));
235
236// When disabled, try to detect and prevent cloning of recursive contexts.
237// This is only necessary until we support cloning through recursive cycles.
238// Leave on by default for now, as disabling requires a little bit of compile
239// time overhead and doesn't affect correctness, it will just inflate the cold
240// hinted bytes reporting a bit when -memprof-report-hinted-sizes is enabled.
242 "memprof-allow-recursive-contexts", cl::init(true), cl::Hidden,
243 cl::desc("Allow cloning of contexts having recursive cycles"));
244
245// Set the minimum absolute count threshold for allowing inlining of indirect
246// calls promoted during cloning.
248 "memprof-icp-noinline-threshold", cl::init(0), cl::Hidden,
249 cl::desc("Minimum absolute count for promoted target to be inlinable"));
250
251namespace llvm {
253 "enable-memprof-context-disambiguation", cl::Hidden,
254 cl::desc("Enable MemProf context disambiguation"));
255
256// Indicate we are linking with an allocator that supports hot/cold operator
257// new interfaces.
259 "supports-hot-cold-new", cl::init(false), cl::Hidden,
260 cl::desc("Linking with hot/cold operator new interfaces"));
261
263 "memprof-require-definition-for-promotion", cl::init(false), cl::Hidden,
264 cl::desc(
265 "Require target function definition when promoting indirect calls"));
266
267// Applying the thin link cloning decisions to indirect calls requires the
268// ThinLTO backend to perform ICP to the profiled target, which requires that
269// the target be available in the caller's module (or in any module the caller
270// is imported into). When the target is defined in a different module it must
271// be imported, but the profiled targets are often synthesized from the MemProf
272// profile with a small count, so their summary edges are not hot and large
273// targets are often not imported. Since the thin link cloning runs before the
274// function importing analysis, we can mark the indirect call edges to callees
275// of callsites that were assigned to call a cloned callee as requiring a
276// declaration import, in which case the function importer imports at least a
277// declaration of the callee into any module containing the caller that
278// doesn't define the callee. Direct calls don't require importing the callee,
279// since the ThinLTO backend can simply call a declaration of the callee clone,
280// so we only do this for edges marked as being from indirect calls in the
281// summary. Note that unlike regular ICP, which by default requires the
282// target's definition (see -icp-allow-decls), MemProf ICP can promote to a
283// declaration of the target (see -memprof-require-definition-for-promotion),
284// since the purpose is to call the assigned clone rather than to inline. This
285// is therefore not done under -memprof-require-definition-for-promotion.
287 "memprof-import-cloned-indirect-targets", cl::init(true), cl::Hidden,
288 cl::desc("Import at least a declaration of the indirect call targets of "
289 "callsites assigned to call a cloned callee (needed for MemProf "
290 "ICP in the ThinLTO backend)"));
291
295
296// Appends a per-context diagnostic suffix to each -memprof-report-hinted-sizes
297// line: the allocation function clone, how far the context matched, and the
298// post-cloning call paths from the outermost matched caller to the reached
299// allocation clone(s) and their final hints. Requires
300// -memprof-report-hinted-sizes, and adds some memory and time overhead.
302 "memprof-report-hinted-sizes-detail", cl::init(false), cl::Hidden,
303 cl::desc("Append post-cloning call path and matching details to each "
304 "-memprof-report-hinted-sizes line"));
305
306// Post-cloning call paths in the detail suffix longer than this (in functions)
307// have runs of uncloned (or cloned) functions in their middle elided to
308// "...", keeping the ends and every cloned/uncloned transition.
310 "memprof-report-hinted-sizes-detail-max-path-len", cl::init(7), cl::Hidden,
311 cl::desc("Maximum number of functions printed in full for a post-cloning "
312 "call path in the -memprof-report-hinted-sizes-detail suffix; "
313 "longer paths are elided in the middle"));
314
316 "memprof-top-n-important", cl::init(10), cl::Hidden,
317 cl::desc("Number of largest cold contexts to consider important"));
318
320 "memprof-fixup-important", cl::init(true), cl::Hidden,
321 cl::desc("Enables edge fixup for important contexts"));
322
323} // namespace llvm
324
325namespace {
326
327/// CRTP base for graphs built from either IR or ThinLTO summary index.
328///
329/// The graph represents the call contexts in all memprof metadata on allocation
330/// calls, with nodes for the allocations themselves, as well as for the calls
331/// in each context. The graph is initially built from the allocation memprof
332/// metadata (or summary) MIBs. It is then updated to match calls with callsite
333/// metadata onto the nodes, updating it to reflect any inlining performed on
334/// those calls.
335///
336/// Each MIB (representing an allocation's call context with allocation
337/// behavior) is assigned a unique context id during the graph build. The edges
338/// and nodes in the graph are decorated with the context ids they carry. This
339/// is used to correctly update the graph when cloning is performed so that we
340/// can uniquify the context for a single (possibly cloned) allocation.
341template <typename DerivedCCG, typename FuncTy, typename CallTy>
342class CallsiteContextGraph {
343public:
344 CallsiteContextGraph() = default;
345 CallsiteContextGraph(const CallsiteContextGraph &) = default;
346 CallsiteContextGraph(CallsiteContextGraph &&) = default;
347
348 /// Main entry point to perform analysis and transformations on graph.
349 bool process(function_ref<void(StringRef, StringRef, const Twine &)>
350 EmitRemark = nullptr,
351 bool AllowExtraAnalysis = false);
352
353 /// Perform cloning on the graph necessary to uniquely identify the allocation
354 /// behavior of an allocation based on its context.
355 void identifyClones();
356
357 /// Assign callsite clones to functions, cloning functions as needed to
358 /// accommodate the combinations of their callsite clones reached by callers.
359 /// For regular LTO this clones functions and callsites in the IR, but for
360 /// ThinLTO the cloning decisions are noted in the summaries and later applied
361 /// in applyImport.
362 bool assignFunctions();
363
364 void dump() const;
365 void print(raw_ostream &OS) const;
366 void printTotalSizes(raw_ostream &OS,
367 function_ref<void(StringRef, StringRef, const Twine &)>
368 EmitRemark = nullptr) const;
369
371 const CallsiteContextGraph &CCG) {
372 CCG.print(OS);
373 return OS;
374 }
375
376 friend struct GraphTraits<
377 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
378 friend struct DOTGraphTraits<
379 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
380
381 void exportToDot(std::string Label) const;
382
383 /// Represents a function clone via FuncTy pointer and clone number pair.
384 struct FuncInfo final
385 : public std::pair<FuncTy *, unsigned /*Clone number*/> {
386 using Base = std::pair<FuncTy *, unsigned>;
387 FuncInfo(const Base &B) : Base(B) {}
388 FuncInfo(FuncTy *F = nullptr, unsigned CloneNo = 0) : Base(F, CloneNo) {}
389 explicit operator bool() const { return this->first != nullptr; }
390 FuncTy *func() const { return this->first; }
391 unsigned cloneNo() const { return this->second; }
392 };
393
394 /// Represents a callsite clone via CallTy and clone number pair.
395 struct CallInfo final : public std::pair<CallTy, unsigned /*Clone number*/> {
396 using Base = std::pair<CallTy, unsigned>;
397 CallInfo(const Base &B) : Base(B) {}
398 CallInfo(CallTy Call = nullptr, unsigned CloneNo = 0)
399 : Base(Call, CloneNo) {}
400 explicit operator bool() const { return (bool)this->first; }
401 CallTy call() const { return this->first; }
402 unsigned cloneNo() const { return this->second; }
403 void setCloneNo(unsigned N) { this->second = N; }
404 void print(raw_ostream &OS) const {
405 if (!operator bool()) {
406 assert(!cloneNo());
407 OS << "null Call";
408 return;
409 }
410 call()->print(OS);
411 OS << "\t(clone " << cloneNo() << ")";
412 }
413 void dump() const {
414 print(dbgs());
415 dbgs() << "\n";
416 }
417 friend raw_ostream &operator<<(raw_ostream &OS, const CallInfo &Call) {
418 Call.print(OS);
419 return OS;
420 }
421 };
422
423 struct ContextEdge;
424
425 /// Node in the Callsite Context Graph
426 struct ContextNode {
427 // Assigned to nodes as they are created, useful for debugging.
428 unsigned NodeId = 0;
429
430 // Keep this for now since in the IR case where we have an Instruction* it
431 // is not as immediately discoverable. Used for printing richer information
432 // when dumping graph.
433 bool IsAllocation;
434
435 // Keeps track of when the Call was reset to null because there was
436 // recursion.
437 bool Recursive = false;
438
439 // This will be formed by ORing together the AllocationType enum values
440 // for contexts including this node.
441 uint8_t AllocTypes = 0;
442
443 // The corresponding allocation or interior call. This is the primary call
444 // for which we have created this node.
445 CallInfo Call;
446
447 // List of other calls that can be treated the same as the primary call
448 // through cloning. I.e. located in the same function and have the same
449 // (possibly trimmed) stack ids. They will be updated the same way as the
450 // primary call when assigning to function clones.
451 SmallVector<CallInfo, 0> MatchingCalls;
452
453 // For alloc nodes this is a unique id assigned when constructed, and for
454 // callsite stack nodes it is the original stack id when the node is
455 // constructed from the memprof MIB metadata on the alloc nodes. Note that
456 // this is only used when matching callsite metadata onto the stack nodes
457 // created when processing the allocation memprof MIBs, and for labeling
458 // nodes in the dot graph. Therefore we don't bother to assign a value for
459 // clones.
460 uint64_t OrigStackOrAllocId = 0;
461
462 // Edges to all callees in the profiled call stacks.
463 // TODO: Should this be a map (from Callee node) for more efficient lookup?
464 std::vector<std::shared_ptr<ContextEdge>> CalleeEdges;
465
466 // Edges to all callers in the profiled call stacks.
467 // TODO: Should this be a map (from Caller node) for more efficient lookup?
468 std::vector<std::shared_ptr<ContextEdge>> CallerEdges;
469
470 // Returns true if we need to look at the callee edges for determining the
471 // node context ids and allocation type.
472 bool useCallerEdgesForContextInfo() const {
473 // Typically if the callee edges are empty either the caller edges are
474 // also empty, or this is an allocation (leaf node). However, if we are
475 // allowing recursive callsites and contexts this will be violated for
476 // incompletely cloned recursive cycles.
477 assert(!CalleeEdges.empty() || CallerEdges.empty() || IsAllocation ||
479 // When cloning for a recursive context, during cloning we might be in the
480 // midst of cloning for a recurrence and have moved context ids off of a
481 // caller edge onto the clone but not yet off of the incoming caller
482 // (back) edge. If we don't look at those we miss the fact that this node
483 // still has context ids of interest.
484 return IsAllocation || CloneRecursiveContexts;
485 }
486
487 // Compute the context ids for this node from the union of its edge context
488 // ids.
489 DenseSet<uint32_t> getContextIds() const {
490 unsigned Count = 0;
491 // Compute the number of ids for reserve below. In general we only need to
492 // look at one set of edges, typically the callee edges, since other than
493 // allocations and in some cases during recursion cloning, all the context
494 // ids on the callers should also flow out via callee edges.
495 for (auto &Edge : CalleeEdges.empty() ? CallerEdges : CalleeEdges)
496 Count += Edge->getContextIds().size();
497 DenseSet<uint32_t> ContextIds;
498 ContextIds.reserve(Count);
500 CalleeEdges, useCallerEdgesForContextInfo()
501 ? CallerEdges
502 : std::vector<std::shared_ptr<ContextEdge>>());
503 for (const auto &Edge : Edges)
504 ContextIds.insert_range(Edge->getContextIds());
505 return ContextIds;
506 }
507
508 // Compute the allocation type for this node from the OR of its edge
509 // allocation types.
510 uint8_t computeAllocType() const {
511 uint8_t BothTypes =
512 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
513 uint8_t AllocType = (uint8_t)AllocationType::None;
515 CalleeEdges, useCallerEdgesForContextInfo()
516 ? CallerEdges
517 : std::vector<std::shared_ptr<ContextEdge>>());
518 for (const auto &Edge : Edges) {
519 AllocType |= Edge->AllocTypes;
520 // Bail early if alloc type reached both, no further refinement.
521 if (AllocType == BothTypes)
522 return AllocType;
523 }
524 return AllocType;
525 }
526
527 // The context ids set for this node is empty if its edge context ids are
528 // also all empty.
529 bool emptyContextIds() const {
531 CalleeEdges, useCallerEdgesForContextInfo()
532 ? CallerEdges
533 : std::vector<std::shared_ptr<ContextEdge>>());
534 for (const auto &Edge : Edges) {
535 if (!Edge->getContextIds().empty())
536 return false;
537 }
538 return true;
539 }
540
541 // Whether the given context id is among this node's context ids.
542 bool hasContextId(uint32_t Id) const {
544 CalleeEdges, useCallerEdgesForContextInfo()
545 ? CallerEdges
546 : std::vector<std::shared_ptr<ContextEdge>>());
547 for (const auto &Edge : Edges) {
548 if (Edge->getContextIds().contains(Id))
549 return true;
550 }
551 return false;
552 }
553
554 // List of clones of this ContextNode, initially empty.
555 std::vector<ContextNode *> Clones;
556
557 // If a clone, points to the original uncloned node.
558 ContextNode *CloneOf = nullptr;
559
560 ContextNode(bool IsAllocation) : IsAllocation(IsAllocation), Call() {}
561
562 ContextNode(bool IsAllocation, CallInfo C)
563 : IsAllocation(IsAllocation), Call(C) {}
564
565 void addClone(ContextNode *Clone) {
566 if (CloneOf) {
567 CloneOf->Clones.push_back(Clone);
568 Clone->CloneOf = CloneOf;
569 } else {
570 Clones.push_back(Clone);
571 assert(!Clone->CloneOf);
572 Clone->CloneOf = this;
573 }
574 }
575
576 ContextNode *getOrigNode() {
577 if (!CloneOf)
578 return this;
579 return CloneOf;
580 }
581
582 const ContextNode *getOrigNode() const {
583 if (!CloneOf)
584 return this;
585 return CloneOf;
586 }
587
588 void addOrUpdateCallerEdge(ContextNode *Caller, AllocationType AllocType,
589 unsigned int ContextId);
590
591 ContextEdge *findEdgeFromCallee(const ContextNode *Callee);
592 ContextEdge *findEdgeFromCaller(const ContextNode *Caller);
593 void eraseCalleeEdge(const ContextEdge *Edge);
594 void eraseCallerEdge(const ContextEdge *Edge);
595
596 void setCall(CallInfo C) { Call = std::move(C); }
597
598 bool hasCall() const { return (bool)Call.call(); }
599
600 void printCall(raw_ostream &OS) const { Call.print(OS); }
601
602 // True if this node was effectively removed from the graph, in which case
603 // it should have an allocation type of None and empty context ids.
604 bool isRemoved() const {
605 // Typically if the callee edges are empty either the caller edges are
606 // also empty, or this is an allocation (leaf node). However, if we are
607 // allowing recursive callsites and contexts this will be violated for
608 // incompletely cloned recursive cycles.
610 (AllocTypes == (uint8_t)AllocationType::None) ==
611 emptyContextIds());
612 return AllocTypes == (uint8_t)AllocationType::None;
613 }
614
615 void dump() const;
616 void print(raw_ostream &OS) const;
617
618 friend raw_ostream &operator<<(raw_ostream &OS, const ContextNode &Node) {
619 Node.print(OS);
620 return OS;
621 }
622 };
623
624 /// Edge in the Callsite Context Graph from a ContextNode N to a caller or
625 /// callee.
626 struct ContextEdge {
627 ContextNode *Callee;
628 ContextNode *Caller;
629
630 // This will be formed by ORing together the AllocationType enum values
631 // for contexts including this edge.
632 uint8_t AllocTypes = 0;
633
634 // Set just before initiating cloning when cloning of recursive contexts is
635 // enabled. Used to defer cloning of backedges until we have done cloning of
636 // the callee node for non-backedge caller edges. This exposes cloning
637 // opportunities through the backedge of the cycle.
638 // TODO: Note that this is not updated during cloning, and it is unclear
639 // whether that would be needed.
640 bool IsBackedge = false;
641
642 // The set of IDs for contexts including this edge.
643 DenseSet<uint32_t> ContextIds;
644
645 ContextEdge(ContextNode *Callee, ContextNode *Caller, uint8_t AllocType,
646 DenseSet<uint32_t> ContextIds)
647 : Callee(Callee), Caller(Caller), AllocTypes(AllocType),
648 ContextIds(std::move(ContextIds)) {}
649
650 DenseSet<uint32_t> &getContextIds() { return ContextIds; }
651
652 // Helper to clear the fields of this edge when we are removing it from the
653 // graph.
654 inline void clear() {
655 ContextIds.clear();
656 AllocTypes = (uint8_t)AllocationType::None;
657 Caller = nullptr;
658 Callee = nullptr;
659 }
660
661 // Check if edge was removed from the graph. This is useful while iterating
662 // over a copy of edge lists when performing operations that mutate the
663 // graph in ways that might remove one of the edges.
664 inline bool isRemoved() const {
665 if (Callee || Caller)
666 return false;
667 // Any edges that have been removed from the graph but are still in a
668 // shared_ptr somewhere should have all fields null'ed out by clear()
669 // above.
670 assert(AllocTypes == (uint8_t)AllocationType::None);
671 assert(ContextIds.empty());
672 return true;
673 }
674
675 void dump() const;
676 void print(raw_ostream &OS) const;
677
678 friend raw_ostream &operator<<(raw_ostream &OS, const ContextEdge &Edge) {
679 Edge.print(OS);
680 return OS;
681 }
682 };
683
684 /// Helpers to remove edges that have allocation type None (due to not
685 /// carrying any context ids) after transformations.
686 void removeNoneTypeCalleeEdges(ContextNode *Node);
687 void removeNoneTypeCallerEdges(ContextNode *Node);
688 void
689 recursivelyRemoveNoneTypeCalleeEdges(ContextNode *Node,
690 DenseSet<const ContextNode *> &Visited);
691
692protected:
693 /// Get the list of context nodes for the stack ids in the given callsite
694 /// context, stopping at the first stack id that does not have a node.
695 template <class NodeT, class IteratorT>
696 std::vector<ContextNode *>
697 getStackNodesForCallsite(CallStack<NodeT, IteratorT> &CallsiteContext);
698
699 /// Adds nodes for the given allocation and any stack ids on its memprof MIB
700 /// metadata (or summary).
701 ContextNode *addAllocNode(CallInfo Call, const FuncTy *F);
702
703 /// Adds nodes for the given MIB stack ids.
704 template <class NodeT, class IteratorT>
705 void addStackNodesForMIB(
706 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
707 CallStack<NodeT, IteratorT> &CallsiteContext, AllocationType AllocType,
708 ArrayRef<ContextTotalSize> ContextSizeInfo,
709 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold);
710
711 /// Matches all callsite metadata (or summary) to the nodes created for
712 /// allocation memprof MIB metadata, synthesizing new nodes to reflect any
713 /// inlining performed on those callsite instructions.
714 void updateStackNodes();
715
716 /// Optionally fixup edges for the N largest cold contexts to better enable
717 /// cloning. This is particularly helpful if the context includes recursion
718 /// as well as inlining, resulting in a single stack node for multiple stack
719 /// ids in the context. With recursion it is particularly difficult to get the
720 /// edge updates correct as in the general case we have lost the original
721 /// stack id ordering for the context. Do more expensive fixup for the largest
722 /// contexts, controlled by MemProfTopNImportant and MemProfFixupImportant.
723 void fixupImportantContexts();
724
725 /// Update graph to conservatively handle any callsite stack nodes that target
726 /// multiple different callee target functions.
727 void handleCallsitesWithMultipleTargets();
728
729 /// Mark backedges via the standard DFS based backedge algorithm.
730 void markBackedges();
731
732 /// Merge clones generated during cloning for different allocations but that
733 /// are called by the same caller node, to ensure proper function assignment.
734 void mergeClones();
735
736 // Try to partition calls on the given node (already placed into the AllCalls
737 // array) by callee function, creating new copies of Node as needed to hold
738 // calls with different callees, and moving the callee edges appropriately.
739 // Returns true if partitioning was successful.
740 bool partitionCallsByCallee(
741 ContextNode *Node, ArrayRef<CallInfo> AllCalls,
742 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode);
743
744 /// Save lists of calls with MemProf metadata in each function, for faster
745 /// iteration.
746 MapVector<FuncTy *, std::vector<CallInfo>> FuncToCallsWithMetadata;
747
748 /// Map from callsite node to the enclosing caller function.
749 std::map<const ContextNode *, const FuncTy *> NodeToCallingFunc;
750
751 const FuncTy *getCallingFunc(const ContextNode *N) const {
752 auto It = NodeToCallingFunc.find(N);
753 return It != NodeToCallingFunc.end() ? It->second : nullptr;
754 }
755
756 /// Functions that are referenced (called directly, or address-taken) in the
757 /// module or summary index. Only populated, at the start of reporting, when
758 /// MemProfReportHintedSizesDetail is enabled; used to distinguish allocation
759 /// functions with no references at all from those whose callers simply did
760 /// not match the profile.
761 DenseSet<const FuncTy *> FunctionsWithCallers;
762
763 // When exporting to dot, and an allocation id is specified, contains the
764 // context ids on that allocation.
765 DenseSet<uint32_t> DotAllocContextIds;
766
767private:
768 using EdgeIter = typename std::vector<std::shared_ptr<ContextEdge>>::iterator;
769
770 // Structure to keep track of information for each call as we are matching
771 // non-allocation callsites onto context nodes created from the allocation
772 // call metadata / summary contexts.
773 struct CallContextInfo {
774 // The callsite we're trying to match.
775 CallTy Call;
776 // The context nodes for the callsite's stack ids that have one, saved to
777 // avoid repeatedly looking them up. The stack ids are available via the
778 // nodes' OrigStackOrAllocId. Since each stack id has its own node, and the
779 // stack id to node map is not modified while matching calls, two calls
780 // have the same stack ids iff they have the same nodes.
781 std::vector<ContextNode *> StackNodes;
782 // The function containing this callsite.
783 const FuncTy *Func;
784 // Initially empty, if needed this will be updated to contain the context
785 // ids for use in a new context node created for this callsite.
786 DenseSet<uint32_t> ContextIds;
787 };
788
789 /// Helper to remove edge from graph, updating edge iterator if it is provided
790 /// (in which case CalleeIter indicates which edge list is being iterated).
791 /// This will also perform the necessary clearing of the ContextEdge members
792 /// to enable later checking if the edge has been removed (since we may have
793 /// other copies of the shared_ptr in existence, and in fact rely on this to
794 /// enable removal while iterating over a copy of a node's edge list).
795 void removeEdgeFromGraph(ContextEdge *Edge, EdgeIter *EI = nullptr,
796 bool CalleeIter = true);
797
798 /// Assigns the given Node to calls at or inlined into the location with
799 /// the Node's stack id, after post order traversing and processing its
800 /// caller nodes. Uses the call information recorded in the given
801 /// StackIdToMatchingCalls map, and creates new nodes for inlined sequences
802 /// as needed. Called by updateStackNodes which sets up the given
803 /// StackIdToMatchingCalls map.
804 void assignStackNodesPostOrder(
805 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
806 DenseMap<uint64_t, std::vector<CallContextInfo>> &StackIdToMatchingCalls,
807 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
808 const DenseSet<uint32_t> &ImportantContextIds);
809
810 /// Duplicates the given set of context ids, updating the provided
811 /// map from each original id with the newly generated context ids,
812 /// and returning the new duplicated id set.
813 DenseSet<uint32_t> duplicateContextIds(
814 const DenseSet<uint32_t> &StackSequenceContextIds,
815 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds);
816
817 /// Propagates all duplicated context ids across the graph.
818 void propagateDuplicateContextIds(
819 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds);
820
821 /// Connect the NewNode to OrigNode's callees if TowardsCallee is true,
822 /// else to its callers. Also updates OrigNode's edges to remove any context
823 /// ids moved to the newly created edge.
824 void connectNewNode(ContextNode *NewNode, ContextNode *OrigNode,
825 bool TowardsCallee, const DenseSet<uint32_t> &ContextIds);
826
827 /// Get the stack id corresponding to the given Id or Index (for IR this will
828 /// return itself, for a summary index this will return the id recorded in the
829 /// index for that stack id index value).
830 uint64_t getStackId(uint64_t IdOrIndex) const {
831 return static_cast<const DerivedCCG *>(this)->getStackId(IdOrIndex);
832 }
833
834 /// Returns true if the given call targets the callee of the given edge, or if
835 /// we were able to identify the call chain through intermediate tail calls.
836 /// In the latter case new context nodes are added to the graph for the
837 /// identified tail calls, and their synthesized nodes are added to
838 /// TailCallToContextNodeMap. The EdgeIter is updated in the latter case for
839 /// the updated edges and to prepare it for an increment in the caller.
840 bool
841 calleesMatch(CallTy Call, EdgeIter &EI,
842 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap);
843
844 // Return the callee function of the given call, or nullptr if it can't be
845 // determined
846 const FuncTy *getCalleeFunc(CallTy Call) {
847 return static_cast<DerivedCCG *>(this)->getCalleeFunc(Call);
848 }
849
850 /// Returns true if the given call targets the given function, or if we were
851 /// able to identify the call chain through intermediate tail calls (in which
852 /// case FoundCalleeChain will be populated).
853 bool calleeMatchesFunc(
854 CallTy Call, const FuncTy *Func, const FuncTy *CallerFunc,
855 std::vector<std::pair<CallTy, FuncTy *>> &FoundCalleeChain) {
856 return static_cast<DerivedCCG *>(this)->calleeMatchesFunc(
857 Call, Func, CallerFunc, FoundCalleeChain);
858 }
859
860 /// Returns true if both call instructions have the same callee.
861 bool sameCallee(CallTy Call1, CallTy Call2) {
862 return static_cast<DerivedCCG *>(this)->sameCallee(Call1, Call2);
863 }
864
865 /// Get the list of context nodes for the stack ids in the given callsite's
866 /// context, stopping at the first stack id that does not have a node.
867 std::vector<ContextNode *> getStackNodesForCall(CallTy Call) {
868 return static_cast<DerivedCCG *>(this)->getStackNodesForCall(Call);
869 }
870
871 /// Get the last stack id in the context for callsite.
872 uint64_t getLastStackId(CallTy Call) {
873 return static_cast<DerivedCCG *>(this)->getLastStackId(Call);
874 }
875
876 /// Update the allocation call to record type of allocated memory.
877 void updateAllocationCall(CallInfo &Call, AllocationType AllocType) {
878 if (AllocType == AllocationType::Cold)
879 AllocTypeCold++;
880 else if (isAmbiguousAllocType((uint8_t)AllocType))
881 AllocTypeAmbiguous++;
882 else
883 AllocTypeNotCold++;
884 static_cast<DerivedCCG *>(this)->updateAllocationCall(Call, AllocType);
885 }
886
887 /// Get the AllocationType assigned to the given allocation instruction clone.
888 AllocationType getAllocationCallType(const CallInfo &Call) const {
889 return static_cast<const DerivedCCG *>(this)->getAllocationCallType(Call);
890 }
891
892 /// Update non-allocation call to invoke (possibly cloned) function
893 /// CalleeFunc.
894 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc) {
895 static_cast<DerivedCCG *>(this)->updateCall(CallerCall, CalleeFunc);
896 }
897
898 /// Clone the given function for the given callsite, recording mapping of all
899 /// of the functions tracked calls to their new versions in the CallMap.
900 /// Assigns new clones to clone number CloneNo.
901 FuncInfo cloneFunctionForCallsite(
902 FuncInfo &Func, CallInfo &Call, DenseMap<CallInfo, CallInfo> &CallMap,
903 std::vector<CallInfo> &CallsWithMetadataInFunc, unsigned CloneNo) {
904 return static_cast<DerivedCCG *>(this)->cloneFunctionForCallsite(
905 Func, Call, CallMap, CallsWithMetadataInFunc, CloneNo);
906 }
907
908 /// Gets a label to use in the dot graph for the given call clone in the given
909 /// function.
910 std::string getLabel(const FuncTy *Func, const CallTy Call,
911 unsigned CloneNo) const {
912 return static_cast<const DerivedCCG *>(this)->getLabel(Func, Call, CloneNo);
913 }
914
915 /// Gets the function name (with optional clone suffix) for reporting.
916 std::string getFuncName(const FuncTy *Func, unsigned CloneNo = 0) const {
917 return static_cast<const DerivedCCG *>(this)->getFuncName(Func, CloneNo);
918 }
919
920 /// Returns true if the given function was marked dead by ThinLTO dead symbol
921 /// analysis.
922 bool isFuncDead(const FuncTy *Func) const {
923 return static_cast<const DerivedCCG *>(this)->isFuncDead(Func);
924 }
925
926 /// Populates FunctionsWithCallers (MemProfReportHintedSizesDetail only).
927 void populateFunctionsWithCallers() {
928 static_cast<DerivedCCG *>(this)->populateFunctionsWithCallers();
929 }
930
931 /// Records, before identifyClones(), the chain of (uncloned) nodes of every
932 /// context and how far it matched (MemProfReportHintedSizesDetail only).
933 void capturePreCloningContextInfo();
934
935 /// Formats the detail suffix for the report line of context Id, whose
936 /// (possibly cloned) allocation node is Node (MemProfReportHintedSizesDetail
937 /// only). See the option description for the format.
938 std::string formatContextReportSuffix(const ContextNode *Node,
939 uint32_t Id) const;
940
941 // Create and return a new ContextNode.
942 ContextNode *createNewNode(bool IsAllocation, const FuncTy *F = nullptr,
943 CallInfo C = CallInfo()) {
944 NodeOwner.push_back(std::make_unique<ContextNode>(IsAllocation, C));
945 auto *NewNode = NodeOwner.back().get();
946 if (F)
947 NodeToCallingFunc[NewNode] = F;
948 NewNode->NodeId = NodeOwner.size();
949 return NewNode;
950 }
951
952 /// Helpers to find the node corresponding to the given call or stackid.
953 ContextNode *getNodeForInst(const CallInfo &C);
954 ContextNode *getNodeForAlloc(const CallInfo &C);
955 ContextNode *getNodeForStackId(uint64_t StackId);
956
957 /// Computes the alloc type corresponding to the given context ids, by
958 /// unioning their recorded alloc types.
959 uint8_t computeAllocType(DenseSet<uint32_t> &ContextIds) const;
960
961 /// Returns the allocation type of the intersection of the contexts of two
962 /// nodes (based on their provided context id sets), optimized for the case
963 /// when Node1Ids is smaller than Node2Ids.
964 uint8_t intersectAllocTypesImpl(const DenseSet<uint32_t> &Node1Ids,
965 const DenseSet<uint32_t> &Node2Ids) const;
966
967 /// Returns the allocation type of the intersection of the contexts of two
968 /// nodes (based on their provided context id sets).
969 uint8_t intersectAllocTypes(const DenseSet<uint32_t> &Node1Ids,
970 const DenseSet<uint32_t> &Node2Ids) const;
971
972 /// Create a clone of Edge's callee and move Edge to that new callee node,
973 /// performing the necessary context id and allocation type updates.
974 /// If ContextIdsToMove is non-empty, only that subset of Edge's ids are
975 /// moved to an edge to the new callee.
976 ContextNode *
977 moveEdgeToNewCalleeClone(const std::shared_ptr<ContextEdge> &Edge,
978 DenseSet<uint32_t> ContextIdsToMove = {});
979
980 /// Change the callee of Edge to existing callee clone NewCallee, performing
981 /// the necessary context id and allocation type updates.
982 /// If ContextIdsToMove is non-empty, only that subset of Edge's ids are
983 /// moved to an edge to the new callee.
984 void moveEdgeToExistingCalleeClone(const std::shared_ptr<ContextEdge> &Edge,
985 ContextNode *NewCallee,
986 bool NewClone = false,
987 DenseSet<uint32_t> ContextIdsToMove = {});
988
989 /// Change the caller of the edge at the given callee edge iterator to be
990 /// NewCaller, performing the necessary context id and allocation type
991 /// updates. This is similar to the above moveEdgeToExistingCalleeClone, but
992 /// a simplified version of it as we always move the given edge and all of its
993 /// context ids.
994 void moveCalleeEdgeToNewCaller(const std::shared_ptr<ContextEdge> &Edge,
995 ContextNode *NewCaller);
996
997 /// Recursive helper for marking backedges via DFS.
998 void markBackedges(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
999 DenseSet<const ContextNode *> &CurrentStack);
1000
1001 /// Recursive helper for merging clones.
1002 void
1003 mergeClones(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1004 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode);
1005 /// Main worker for merging callee clones for a given node.
1006 void mergeNodeCalleeClones(
1007 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1008 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode);
1009 /// Helper to find other callers of the given set of callee edges that can
1010 /// share the same callee merge node.
1011 void findOtherCallersToShareMerge(
1012 ContextNode *Node, std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
1013 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
1014 DenseSet<ContextNode *> &OtherCallersToShareMerge);
1015
1016 /// Recursively perform cloning on the graph for the given Node and its
1017 /// callers, in order to uniquely identify the allocation behavior of an
1018 /// allocation given its context. The context ids of the allocation being
1019 /// processed are given in AllocContextIds.
1020 void identifyClones(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1021 const DenseSet<uint32_t> &AllocContextIds);
1022
1023 /// Records which clone of a callsite node an implicit caller requires (see
1024 /// assignImplicitCallers). The call to that callsite in a given function
1025 /// clone (the map key below) must call the same callee version as Source.
1026 struct ImplicitSource {
1027 /// The required clone of the callsite node.
1028 const ContextNode *Source;
1029 /// One of the trimmed context ids that made Source required. If Source is
1030 /// later emptied by further cloning, this id is used to find the clone
1031 /// that now carries the trimmed contexts (see resolveImplicitSource).
1032 uint32_t ContextId;
1033 };
1034 /// Map from (original callsite node, function clone number) to the clone of
1035 /// that callsite node that the call in that function clone must follow.
1036 using ImplicitSourceMap =
1037 DenseMap<std::pair<const ContextNode *, unsigned>, ImplicitSource>;
1038
1039 /// Assign the implicit callers of the clones of Node (callsite clones without
1040 /// an edge to any clone of Node which contexts trimmed at Node's frame would
1041 /// have reached) the function clone called by the caller carrying those
1042 /// contexts, and record the clone of Node their calls must follow. See
1043 /// assignFunctions for the maps.
1044 void assignImplicitCallers(
1045 ContextNode *Node, const DenseSet<uint32_t> &TrimmedContextIds,
1046 DenseMap<ContextNode *, FuncInfo> &CallsiteToCalleeFuncCloneMap,
1047 const std::map<FuncInfo, ContextNode *> &FuncCloneToCurNodeCloneMap,
1048 ImplicitSourceMap &ImplicitSources);
1049
1050 /// Returns the clone of Node (the original callsite node) that the implicit
1051 /// source Src refers to: Src.Source unless it has since been emptied, in
1052 /// which case the clone that now carries Src.ContextId (null if none does,
1053 /// which is not expected).
1054 static const ContextNode *resolveImplicitSource(const ContextNode *Node,
1055 const ImplicitSource &Src);
1056
1057 /// Map from each context ID to the AllocationType assigned to that context.
1058 DenseMap<uint32_t, AllocationType> ContextIdToAllocationType;
1059
1060 /// Map from each contextID to the profiled full contexts and their total
1061 /// sizes (there may be more than one due to context trimming),
1062 /// optionally populated when requested (via MemProfReportHintedSizes or
1063 /// MinClonedColdBytePercent).
1064 DenseMap<uint32_t, std::vector<ContextTotalSize>> ContextIdToContextSizeInfos;
1065
1066 /// Identifies the context node created for a stack id when adding the MIB
1067 /// contexts to the graph. This is used to locate the context nodes when
1068 /// trying to assign the corresponding callsites with those stack ids to these
1069 /// nodes.
1070 DenseMap<uint64_t, ContextNode *> StackEntryIdToContextNodeMap;
1071
1072 /// Saves information for the contexts identified as important (the largest
1073 /// cold contexts up to MemProfTopNImportant).
1074 struct ImportantContextInfo {
1075 // The original list of leaf first stack ids corresponding to this context.
1076 std::vector<uint64_t> StackIds;
1077 // Max length of stack ids corresponding to a single stack ContextNode for
1078 // this context (i.e. the max length of a key in StackIdsToNode below).
1079 unsigned MaxLength = 0;
1080 // Mapping of slices of the stack ids to the corresponding ContextNode
1081 // (there can be multiple stack ids due to inlining). Populated when
1082 // updating stack nodes while matching them to the IR or summary.
1083 std::map<std::vector<uint64_t>, ContextNode *> StackIdsToNode;
1084 };
1085
1086 // Map of important full context ids to information about each.
1087 DenseMap<uint32_t, ImportantContextInfo> ImportantContextIdInfo;
1088
1089 // For each important context id found in Node (if any), records the list of
1090 // stack ids (those of the given StackNodes) that corresponded to the given
1091 // callsite Node. There can be more than one in the case of inlining.
1092 void recordStackNode(ArrayRef<ContextNode *> StackNodes, ContextNode *Node,
1093 // We pass in the Node's context ids to avoid the
1094 // overhead of computing them as the caller already has
1095 // them in some cases.
1096 const DenseSet<uint32_t> &NodeContextIds,
1097 const DenseSet<uint32_t> &ImportantContextIds) {
1098 if (!MemProfTopNImportant) {
1099 assert(ImportantContextIds.empty());
1100 return;
1101 }
1102 DenseSet<uint32_t> Ids =
1103 set_intersection(NodeContextIds, ImportantContextIds);
1104 if (Ids.empty())
1105 return;
1106 std::vector<uint64_t> StackIds;
1107 StackIds.reserve(StackNodes.size());
1108 for (const ContextNode *N : StackNodes)
1109 StackIds.push_back(N->OrigStackOrAllocId);
1110 auto Size = StackIds.size();
1111 for (auto Id : Ids) {
1112 auto &Entry = ImportantContextIdInfo[Id];
1113 Entry.StackIdsToNode[StackIds] = Node;
1114 // Keep track of the max to simplify later analysis.
1115 if (Size > Entry.MaxLength)
1116 Entry.MaxLength = Size;
1117 }
1118 }
1119
1120 /// Maps to track the calls to their corresponding nodes in the graph.
1121 MapVector<CallInfo, ContextNode *> AllocationCallToContextNodeMap;
1122 MapVector<CallInfo, ContextNode *> NonAllocationCallToContextNodeMap;
1123
1124 /// Owner of all ContextNode unique_ptrs.
1125 std::vector<std::unique_ptr<ContextNode>> NodeOwner;
1126
1127 /// Perform sanity checks on graph when requested.
1128 void check() const;
1129
1130 /// Keeps track of the last unique context id assigned.
1131 unsigned int LastContextId = 0;
1132
1133 /// Per-context information captured before identifyClones() when
1134 /// MemProfReportHintedSizesDetail is enabled, so that the report can relate
1135 /// the final (cloned) state back to the original context. "Frames" below are
1136 /// CCG nodes, not profile stack frames: a node matched to a call covers all
1137 /// of that call's inlined stack frames, so a chain can be shorter than the
1138 /// profiled stack.
1139 struct PreCloningContextInfo {
1140 // Ordered chain of uncloned ContextNodes for this context ID from the leaf
1141 // allocation node (Chain[0]) up to the outermost node in the CCG for this
1142 // context.
1143 std::vector<const ContextNode *> Chain;
1144 // Index in Chain of the outermost matched callsite node, i.e. the
1145 // outermost node such that it and all nodes below it
1146 // (Chain[1..MaxMatchedFrame]) were matched to a call in the IR/summary
1147 // (hasCall() == true). If the whole context matched, this is the
1148 // context's outermost node (possibly where the context was trimmed);
1149 // otherwise it is the last matched node below the first unmatched one. The
1150 // function containing it (the "outermost matched caller") is where the
1151 // reported post-cloning paths start. 0 if no caller of the allocation
1152 // matched.
1153 unsigned MaxMatchedFrame = 0;
1154 // True if the outermost matched node had caller edges for other contexts,
1155 // i.e. the context was trimmed below callers that other contexts reach.
1156 bool OutermostMatchedNodeHasOtherCallers = false;
1157 // If MaxMatchedFrame + 1 < Chain.size(), why did Chain[MaxMatchedFrame + 1]
1158 // not have a call: it was a recursive cycle node, or its calling function
1159 // was found but the call there did not match the callee (mismatched
1160 // callee); otherwise the caller had no !callsite for this stack id.
1161 bool StoppedAtRecursive = false;
1162 bool StoppedAtMismatchedCallee = false;
1163 // Stack id and (when known) calling function of the first unmatched node.
1164 uint64_t UnmatchedStackId = 0;
1165 const FuncTy *UnmatchedCallingFunc = nullptr;
1166 };
1167 /// Map from context id to its pre-cloning information.
1168 DenseMap<uint32_t, PreCloningContextInfo> PreCloningContextInfoMap;
1169 /// Allocation nodes (uncloned) that had at least one matched caller before
1170 /// cloning.
1171 DenseSet<const ContextNode *> PreCloningAllocHasMatchedCaller;
1172 /// Map from function to the number of function clones assigned to it
1173 /// (including the original), recorded during assignFunctions().
1174 DenseMap<const FuncTy *, unsigned> FuncToNumClones;
1175 /// Map from (original callsite node, clone number of the function clone
1176 /// containing the call) to the clone number of the callee function the call
1177 /// was updated to in assignFunctions(). Used to follow the post-cloning call
1178 /// path from a caller clone down to the allocation clone it reaches.
1179 DenseMap<std::pair<const ContextNode *, unsigned>, unsigned>
1180 OrigNodeAndCloneToCalleeClone;
1181 /// Map from (original allocation node, clone number of the function clone
1182 /// containing the allocation) to the allocation node in that clone, whose
1183 /// call carries the final hint.
1184 DenseMap<std::pair<const ContextNode *, unsigned>, const ContextNode *>
1185 OrigAllocAndCloneToNode;
1186};
1187
1188template <typename DerivedCCG, typename FuncTy, typename CallTy>
1189using ContextNode =
1190 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode;
1191template <typename DerivedCCG, typename FuncTy, typename CallTy>
1192using ContextEdge =
1193 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge;
1194template <typename DerivedCCG, typename FuncTy, typename CallTy>
1195using FuncInfo =
1196 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::FuncInfo;
1197template <typename DerivedCCG, typename FuncTy, typename CallTy>
1198using CallInfo =
1199 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::CallInfo;
1200
1201/// CRTP derived class for graphs built from IR (regular LTO).
1202class ModuleCallsiteContextGraph
1203 : public CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
1204 Instruction *> {
1205public:
1206 ModuleCallsiteContextGraph(
1207 Module &M,
1208 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
1209
1210private:
1211 friend CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
1212 Instruction *>;
1213
1214 uint64_t getStackId(uint64_t IdOrIndex) const;
1215 const Function *getCalleeFunc(Instruction *Call);
1216 bool calleeMatchesFunc(
1217 Instruction *Call, const Function *Func, const Function *CallerFunc,
1218 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain);
1219 bool sameCallee(Instruction *Call1, Instruction *Call2);
1220 bool findProfiledCalleeThroughTailCalls(
1221 const Function *ProfiledCallee, Value *CurCallee, unsigned Depth,
1222 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
1223 bool &FoundMultipleCalleeChains);
1224 uint64_t getLastStackId(Instruction *Call);
1225 std::vector<ContextNode *> getStackNodesForCall(Instruction *Call);
1226 void updateAllocationCall(CallInfo &Call, AllocationType AllocType);
1227 AllocationType getAllocationCallType(const CallInfo &Call) const;
1228 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1229 CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
1230 Instruction *>::FuncInfo
1231 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &Call,
1232 DenseMap<CallInfo, CallInfo> &CallMap,
1233 std::vector<CallInfo> &CallsWithMetadataInFunc,
1234 unsigned CloneNo);
1235 std::string getLabel(const Function *Func, const Instruction *Call,
1236 unsigned CloneNo) const;
1237 std::string getFuncName(const Function *Func, unsigned CloneNo = 0) const;
1238 bool isFuncDead(const Function *Func) const { return false; }
1239 void populateFunctionsWithCallers();
1240
1241 const Module &Mod;
1242 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
1243};
1244
1245/// Represents a call in the summary index graph, which can either be an
1246/// allocation or an interior callsite node in an allocation's context.
1247/// Holds a pointer to the corresponding data structure in the index.
1248struct IndexCall : public PointerUnion<CallsiteInfo *, AllocInfo *> {
1249 IndexCall() : PointerUnion() {}
1250 IndexCall(std::nullptr_t) : IndexCall() {}
1251 IndexCall(CallsiteInfo *StackNode) : PointerUnion(StackNode) {}
1252 IndexCall(AllocInfo *AllocNode) : PointerUnion(AllocNode) {}
1253 IndexCall(PointerUnion PT) : PointerUnion(PT) {}
1254
1255 IndexCall *operator->() { return this; }
1256
1257 void print(raw_ostream &OS) const {
1258 PointerUnion<CallsiteInfo *, AllocInfo *> Base = *this;
1260 OS << *AI;
1261 } else {
1263 assert(CI);
1264 OS << *CI;
1265 }
1266 }
1267};
1268} // namespace
1269
1270namespace llvm {
1271template <> struct simplify_type<IndexCall> {
1273 static SimpleType getSimplifiedValue(IndexCall &Val) { return Val; }
1274};
1275template <> struct simplify_type<const IndexCall> {
1277 static SimpleType getSimplifiedValue(const IndexCall &Val) { return Val; }
1278};
1279} // namespace llvm
1280
1281namespace {
1282/// CRTP derived class for graphs built from summary index (ThinLTO).
1283class IndexCallsiteContextGraph
1284 : public CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1285 IndexCall> {
1286public:
1287 IndexCallsiteContextGraph(
1288 ModuleSummaryIndex &Index,
1289 llvm::function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1290 isPrevailing);
1291
1292 ~IndexCallsiteContextGraph() {
1293 // Now that we are done with the graph it is safe to add the new
1294 // CallsiteInfo structs to the function summary vectors. The graph nodes
1295 // point into locations within these vectors, so we don't want to add them
1296 // any earlier.
1297 for (auto &I : FunctionCalleesToSynthesizedCallsiteInfos) {
1298 auto *FS = I.first;
1299 for (auto &Callsite : I.second)
1300 FS->addCallsite(std::move(*Callsite.second));
1301 }
1302 }
1303
1304private:
1305 friend CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1306 IndexCall>;
1307
1308 uint64_t getStackId(uint64_t IdOrIndex) const;
1309 const FunctionSummary *getCalleeFunc(IndexCall &Call);
1310 bool calleeMatchesFunc(
1311 IndexCall &Call, const FunctionSummary *Func,
1312 const FunctionSummary *CallerFunc,
1313 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain);
1314 bool sameCallee(IndexCall &Call1, IndexCall &Call2);
1315 bool findProfiledCalleeThroughTailCalls(
1316 ValueInfo ProfiledCallee, ValueInfo CurCallee, unsigned Depth,
1317 std::vector<std::pair<ValueInfo, FunctionSummary *>> &FoundCalleeChain,
1318 bool &FoundMultipleCalleeChains);
1319 uint64_t getLastStackId(IndexCall &Call);
1320 std::vector<ContextNode *> getStackNodesForCall(IndexCall &Call);
1321 void updateAllocationCall(CallInfo &Call, AllocationType AllocType);
1322 AllocationType getAllocationCallType(const CallInfo &Call) const;
1323 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1324 CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1325 IndexCall>::FuncInfo
1326 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &Call,
1327 DenseMap<CallInfo, CallInfo> &CallMap,
1328 std::vector<CallInfo> &CallsWithMetadataInFunc,
1329 unsigned CloneNo);
1330 std::string getLabel(const FunctionSummary *Func, const IndexCall &Call,
1331 unsigned CloneNo) const;
1332 std::string getFuncName(const FunctionSummary *Func,
1333 unsigned CloneNo = 0) const;
1334 bool isFuncDead(const FunctionSummary *Func) const;
1335 void populateFunctionsWithCallers();
1336 DenseSet<GlobalValue::GUID> findAliaseeGUIDsPrevailingInDifferentModule();
1337
1338 // Saves mapping from function summaries containing memprof records back to
1339 // its VI, for use in checking and debugging.
1340 std::map<const FunctionSummary *, ValueInfo> FSToVIMap;
1341
1342 const ModuleSummaryIndex &Index;
1343 llvm::function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1344 isPrevailing;
1345
1346 // Saves/owns the callsite info structures synthesized for missing tail call
1347 // frames that we discover while building the graph.
1348 // It maps from the summary of the function making the tail call, to a map
1349 // of callee ValueInfo to corresponding synthesized callsite info.
1350 DenseMap<FunctionSummary *,
1351 std::map<ValueInfo, std::unique_ptr<CallsiteInfo>>>
1352 FunctionCalleesToSynthesizedCallsiteInfos;
1353};
1354} // namespace
1355
1356template <>
1357struct llvm::DenseMapInfo<CallsiteContextGraph<
1358 ModuleCallsiteContextGraph, Function, Instruction *>::CallInfo>
1360template <>
1361struct llvm::DenseMapInfo<CallsiteContextGraph<
1362 IndexCallsiteContextGraph, FunctionSummary, IndexCall>::CallInfo>
1363 : public DenseMapInfo<std::pair<IndexCall, unsigned>> {};
1364template <>
1365struct llvm::DenseMapInfo<IndexCall>
1366 : public DenseMapInfo<PointerUnion<CallsiteInfo *, AllocInfo *>> {};
1367
1368namespace {
1369
1370// Map the uint8_t alloc types (which may contain NotCold|Cold) to the alloc
1371// type we should actually use on the corresponding allocation.
1372// If we can't clone a node that has NotCold+Cold alloc type, we will fall
1373// back to using NotCold. So don't bother cloning to distinguish NotCold+Cold
1374// from NotCold.
1375AllocationType allocTypeToUse(uint8_t AllocTypes) {
1376 assert(AllocTypes != (uint8_t)AllocationType::None);
1377 if (AllocTypes ==
1380 else
1381 return (AllocationType)AllocTypes;
1382}
1383
1384// Helper to check if the alloc types for all edges recorded in the
1385// InAllocTypes vector match the alloc types for all edges in the Edges
1386// vector.
1387template <typename DerivedCCG, typename FuncTy, typename CallTy>
1388bool allocTypesMatch(
1389 const std::vector<uint8_t> &InAllocTypes,
1390 const std::vector<std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>>
1391 &Edges) {
1392 // This should be called only when the InAllocTypes vector was computed for
1393 // this set of Edges. Make sure the sizes are the same.
1394 assert(InAllocTypes.size() == Edges.size());
1395 return std::equal(
1396 InAllocTypes.begin(), InAllocTypes.end(), Edges.begin(), Edges.end(),
1397 [](const uint8_t &l,
1398 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &r) {
1399 // Can share if one of the edges is None type - don't
1400 // care about the type along that edge as it doesn't
1401 // exist for those context ids.
1402 if (l == (uint8_t)AllocationType::None ||
1403 r->AllocTypes == (uint8_t)AllocationType::None)
1404 return true;
1405 return allocTypeToUse(l) == allocTypeToUse(r->AllocTypes);
1406 });
1407}
1408
1409// Helper to check if the alloc types for all edges recorded in the
1410// InAllocTypes vector match the alloc types for callee edges in the given
1411// clone. Because the InAllocTypes were computed from the original node's callee
1412// edges, and other cloning could have happened after this clone was created, we
1413// need to find the matching clone callee edge, which may or may not exist.
1414template <typename DerivedCCG, typename FuncTy, typename CallTy>
1415bool allocTypesMatchClone(
1416 const std::vector<uint8_t> &InAllocTypes,
1417 const ContextNode<DerivedCCG, FuncTy, CallTy> *Clone) {
1418 const ContextNode<DerivedCCG, FuncTy, CallTy> *Node = Clone->CloneOf;
1419 assert(Node);
1420 // InAllocTypes should have been computed for the original node's callee
1421 // edges.
1422 assert(InAllocTypes.size() == Node->CalleeEdges.size());
1423 // First create a map of the clone callee edge callees to the edge alloc type.
1425 EdgeCalleeMap;
1426 for (const auto &E : Clone->CalleeEdges) {
1427 assert(!EdgeCalleeMap.contains(E->Callee));
1428 EdgeCalleeMap[E->Callee] = E->AllocTypes;
1429 }
1430 // Next, walk the original node's callees, and look for the corresponding
1431 // clone edge to that callee.
1432 for (unsigned I = 0; I < Node->CalleeEdges.size(); I++) {
1433 auto Iter = EdgeCalleeMap.find(Node->CalleeEdges[I]->Callee);
1434 // Not found is ok, we will simply add an edge if we use this clone.
1435 if (Iter == EdgeCalleeMap.end())
1436 continue;
1437 // Can share if one of the edges is None type - don't
1438 // care about the type along that edge as it doesn't
1439 // exist for those context ids.
1440 if (InAllocTypes[I] == (uint8_t)AllocationType::None ||
1441 Iter->second == (uint8_t)AllocationType::None)
1442 continue;
1443 if (allocTypeToUse(Iter->second) != allocTypeToUse(InAllocTypes[I]))
1444 return false;
1445 }
1446 return true;
1447}
1448
1449} // end anonymous namespace
1450
1451template <typename DerivedCCG, typename FuncTy, typename CallTy>
1452typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1453CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForInst(
1454 const CallInfo &C) {
1455 ContextNode *Node = getNodeForAlloc(C);
1456 if (Node)
1457 return Node;
1458
1459 return NonAllocationCallToContextNodeMap.lookup(C);
1460}
1461
1462template <typename DerivedCCG, typename FuncTy, typename CallTy>
1463typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1464CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForAlloc(
1465 const CallInfo &C) {
1466 return AllocationCallToContextNodeMap.lookup(C);
1467}
1468
1469template <typename DerivedCCG, typename FuncTy, typename CallTy>
1470typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1471CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForStackId(
1472 uint64_t StackId) {
1473 auto StackEntryNode = StackEntryIdToContextNodeMap.find(StackId);
1474 if (StackEntryNode != StackEntryIdToContextNodeMap.end())
1475 return StackEntryNode->second;
1476 return nullptr;
1477}
1478
1479template <typename DerivedCCG, typename FuncTy, typename CallTy>
1480void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1481 addOrUpdateCallerEdge(ContextNode *Caller, AllocationType AllocType,
1482 unsigned int ContextId) {
1483 for (auto &Edge : CallerEdges) {
1484 if (Edge->Caller == Caller) {
1485 Edge->AllocTypes |= (uint8_t)AllocType;
1486 Edge->getContextIds().insert(ContextId);
1487 return;
1488 }
1489 }
1490 std::shared_ptr<ContextEdge> Edge = std::make_shared<ContextEdge>(
1491 this, Caller, (uint8_t)AllocType, DenseSet<uint32_t>({ContextId}));
1492 CallerEdges.push_back(Edge);
1493 Caller->CalleeEdges.push_back(Edge);
1494}
1495
1496template <typename DerivedCCG, typename FuncTy, typename CallTy>
1497void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::removeEdgeFromGraph(
1498 ContextEdge *Edge, EdgeIter *EI, bool CalleeIter) {
1499 assert(!EI || (*EI)->get() == Edge);
1500 assert(!Edge->isRemoved());
1501 // Save the Caller and Callee pointers so we can erase Edge from their edge
1502 // lists after clearing Edge below. We do the clearing first in case it is
1503 // destructed after removing from the edge lists (if those were the last
1504 // shared_ptr references to Edge).
1505 auto *Callee = Edge->Callee;
1506 auto *Caller = Edge->Caller;
1507
1508 // Make sure the edge fields are cleared out so we can properly detect
1509 // removed edges if Edge is not destructed because there is still a shared_ptr
1510 // reference.
1511 Edge->clear();
1512
1513#ifndef NDEBUG
1514 auto CalleeCallerCount = Callee->CallerEdges.size();
1515 auto CallerCalleeCount = Caller->CalleeEdges.size();
1516#endif
1517 if (!EI) {
1518 Callee->eraseCallerEdge(Edge);
1519 Caller->eraseCalleeEdge(Edge);
1520 } else if (CalleeIter) {
1521 Callee->eraseCallerEdge(Edge);
1522 *EI = Caller->CalleeEdges.erase(*EI);
1523 } else {
1524 Caller->eraseCalleeEdge(Edge);
1525 *EI = Callee->CallerEdges.erase(*EI);
1526 }
1527 assert(Callee->CallerEdges.size() < CalleeCallerCount);
1528 assert(Caller->CalleeEdges.size() < CallerCalleeCount);
1529}
1530
1531template <typename DerivedCCG, typename FuncTy, typename CallTy>
1532void CallsiteContextGraph<
1533 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCalleeEdges(ContextNode *Node) {
1534 for (auto EI = Node->CalleeEdges.begin(); EI != Node->CalleeEdges.end();) {
1535 auto Edge = *EI;
1536 if (Edge->AllocTypes == (uint8_t)AllocationType::None) {
1537 assert(Edge->ContextIds.empty());
1538 removeEdgeFromGraph(Edge.get(), &EI, /*CalleeIter=*/true);
1539 } else
1540 ++EI;
1541 }
1542}
1543
1544template <typename DerivedCCG, typename FuncTy, typename CallTy>
1545void CallsiteContextGraph<
1546 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCallerEdges(ContextNode *Node) {
1547 for (auto EI = Node->CallerEdges.begin(); EI != Node->CallerEdges.end();) {
1548 auto Edge = *EI;
1549 if (Edge->AllocTypes == (uint8_t)AllocationType::None) {
1550 assert(Edge->ContextIds.empty());
1551 Edge->Caller->eraseCalleeEdge(Edge.get());
1552 EI = Node->CallerEdges.erase(EI);
1553 } else
1554 ++EI;
1555 }
1556}
1557
1558template <typename DerivedCCG, typename FuncTy, typename CallTy>
1559typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1560CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1561 findEdgeFromCallee(const ContextNode *Callee) {
1562 for (const auto &Edge : CalleeEdges)
1563 if (Edge->Callee == Callee)
1564 return Edge.get();
1565 return nullptr;
1566}
1567
1568template <typename DerivedCCG, typename FuncTy, typename CallTy>
1569typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1570CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1571 findEdgeFromCaller(const ContextNode *Caller) {
1572 for (const auto &Edge : CallerEdges)
1573 if (Edge->Caller == Caller)
1574 return Edge.get();
1575 return nullptr;
1576}
1577
1578template <typename DerivedCCG, typename FuncTy, typename CallTy>
1579void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1580 eraseCalleeEdge(const ContextEdge *Edge) {
1581 auto EI = llvm::find_if(
1582 CalleeEdges, [Edge](const std::shared_ptr<ContextEdge> &CalleeEdge) {
1583 return CalleeEdge.get() == Edge;
1584 });
1585 assert(EI != CalleeEdges.end());
1586 CalleeEdges.erase(EI);
1587}
1588
1589template <typename DerivedCCG, typename FuncTy, typename CallTy>
1590void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1591 eraseCallerEdge(const ContextEdge *Edge) {
1592 auto EI = llvm::find_if(
1593 CallerEdges, [Edge](const std::shared_ptr<ContextEdge> &CallerEdge) {
1594 return CallerEdge.get() == Edge;
1595 });
1596 assert(EI != CallerEdges.end());
1597 CallerEdges.erase(EI);
1598}
1599
1600template <typename DerivedCCG, typename FuncTy, typename CallTy>
1601uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::computeAllocType(
1602 DenseSet<uint32_t> &ContextIds) const {
1603 uint8_t BothTypes =
1604 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1605 uint8_t AllocType = (uint8_t)AllocationType::None;
1606 for (auto Id : ContextIds) {
1607 AllocType |= (uint8_t)ContextIdToAllocationType.at(Id);
1608 // Bail early if alloc type reached both, no further refinement.
1609 if (AllocType == BothTypes)
1610 return AllocType;
1611 }
1612 return AllocType;
1613}
1614
1615template <typename DerivedCCG, typename FuncTy, typename CallTy>
1616uint8_t
1617CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypesImpl(
1618 const DenseSet<uint32_t> &Node1Ids,
1619 const DenseSet<uint32_t> &Node2Ids) const {
1620 uint8_t BothTypes =
1621 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1622 uint8_t AllocType = (uint8_t)AllocationType::None;
1623 for (auto Id : Node1Ids) {
1624 if (!Node2Ids.count(Id))
1625 continue;
1626 AllocType |= (uint8_t)ContextIdToAllocationType.at(Id);
1627 // Bail early if alloc type reached both, no further refinement.
1628 if (AllocType == BothTypes)
1629 return AllocType;
1630 }
1631 return AllocType;
1632}
1633
1634template <typename DerivedCCG, typename FuncTy, typename CallTy>
1635uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypes(
1636 const DenseSet<uint32_t> &Node1Ids,
1637 const DenseSet<uint32_t> &Node2Ids) const {
1638 if (Node1Ids.size() < Node2Ids.size())
1639 return intersectAllocTypesImpl(Node1Ids, Node2Ids);
1640 else
1641 return intersectAllocTypesImpl(Node2Ids, Node1Ids);
1642}
1643
1644template <typename DerivedCCG, typename FuncTy, typename CallTy>
1645typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1646CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addAllocNode(
1647 CallInfo Call, const FuncTy *F) {
1648 assert(!getNodeForAlloc(Call));
1649 ContextNode *AllocNode = createNewNode(/*IsAllocation=*/true, F, Call);
1650 AllocationCallToContextNodeMap[Call] = AllocNode;
1651 // Use LastContextId as a uniq id for MIB allocation nodes.
1652 AllocNode->OrigStackOrAllocId = LastContextId;
1653 // Alloc type should be updated as we add in the MIBs. We should assert
1654 // afterwards that it is not still None.
1655 AllocNode->AllocTypes = (uint8_t)AllocationType::None;
1656
1657 return AllocNode;
1658}
1659
1660static std::string getAllocTypeString(uint8_t AllocTypes) {
1661 if (!AllocTypes)
1662 return "None";
1663 std::string Str;
1664 if (AllocTypes & (uint8_t)AllocationType::NotCold)
1665 Str += "NotCold";
1666 if (AllocTypes & (uint8_t)AllocationType::Cold)
1667 Str += "Cold";
1668 return Str;
1669}
1670
1671template <typename DerivedCCG, typename FuncTy, typename CallTy>
1672template <class NodeT, class IteratorT>
1673void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addStackNodesForMIB(
1674 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
1675 CallStack<NodeT, IteratorT> &CallsiteContext, AllocationType AllocType,
1676 ArrayRef<ContextTotalSize> ContextSizeInfo,
1677 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold) {
1678 // Treating the hot alloc type as NotCold before the disambiguation for "hot"
1679 // is done.
1680 if (AllocType == AllocationType::Hot)
1681 AllocType = AllocationType::NotCold;
1682
1683 ContextIdToAllocationType[++LastContextId] = AllocType;
1684
1685 bool IsImportant = false;
1686 if (!ContextSizeInfo.empty()) {
1687 auto &Entry = ContextIdToContextSizeInfos[LastContextId];
1688 // If this is a cold allocation, and we are collecting non-zero largest
1689 // contexts, see if this is a candidate.
1690 if (AllocType == AllocationType::Cold && MemProfTopNImportant > 0) {
1691 uint64_t TotalCold = 0;
1692 for (auto &CSI : ContextSizeInfo)
1693 TotalCold += CSI.TotalSize;
1694 // Record this context if either we haven't found the first top-n largest
1695 // yet, or if it is larger than the smallest already recorded.
1696 if (TotalSizeToContextIdTopNCold.size() < MemProfTopNImportant ||
1697 // Since TotalSizeToContextIdTopNCold is a std::map, it is implicitly
1698 // sorted in ascending size of its key which is the size.
1699 TotalCold > TotalSizeToContextIdTopNCold.begin()->first) {
1700 if (TotalSizeToContextIdTopNCold.size() == MemProfTopNImportant) {
1701 // Remove old one and its associated entries.
1702 auto IdToRemove = TotalSizeToContextIdTopNCold.begin()->second;
1703 TotalSizeToContextIdTopNCold.erase(
1704 TotalSizeToContextIdTopNCold.begin());
1705 assert(ImportantContextIdInfo.count(IdToRemove));
1706 ImportantContextIdInfo.erase(IdToRemove);
1707 }
1708 TotalSizeToContextIdTopNCold[TotalCold] = LastContextId;
1709 IsImportant = true;
1710 }
1711 }
1712 Entry.insert(Entry.begin(), ContextSizeInfo.begin(), ContextSizeInfo.end());
1713 }
1714
1715 // Update alloc type and context ids for this MIB.
1716 AllocNode->AllocTypes |= (uint8_t)AllocType;
1717
1718 // Now add or update nodes for each stack id in alloc's context.
1719 // Later when processing the stack ids on non-alloc callsites we will adjust
1720 // for any inlining in the context.
1721 ContextNode *PrevNode = AllocNode;
1722 // Look for recursion (direct recursion should have been collapsed by
1723 // module summary analysis, here we should just be detecting mutual
1724 // recursion). Mark these nodes so we don't try to clone.
1725 SmallSet<uint64_t, 8> StackIdSet;
1726 // Skip any on the allocation call (inlining).
1727 for (auto ContextIter = StackContext.beginAfterSharedPrefix(CallsiteContext);
1728 ContextIter != StackContext.end(); ++ContextIter) {
1729 auto StackId = getStackId(*ContextIter);
1730 if (IsImportant)
1731 ImportantContextIdInfo[LastContextId].StackIds.push_back(StackId);
1732 ContextNode *StackNode = getNodeForStackId(StackId);
1733 if (!StackNode) {
1734 StackNode = createNewNode(/*IsAllocation=*/false);
1735 StackEntryIdToContextNodeMap[StackId] = StackNode;
1736 StackNode->OrigStackOrAllocId = StackId;
1737 }
1738 // Marking a node recursive will prevent its cloning completely, even for
1739 // non-recursive contexts flowing through it.
1741 auto Ins = StackIdSet.insert(StackId);
1742 if (!Ins.second)
1743 StackNode->Recursive = true;
1744 }
1745 StackNode->AllocTypes |= (uint8_t)AllocType;
1746 PrevNode->addOrUpdateCallerEdge(StackNode, AllocType, LastContextId);
1747 PrevNode = StackNode;
1748 }
1749}
1750
1751template <typename DerivedCCG, typename FuncTy, typename CallTy>
1752DenseSet<uint32_t>
1753CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::duplicateContextIds(
1754 const DenseSet<uint32_t> &StackSequenceContextIds,
1755 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds) {
1756 DenseSet<uint32_t> NewContextIds;
1757 for (auto OldId : StackSequenceContextIds) {
1758 NewContextIds.insert(++LastContextId);
1759 OldToNewContextIds[OldId].insert(LastContextId);
1760 assert(ContextIdToAllocationType.count(OldId));
1761 // The new context has the same allocation type and size info as original.
1762 ContextIdToAllocationType[LastContextId] = ContextIdToAllocationType[OldId];
1763 auto CSI = ContextIdToContextSizeInfos.find(OldId);
1764 if (CSI != ContextIdToContextSizeInfos.end())
1765 ContextIdToContextSizeInfos[LastContextId] = CSI->second;
1766 if (DotAllocContextIds.contains(OldId))
1767 DotAllocContextIds.insert(LastContextId);
1768 }
1769 return NewContextIds;
1770}
1771
1772template <typename DerivedCCG, typename FuncTy, typename CallTy>
1773void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1774 propagateDuplicateContextIds(
1775 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds) {
1776 // Build a set of duplicated context ids corresponding to the input id set.
1777 auto GetNewIds = [&OldToNewContextIds](const DenseSet<uint32_t> &ContextIds) {
1778 DenseSet<uint32_t> NewIds;
1779 for (auto Id : ContextIds)
1780 if (auto NewId = OldToNewContextIds.find(Id);
1781 NewId != OldToNewContextIds.end())
1782 NewIds.insert_range(NewId->second);
1783 return NewIds;
1784 };
1785
1786 // Recursively update context ids sets along caller edges.
1787 auto UpdateCallers = [&](ContextNode *Node,
1788 DenseSet<const ContextEdge *> &Visited,
1789 auto &&UpdateCallers) -> void {
1790 for (const auto &Edge : Node->CallerEdges) {
1791 auto Inserted = Visited.insert(Edge.get());
1792 if (!Inserted.second)
1793 continue;
1794 ContextNode *NextNode = Edge->Caller;
1795 DenseSet<uint32_t> NewIdsToAdd = GetNewIds(Edge->getContextIds());
1796 // Only need to recursively iterate to NextNode via this caller edge if
1797 // it resulted in any added ids to NextNode.
1798 if (!NewIdsToAdd.empty()) {
1799 Edge->getContextIds().insert_range(NewIdsToAdd);
1800 UpdateCallers(NextNode, Visited, UpdateCallers);
1801 }
1802 }
1803 };
1804
1805 DenseSet<const ContextEdge *> Visited;
1806 for (auto &Entry : AllocationCallToContextNodeMap) {
1807 auto *Node = Entry.second;
1808 UpdateCallers(Node, Visited, UpdateCallers);
1809 }
1810}
1811
1812template <typename DerivedCCG, typename FuncTy, typename CallTy>
1813void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::connectNewNode(
1814 ContextNode *NewNode, ContextNode *OrigNode, bool TowardsCallee,
1815 const DenseSet<uint32_t> &ContextIds) {
1816 auto &OrigEdges =
1817 TowardsCallee ? OrigNode->CalleeEdges : OrigNode->CallerEdges;
1818 // Increment iterator in loop so that we can remove edges as needed.
1819 for (auto EI = OrigEdges.begin(); EI != OrigEdges.end();) {
1820 auto Edge = *EI;
1821 DenseSet<uint32_t> NewEdgeContextIds;
1822 // Remove any matching context ids from Edge, return set that were found and
1823 // removed, these are the new edge's context ids.
1824 set_subtract(Edge->getContextIds(), ContextIds, NewEdgeContextIds);
1825 // If no matching context ids for this edge, skip it.
1826 if (NewEdgeContextIds.empty()) {
1827 ++EI;
1828 continue;
1829 }
1830 if (TowardsCallee) {
1831 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1832 auto NewEdge = std::make_shared<ContextEdge>(
1833 Edge->Callee, NewNode, NewAllocType, std::move(NewEdgeContextIds));
1834 NewNode->CalleeEdges.push_back(NewEdge);
1835 NewEdge->Callee->CallerEdges.push_back(NewEdge);
1836 } else {
1837 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1838 auto NewEdge = std::make_shared<ContextEdge>(
1839 NewNode, Edge->Caller, NewAllocType, std::move(NewEdgeContextIds));
1840 NewNode->CallerEdges.push_back(NewEdge);
1841 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
1842 }
1843 // Remove old edge if context ids empty.
1844 if (Edge->getContextIds().empty()) {
1845 removeEdgeFromGraph(Edge.get(), &EI, TowardsCallee);
1846 continue;
1847 }
1848 ++EI;
1849 }
1850}
1851
1852template <typename DerivedCCG, typename FuncTy, typename CallTy>
1853static void checkEdge(
1854 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &Edge) {
1855 // Confirm that alloc type is not None and that we have at least one context
1856 // id.
1857 assert(Edge->AllocTypes != (uint8_t)AllocationType::None);
1858 assert(!Edge->ContextIds.empty());
1859}
1860
1861template <typename DerivedCCG, typename FuncTy, typename CallTy>
1862static void checkNode(const ContextNode<DerivedCCG, FuncTy, CallTy> *Node,
1863 bool CheckEdges = true) {
1864 if (Node->isRemoved())
1865 return;
1866#ifndef NDEBUG
1867 // Compute node's context ids once for use in asserts.
1868 auto NodeContextIds = Node->getContextIds();
1869#endif
1870 // Node's context ids should be the union of both its callee and caller edge
1871 // context ids.
1872 if (Node->CallerEdges.size()) {
1873 DenseSet<uint32_t> CallerEdgeContextIds(
1874 Node->CallerEdges.front()->ContextIds);
1875 for (const auto &Edge : llvm::drop_begin(Node->CallerEdges)) {
1876 if (CheckEdges)
1878 set_union(CallerEdgeContextIds, Edge->ContextIds);
1879 }
1880 // Node can have more context ids than callers if some contexts terminate at
1881 // node and some are longer. If we are allowing recursive callsites and
1882 // contexts this will be violated for incompletely cloned recursive cycles,
1883 // so skip the checking in that case.
1885 NodeContextIds == CallerEdgeContextIds ||
1886 set_is_subset(CallerEdgeContextIds, NodeContextIds));
1887 }
1888 if (Node->CalleeEdges.size()) {
1889 DenseSet<uint32_t> CalleeEdgeContextIds(
1890 Node->CalleeEdges.front()->ContextIds);
1891 for (const auto &Edge : llvm::drop_begin(Node->CalleeEdges)) {
1892 if (CheckEdges)
1894 set_union(CalleeEdgeContextIds, Edge->getContextIds());
1895 }
1896 // If we are allowing recursive callsites and contexts this will be violated
1897 // for incompletely cloned recursive cycles, so skip the checking in that
1898 // case.
1900 NodeContextIds == CalleeEdgeContextIds);
1901 }
1902 // FIXME: Since this checking is only invoked under an option, we should
1903 // change the error checking from using assert to something that will trigger
1904 // an error on a release build.
1905#ifndef NDEBUG
1906 // Make sure we don't end up with duplicate edges between the same caller and
1907 // callee.
1909 for (const auto &E : Node->CalleeEdges)
1910 NodeSet.insert(E->Callee);
1911 assert(NodeSet.size() == Node->CalleeEdges.size());
1912#endif
1913}
1914
1915template <typename DerivedCCG, typename FuncTy, typename CallTy>
1916void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1917 assignStackNodesPostOrder(ContextNode *Node,
1918 DenseSet<const ContextNode *> &Visited,
1919 DenseMap<uint64_t, std::vector<CallContextInfo>>
1920 &StackIdToMatchingCalls,
1921 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
1922 const DenseSet<uint32_t> &ImportantContextIds) {
1923 auto Inserted = Visited.insert(Node);
1924 if (!Inserted.second)
1925 return;
1926 // Post order traversal. Iterate over a copy since we may add nodes and
1927 // therefore new callers during the recursive call, invalidating any
1928 // iterator over the original edge vector. We don't need to process these
1929 // new nodes as they were already processed on creation.
1930 auto CallerEdges = Node->CallerEdges;
1931 for (auto &Edge : CallerEdges) {
1932 // Skip any that have been removed during the recursion.
1933 if (Edge->isRemoved()) {
1934 assert(!is_contained(Node->CallerEdges, Edge));
1935 continue;
1936 }
1937 assignStackNodesPostOrder(Edge->Caller, Visited, StackIdToMatchingCalls,
1938 CallToMatchingCall, ImportantContextIds);
1939 }
1940
1941 // If this node's stack id is in the map, update the graph to contain new
1942 // nodes representing any inlining at interior callsites. Note we move the
1943 // associated context ids over to the new nodes.
1944
1945 // Ignore this node if it is for an allocation or we didn't record any
1946 // stack id lists ending at it.
1947 if (Node->IsAllocation ||
1948 !StackIdToMatchingCalls.count(Node->OrigStackOrAllocId))
1949 return;
1950
1951 auto &Calls = StackIdToMatchingCalls[Node->OrigStackOrAllocId];
1952 // Handle the simple case first. A single call with a single stack id.
1953 // In this case there is no need to create any new context nodes, simply
1954 // assign the context node for stack id to this Call.
1955 if (Calls.size() == 1) {
1956 auto &[Call, StackNodes, Func, SavedContextIds] = Calls[0];
1957 if (StackNodes.size() == 1) {
1958 assert(SavedContextIds.empty());
1959 // It should be this Node
1960 assert(Node == StackNodes[0]);
1961 if (Node->Recursive)
1962 return;
1963 Node->setCall(Call);
1964 NonAllocationCallToContextNodeMap[Call] = Node;
1965 NodeToCallingFunc[Node] = Func;
1966 recordStackNode(StackNodes, Node, Node->getContextIds(),
1967 ImportantContextIds);
1968 return;
1969 }
1970 }
1971
1972#ifndef NDEBUG
1973 // Find the node for the last stack id, which should be the same
1974 // across all calls recorded for this id, and is this node's id.
1975 uint64_t LastId = Node->OrigStackOrAllocId;
1976 ContextNode *LastNode = getNodeForStackId(LastId);
1977 // We should only have kept stack ids that had nodes.
1978 assert(LastNode);
1979 assert(LastNode == Node);
1980#else
1981 ContextNode *LastNode = Node;
1982#endif
1983
1984 // Compute the last node's context ids once, as it is shared by all calls in
1985 // this entry.
1986 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
1987
1988 [[maybe_unused]] bool PrevIterCreatedNode = false;
1989 bool CreatedNode = false;
1990 for (unsigned I = 0; I < Calls.size();
1991 I++, PrevIterCreatedNode = CreatedNode) {
1992 CreatedNode = false;
1993 auto &[Call, StackNodes, Func, SavedContextIds] = Calls[I];
1994 // Skip any for which we didn't assign any ids, these don't get a node in
1995 // the graph.
1996 if (SavedContextIds.empty()) {
1997 // If this call has a matching call (located in the same function and
1998 // having the same stack ids), simply add it to the context node created
1999 // for its matching call earlier. These can be treated the same through
2000 // cloning and get updated at the same time.
2001 if (!CallToMatchingCall.contains(Call))
2002 continue;
2003 auto MatchingCall = CallToMatchingCall[Call];
2004 if (!NonAllocationCallToContextNodeMap.contains(MatchingCall)) {
2005 // This should only happen if we had a prior iteration, and it didn't
2006 // create a node because of the below recomputation of context ids
2007 // finding none remaining and continuing early.
2008 assert(I > 0 && !PrevIterCreatedNode);
2009 continue;
2010 }
2011 NonAllocationCallToContextNodeMap[MatchingCall]->MatchingCalls.push_back(
2012 Call);
2013 continue;
2014 }
2015
2016 assert(LastNode == StackNodes.back());
2017
2018 // Recompute the context ids for this stack id sequence (the
2019 // intersection of the context ids of the corresponding nodes).
2020 // Start with the ids we saved in the map for this call, which could be
2021 // duplicated context ids. We have to recompute as we might have overlap
2022 // overlap between the saved context ids for different last nodes, and
2023 // removed them already during the post order traversal.
2024 set_intersect(SavedContextIds, LastNodeContextIds);
2025 ContextNode *PrevNode = LastNode;
2026 bool Skip = false;
2027 // Iterate backwards through the stack nodes, starting after the last one
2028 // in the list, which was handled once outside for all Calls.
2029 for (auto NodeIter = StackNodes.rbegin() + 1; NodeIter != StackNodes.rend();
2030 NodeIter++) {
2031 ContextNode *CurNode = *NodeIter;
2032 // We should only have kept stack ids that had nodes and weren't
2033 // recursive.
2034 assert(CurNode);
2035 assert(!CurNode->Recursive);
2036
2037 auto *Edge = CurNode->findEdgeFromCaller(PrevNode);
2038 if (!Edge) {
2039 Skip = true;
2040 break;
2041 }
2042 PrevNode = CurNode;
2043
2044 // Update the context ids, which is the intersection of the ids along
2045 // all edges in the sequence.
2046 set_intersect(SavedContextIds, Edge->getContextIds());
2047
2048 // If we now have no context ids for clone, skip this call.
2049 if (SavedContextIds.empty()) {
2050 Skip = true;
2051 break;
2052 }
2053 }
2054 if (Skip)
2055 continue;
2056
2057 // Create new context node.
2058 ContextNode *NewNode = createNewNode(/*IsAllocation=*/false, Func, Call);
2059 NonAllocationCallToContextNodeMap[Call] = NewNode;
2060 CreatedNode = true;
2061 NewNode->AllocTypes = computeAllocType(SavedContextIds);
2062
2063 ContextNode *FirstNode = StackNodes[0];
2064 assert(FirstNode);
2065
2066 // Connect to callees of innermost stack frame in inlined call chain.
2067 // This updates context ids for FirstNode's callee's to reflect those
2068 // moved to NewNode.
2069 connectNewNode(NewNode, FirstNode, /*TowardsCallee=*/true, SavedContextIds);
2070
2071 // Connect to callers of outermost stack frame in inlined call chain.
2072 // This updates context ids for FirstNode's caller's to reflect those
2073 // moved to NewNode.
2074 connectNewNode(NewNode, LastNode, /*TowardsCallee=*/false, SavedContextIds);
2075
2076 // Now we need to remove context ids from edges/nodes between First and
2077 // Last Node.
2078 PrevNode = nullptr;
2079 for (ContextNode *CurNode : StackNodes) {
2080 // We should only have kept stack ids that had nodes.
2081 assert(CurNode);
2082
2083 // Remove the context ids moved to NewNode from CurNode, and the
2084 // edge from the prior node.
2085 if (PrevNode) {
2086 auto *PrevEdge = CurNode->findEdgeFromCallee(PrevNode);
2087 // If the sequence contained recursion, we might have already removed
2088 // some edges during the connectNewNode calls above.
2089 if (!PrevEdge) {
2090 PrevNode = CurNode;
2091 continue;
2092 }
2093 set_subtract(PrevEdge->getContextIds(), SavedContextIds);
2094 if (PrevEdge->getContextIds().empty())
2095 removeEdgeFromGraph(PrevEdge);
2096 }
2097 // Since we update the edges from leaf to tail, only look at the callee
2098 // edges. This isn't an alloc node, so if there are no callee edges, the
2099 // alloc type is None.
2100 CurNode->AllocTypes = CurNode->CalleeEdges.empty()
2101 ? (uint8_t)AllocationType::None
2102 : CurNode->computeAllocType();
2103 PrevNode = CurNode;
2104 }
2105
2106 recordStackNode(StackNodes, NewNode, SavedContextIds, ImportantContextIds);
2107
2108 if (VerifyNodes) {
2109 checkNode<DerivedCCG, FuncTy, CallTy>(NewNode, /*CheckEdges=*/true);
2110 for (ContextNode *CurNode : StackNodes) {
2111 // We should only have kept stack ids that had nodes.
2112 assert(CurNode);
2113 checkNode<DerivedCCG, FuncTy, CallTy>(CurNode, /*CheckEdges=*/true);
2114 }
2115 }
2116 }
2117}
2118
2119template <typename DerivedCCG, typename FuncTy, typename CallTy>
2120void CallsiteContextGraph<DerivedCCG, FuncTy,
2121 CallTy>::fixupImportantContexts() {
2122 if (ImportantContextIdInfo.empty())
2123 return;
2124
2125 // Update statistics as we are done building this map at this point.
2126 NumImportantContextIds = ImportantContextIdInfo.size();
2127
2129 return;
2130
2131 if (ExportToDot)
2132 exportToDot("beforestackfixup");
2133
2134 // For each context we identified as important, walk through the saved context
2135 // stack ids in order from leaf upwards, and make sure all edges are correct.
2136 // These can be difficult to get right when updating the graph while mapping
2137 // nodes onto summary or IR, especially when there is recursion. In
2138 // particular, when we have created new nodes to reflect inlining, it is
2139 // sometimes impossible to know exactly how to update the edges in the face of
2140 // recursion, as we have lost the original ordering of the stack ids in the
2141 // contexts.
2142 // TODO: Consider only doing this if we detect the context has recursive
2143 // cycles.
2144 //
2145 // I.e. assume we have a context with stack ids like: {A B A C A D E}
2146 // and let's say A was inlined into B, C, and D. The original graph will have
2147 // multiple recursive cycles through A. When we match the original context
2148 // nodes onto the IR or summary, we will merge {A B} into one context node,
2149 // {A C} onto another, and {A D} onto another. Looking at the stack sequence
2150 // above, we should end up with a non-cyclic set of edges like:
2151 // {AB} <- {AC} <- {AD} <- E. However, because we normally have lost the
2152 // original ordering, we won't get the edges correct initially (it's
2153 // impossible without the original ordering). Here we do the fixup (add and
2154 // removing edges where necessary) for this context. In the
2155 // ImportantContextInfo struct in this case we should have a MaxLength = 2,
2156 // and map entries for {A B}, {A C}, {A D}, and {E}.
2157 for (auto &[CurContextId, Info] : ImportantContextIdInfo) {
2158 if (Info.StackIdsToNode.empty())
2159 continue;
2160 bool Changed = false;
2161 ContextNode *PrevNode = nullptr;
2162 ContextNode *CurNode = nullptr;
2163 DenseSet<const ContextEdge *> VisitedEdges;
2164 ArrayRef<uint64_t> AllStackIds(Info.StackIds);
2165 // Try to identify what callsite ContextNode maps to which slice of the
2166 // context's ordered stack ids.
2167 for (unsigned I = 0; I < AllStackIds.size(); I++, PrevNode = CurNode) {
2168 // We will do this greedily, trying up to MaxLength stack ids in a row, to
2169 // see if we recorded a context node for that sequence.
2170 auto Len = Info.MaxLength;
2171 auto LenToEnd = AllStackIds.size() - I;
2172 if (Len > LenToEnd)
2173 Len = LenToEnd;
2174 CurNode = nullptr;
2175 // Try to find a recorded context node starting with the longest length
2176 // recorded, and on down until we check for just a single stack node.
2177 for (; Len > 0; Len--) {
2178 // Get the slice of the original stack id sequence to check.
2179 auto CheckStackIds = AllStackIds.slice(I, Len);
2180 auto EntryIt = Info.StackIdsToNode.find(CheckStackIds);
2181 if (EntryIt == Info.StackIdsToNode.end())
2182 continue;
2183 CurNode = EntryIt->second;
2184 // Skip forward so we don't try to look for the ones we just matched.
2185 // We increment by Len - 1, because the outer for loop will increment I.
2186 I += Len - 1;
2187 break;
2188 }
2189 // Give up if we couldn't find a node. Since we need to clone from the
2190 // leaf allocation upwards, no sense in doing anymore fixup further up
2191 // the context if we couldn't match part of the original stack context
2192 // onto a callsite node.
2193 if (!CurNode)
2194 break;
2195 // No edges to fix up until we have a pair of nodes that should be
2196 // adjacent in the graph.
2197 if (!PrevNode)
2198 continue;
2199 // See if we already have a call edge from CurNode to PrevNode.
2200 auto *CurEdge = PrevNode->findEdgeFromCaller(CurNode);
2201 if (CurEdge) {
2202 // We already have an edge. Make sure it contains this context id.
2203 if (CurEdge->getContextIds().insert(CurContextId).second) {
2204 NumFixupEdgeIdsInserted++;
2205 Changed = true;
2206 }
2207 } else {
2208 // No edge exists - add one.
2209 NumFixupEdgesAdded++;
2210 DenseSet<uint32_t> ContextIds({CurContextId});
2211 auto AllocType = computeAllocType(ContextIds);
2212 auto NewEdge = std::make_shared<ContextEdge>(
2213 PrevNode, CurNode, AllocType, std::move(ContextIds));
2214 PrevNode->CallerEdges.push_back(NewEdge);
2215 CurNode->CalleeEdges.push_back(NewEdge);
2216 // Save the new edge for the below handling.
2217 CurEdge = NewEdge.get();
2218 Changed = true;
2219 }
2220 VisitedEdges.insert(CurEdge);
2221 // Now remove this context id from any other caller edges calling
2222 // PrevNode.
2223 for (auto &Edge : PrevNode->CallerEdges) {
2224 // Skip the edge updating/created above and edges we have already
2225 // visited (due to recursion).
2226 if (Edge.get() != CurEdge && !VisitedEdges.contains(Edge.get()))
2227 Edge->getContextIds().erase(CurContextId);
2228 }
2229 }
2230 if (Changed)
2231 NumFixedContexts++;
2232 }
2233}
2234
2235template <typename DerivedCCG, typename FuncTy, typename CallTy>
2236void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::updateStackNodes() {
2237 // Map of stack id to all calls with that as the last (outermost caller)
2238 // callsite id that has a context node (some might not due to trimming
2239 // performed during matching of the allocation profile contexts).
2240 // The CallContextInfo contains the Call and a list of the context nodes for
2241 // its stack ids, the function containing Call, and the set of context ids
2242 // the analysis will eventually identify for use in any new node created
2243 // for that callsite.
2244 DenseMap<uint64_t, std::vector<CallContextInfo>> StackIdToMatchingCalls;
2245 for (auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
2246 for (auto &Call : CallsWithMetadata) {
2247 // Ignore allocations, already handled.
2248 if (AllocationCallToContextNodeMap.count(Call))
2249 continue;
2250 std::vector<ContextNode *> StackNodes = getStackNodesForCall(Call.call());
2251 // If there were no nodes created for MIBs on allocs (maybe this was in
2252 // the unambiguous part of the MIB stack that was trimmed), ignore.
2253 if (StackNodes.empty())
2254 continue;
2255 // Otherwise, record this Call along with the list of nodes for the last
2256 // (outermost caller) stack id with a node.
2257 uint64_t LastId = StackNodes.back()->OrigStackOrAllocId;
2258 StackIdToMatchingCalls[LastId].push_back(
2259 {Call.call(), std::move(StackNodes), Func, {}});
2260 }
2261 }
2262
2263 // First make a pass through all stack ids that correspond to a call,
2264 // as identified in the above loop. Compute the context ids corresponding to
2265 // each of these calls when they correspond to multiple stack ids due to
2266 // due to inlining. Perform any duplication of context ids required when
2267 // there is more than one call with the same stack ids. Their (possibly newly
2268 // duplicated) context ids are saved in the StackIdToMatchingCalls map.
2269 DenseMap<uint32_t, DenseSet<uint32_t>> OldToNewContextIds;
2270 // Save a map from each call to any that are found to match it. I.e. located
2271 // in the same function and have the same (possibly trimmed) stack ids. We use
2272 // this to avoid creating extra graph nodes as they can be treated the same.
2273 DenseMap<CallInfo, CallInfo> CallToMatchingCall;
2274 for (auto &It : StackIdToMatchingCalls) {
2275 auto &Calls = It.getSecond();
2276 // Skip single calls with a single stack id. These don't need a new node.
2277 if (Calls.size() == 1) {
2278 auto &StackNodes = Calls[0].StackNodes;
2279 if (StackNodes.size() == 1)
2280 continue;
2281 }
2282 // In order to do the best and maximal matching of inlined calls to context
2283 // node sequences we will sort the vectors of stack nodes in descending
2284 // order of length, and within each length, lexicographically by stack id.
2285 // The latter is so that we can specially handle calls that have identical
2286 // stack id sequences (either due to cloning or artificially because of the
2287 // MIB context trimming). Those with the same stack ids are then sorted by
2288 // function to facilitate efficiently mapping them to the same context node.
2289 // Because the functions are pointers, to ensure a stable sort first assign
2290 // each function pointer to its first index in the Calls array, and then use
2291 // that to sort by.
2292 DenseMap<const FuncTy *, unsigned> FuncToIndex;
2293 for (const auto &[Idx, CallCtxInfo] : enumerate(Calls))
2294 FuncToIndex.insert({CallCtxInfo.Func, Idx});
2295 auto StackIdsLess = [](ArrayRef<ContextNode *> A,
2297 return std::lexicographical_compare(
2298 A.begin(), A.end(), B.begin(), B.end(),
2299 [](const ContextNode *X, const ContextNode *Y) {
2300 return X->OrigStackOrAllocId < Y->OrigStackOrAllocId;
2301 });
2302 };
2303 auto CallLess = [&FuncToIndex, &StackIdsLess](const CallContextInfo &A,
2304 const CallContextInfo &B) {
2305 return A.StackNodes.size() > B.StackNodes.size() ||
2306 (A.StackNodes.size() == B.StackNodes.size() &&
2307 (StackIdsLess(A.StackNodes, B.StackNodes) ||
2308 (A.StackNodes == B.StackNodes &&
2309 FuncToIndex[A.Func] < FuncToIndex[B.Func])));
2310 };
2311 llvm::stable_sort(Calls, CallLess);
2312
2313 // Find the node for the last stack id, which should be the same
2314 // across all calls recorded for this id, and is the id for this
2315 // entry in the StackIdToMatchingCalls map.
2316 uint64_t LastId = It.getFirst();
2317 // All calls in this entry share the same last node.
2318 ContextNode *LastNode = Calls[0].StackNodes.back();
2319 // We should only have kept stack ids that had nodes.
2320 assert(LastNode);
2321 assert(LastNode == getNodeForStackId(LastId));
2322
2323 if (LastNode->Recursive)
2324 continue;
2325
2326 // Initialize the context ids with the last node's. We will subsequently
2327 // refine the context ids by computing the intersection along all edges.
2328 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
2329 assert(!LastNodeContextIds.empty());
2330
2331#ifndef NDEBUG
2332 // Save the set of functions seen for a particular set of the same stack
2333 // ids. This is used to ensure that they have been correctly sorted to be
2334 // adjacent in the Calls list, since we rely on that to efficiently place
2335 // all such matching calls onto the same context node.
2336 DenseSet<const FuncTy *> MatchingIdsFuncSet;
2337#endif
2338
2339 for (unsigned I = 0; I < Calls.size(); I++) {
2340 auto &[Call, StackNodes, Func, SavedContextIds] = Calls[I];
2341 assert(SavedContextIds.empty());
2342 assert(LastNode == StackNodes.back());
2343
2344#ifndef NDEBUG
2345 // If this call has a different set of ids than the last one, clear the
2346 // set used to ensure they are sorted properly.
2347 if (I > 0 && StackNodes != Calls[I - 1].StackNodes)
2348 MatchingIdsFuncSet.clear();
2349#endif
2350
2351 // First compute the context ids for this stack id sequence (the
2352 // intersection of the context ids of the corresponding nodes).
2353 // Start with the remaining saved ids for the last node.
2354 assert(!LastNodeContextIds.empty());
2355 DenseSet<uint32_t> StackSequenceContextIds = LastNodeContextIds;
2356
2357 ContextNode *PrevNode = LastNode;
2358 ContextNode *CurNode = LastNode;
2359 bool Skip = false;
2360
2361 // Iterate backwards through the stack nodes, starting after the last
2362 // one in the list, which was handled once outside for all Calls.
2363 for (auto NodeIter = StackNodes.rbegin() + 1;
2364 NodeIter != StackNodes.rend(); NodeIter++) {
2365 CurNode = *NodeIter;
2366 // We should only have kept stack ids that had nodes.
2367 assert(CurNode);
2368
2369 if (CurNode->Recursive) {
2370 Skip = true;
2371 break;
2372 }
2373
2374 auto *Edge = CurNode->findEdgeFromCaller(PrevNode);
2375 // If there is no edge then the nodes belong to different MIB contexts,
2376 // and we should skip this inlined context sequence. For example, this
2377 // particular inlined context may include stack ids A->B, and we may
2378 // indeed have nodes for both A and B, but it is possible that they were
2379 // never profiled in sequence in a single MIB for any allocation (i.e.
2380 // we might have profiled an allocation that involves the callsite A,
2381 // but through a different one of its callee callsites, and we might
2382 // have profiled an allocation that involves callsite B, but reached
2383 // from a different caller callsite).
2384 if (!Edge) {
2385 Skip = true;
2386 break;
2387 }
2388 PrevNode = CurNode;
2389
2390 // Update the context ids, which is the intersection of the ids along
2391 // all edges in the sequence.
2392 set_intersect(StackSequenceContextIds, Edge->getContextIds());
2393
2394 // If we now have no context ids for clone, skip this call.
2395 if (StackSequenceContextIds.empty()) {
2396 Skip = true;
2397 break;
2398 }
2399 }
2400 if (Skip)
2401 continue;
2402
2403 // If some of this call's stack ids did not have corresponding nodes (due
2404 // to trimming), don't include any context ids for contexts that extend
2405 // beyond these nodes. Otherwise we would be matching part of unrelated /
2406 // not fully matching stack contexts. To do this, subtract any context ids
2407 // found in caller nodes of the last node found above.
2408 if (LastId != getLastStackId(Call)) {
2409 for (const auto &PE : LastNode->CallerEdges) {
2410 set_subtract(StackSequenceContextIds, PE->getContextIds());
2411 if (StackSequenceContextIds.empty())
2412 break;
2413 }
2414 // If we now have no context ids for clone, skip this call.
2415 if (StackSequenceContextIds.empty())
2416 continue;
2417 }
2418
2419#ifndef NDEBUG
2420 // If the prior call had the same stack ids this set would not be empty.
2421 // Check if we already have a call that "matches" because it is located
2422 // in the same function. If the Calls list was sorted properly we should
2423 // not encounter this situation as all such entries should be adjacent
2424 // and processed in bulk further below.
2425 assert(!MatchingIdsFuncSet.contains(Func));
2426
2427 MatchingIdsFuncSet.insert(Func);
2428#endif
2429
2430 // Check if the next set of stack ids is the same (since the Calls vector
2431 // of tuples is sorted by the stack ids we can just look at the next one).
2432 // If so, save them in the CallToMatchingCall map so that they get
2433 // assigned to the same context node, and skip them. Comparing the stack
2434 // nodes is equivalent to comparing the stack ids, as each stack id has
2435 // its own node and the stack id to node map is not modified here.
2436 bool DuplicateContextIds = false;
2437 for (unsigned J = I + 1; J < Calls.size(); J++) {
2438 auto &CallCtxInfo = Calls[J];
2439 if (CallCtxInfo.StackNodes != StackNodes)
2440 break;
2441 auto *NextFunc = CallCtxInfo.Func;
2442 if (NextFunc != Func) {
2443 // We have another Call with the same ids but that cannot share this
2444 // node, must duplicate ids for it.
2445 DuplicateContextIds = true;
2446 break;
2447 }
2448 auto &NextCall = CallCtxInfo.Call;
2449 CallToMatchingCall[NextCall] = Call;
2450 // Update I so that it gets incremented correctly to skip this call.
2451 I = J;
2452 }
2453
2454 // If we don't have duplicate context ids, then we can assign all the
2455 // context ids computed for the original node sequence to this call.
2456 // If there are duplicate calls with the same stack ids then we synthesize
2457 // new context ids that are duplicates of the originals. These are
2458 // assigned to SavedContextIds, which is a reference into the map entry
2459 // for this call, allowing us to access these ids later on.
2460 OldToNewContextIds.reserve(OldToNewContextIds.size() +
2461 StackSequenceContextIds.size());
2462 SavedContextIds =
2463 DuplicateContextIds
2464 ? duplicateContextIds(StackSequenceContextIds, OldToNewContextIds)
2465 : StackSequenceContextIds;
2466 assert(!SavedContextIds.empty());
2467
2468 if (!DuplicateContextIds) {
2469 // Update saved last node's context ids to remove those that are
2470 // assigned to other calls, so that it is ready for the next call at
2471 // this stack id.
2472 set_subtract(LastNodeContextIds, StackSequenceContextIds);
2473 if (LastNodeContextIds.empty())
2474 break;
2475 }
2476 }
2477 }
2478
2479 // Propagate the duplicate context ids over the graph.
2480 propagateDuplicateContextIds(OldToNewContextIds);
2481
2482 if (VerifyCCG)
2483 check();
2484
2485 // Now perform a post-order traversal over the graph, starting with the
2486 // allocation nodes, essentially processing nodes from callers to callees.
2487 // For any that contains an id in the map, update the graph to contain new
2488 // nodes representing any inlining at interior callsites. Note we move the
2489 // associated context ids over to the new nodes.
2490 DenseSet<const ContextNode *> Visited;
2491 DenseSet<uint32_t> ImportantContextIds(llvm::from_range,
2492 ImportantContextIdInfo.keys());
2493 for (auto &Entry : AllocationCallToContextNodeMap)
2494 assignStackNodesPostOrder(Entry.second, Visited, StackIdToMatchingCalls,
2495 CallToMatchingCall, ImportantContextIds);
2496
2497 fixupImportantContexts();
2498
2499 if (VerifyCCG)
2500 check();
2501}
2502
2503uint64_t ModuleCallsiteContextGraph::getLastStackId(Instruction *Call) {
2504 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2505 Call->getMetadata(LLVMContext::MD_callsite));
2506 return CallsiteContext.back();
2507}
2508
2509uint64_t IndexCallsiteContextGraph::getLastStackId(IndexCall &Call) {
2511 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2512 CallsiteContext(dyn_cast_if_present<CallsiteInfo *>(Call));
2513 // Need to convert index into stack id.
2514 return Index.getStackIdAtIndex(CallsiteContext.back());
2515}
2516
2517static const std::string MemProfCloneSuffix = ".memprof.";
2518
2519static std::string getMemProfFuncName(Twine Base, unsigned CloneNo) {
2520 // We use CloneNo == 0 to refer to the original version, which doesn't get
2521 // renamed with a suffix.
2522 if (!CloneNo)
2523 return Base.str();
2524 return (Base + MemProfCloneSuffix + Twine(CloneNo)).str();
2525}
2526
2527static bool isMemProfClone(const GlobalValue &GV) {
2528 return GV.getName().contains(MemProfCloneSuffix);
2529}
2530
2531// Return the clone number of the given function by extracting it from the
2532// memprof suffix. Assumes the caller has already confirmed it is a memprof
2533// clone.
2534static unsigned getMemProfCloneNum(const Function &F) {
2536 auto Pos = F.getName().find_last_of('.');
2537 assert(Pos > 0);
2538 unsigned CloneNo;
2539 bool Err = F.getName().drop_front(Pos + 1).getAsInteger(10, CloneNo);
2540 assert(!Err);
2541 (void)Err;
2542 return CloneNo;
2543}
2544
2545std::string ModuleCallsiteContextGraph::getLabel(const Function *Func,
2546 const Instruction *Call,
2547 unsigned CloneNo) const {
2548 return (Twine(Call->getFunction()->getName()) + " -> " +
2549 cast<CallBase>(Call)->getCalledFunction()->getName())
2550 .str();
2551}
2552
2553std::string IndexCallsiteContextGraph::getLabel(const FunctionSummary *Func,
2554 const IndexCall &Call,
2555 unsigned CloneNo) const {
2556 auto VI = FSToVIMap.find(Func);
2557 assert(VI != FSToVIMap.end());
2558 std::string CallerName = getMemProfFuncName(VI->second.name(), CloneNo);
2560 return CallerName + " -> alloc";
2561 else {
2562 auto *Callsite = dyn_cast_if_present<CallsiteInfo *>(Call);
2563 return CallerName + " -> " +
2564 getMemProfFuncName(Callsite->Callee.name(),
2565 Callsite->Clones[CloneNo]);
2566 }
2567}
2568
2569std::string ModuleCallsiteContextGraph::getFuncName(const Function *Func,
2570 unsigned CloneNo) const {
2571 if (!Func)
2572 return "<unknown>";
2573 return getMemProfFuncName(Func->getName(), CloneNo);
2574}
2575
2576void ModuleCallsiteContextGraph::populateFunctionsWithCallers() {
2577 // Any use (direct call, address taken, alias, etc.) means the function is
2578 // referenced and may be reached by callers above the profiled context.
2579 for (const auto &F : Mod)
2580 if (!F.use_empty())
2581 FunctionsWithCallers.insert(&F);
2582}
2583
2584std::string IndexCallsiteContextGraph::getFuncName(const FunctionSummary *Func,
2585 unsigned CloneNo) const {
2586 if (!Func)
2587 return "<unknown>";
2588 auto VI = FSToVIMap.find(Func);
2589 if (VI != FSToVIMap.end()) {
2590 if (!VI->second.name().empty())
2591 return getMemProfFuncName(VI->second.name(), CloneNo);
2592 return getMemProfFuncName("GUID:" + std::to_string(VI->second.getGUID()),
2593 CloneNo);
2594 }
2595 return getMemProfFuncName("<unknown>", CloneNo);
2596}
2597
2598bool IndexCallsiteContextGraph::isFuncDead(const FunctionSummary *Func) const {
2599 return Index.withGlobalValueDeadStripping() && Func && !Func->isLive();
2600}
2601
2602void IndexCallsiteContextGraph::populateFunctionsWithCallers() {
2603 for (const auto &I : Index) {
2604 auto VI = Index.getValueInfo(I);
2605 for (const auto &S : VI.getSummaryList()) {
2606 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
2607 !isPrevailing(VI.getGUID(), S.get()))
2608 continue;
2609 if (Index.withGlobalValueDeadStripping() && !S->isLive())
2610 continue;
2611 auto AddReferenced = [&](ValueInfo RefVI) {
2612 for (const auto &RefS : RefVI.getSummaryList()) {
2613 const GlobalValueSummary *Base = RefS->getBaseObject();
2614 if (const auto *RefFS = dyn_cast<FunctionSummary>(Base))
2615 FunctionsWithCallers.insert(RefFS);
2616 }
2617 };
2618 // Address-taken references (e.g. from vtables or function pointers).
2619 for (const auto &RefVI : S->refs())
2620 AddReferenced(RefVI);
2621 // Direct calls.
2622 if (const auto *FS = dyn_cast<FunctionSummary>(S.get()))
2623 for (const auto &CallEdge : FS->calls())
2624 AddReferenced(CallEdge.first);
2625 }
2626 }
2627}
2628
2629std::vector<ModuleCallsiteContextGraph::ContextNode *>
2630ModuleCallsiteContextGraph::getStackNodesForCall(Instruction *Call) {
2631 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2632 Call->getMetadata(LLVMContext::MD_callsite));
2633 return getStackNodesForCallsite<MDNode, MDNode::op_iterator>(CallsiteContext);
2634}
2635
2636std::vector<IndexCallsiteContextGraph::ContextNode *>
2637IndexCallsiteContextGraph::getStackNodesForCall(IndexCall &Call) {
2639 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2640 CallsiteContext(dyn_cast_if_present<CallsiteInfo *>(Call));
2641 return getStackNodesForCallsite<CallsiteInfo,
2642 SmallVector<unsigned>::const_iterator>(
2643 CallsiteContext);
2644}
2645
2646template <typename DerivedCCG, typename FuncTy, typename CallTy>
2647template <class NodeT, class IteratorT>
2648std::vector<
2649 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *>
2650CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getStackNodesForCallsite(
2651 CallStack<NodeT, IteratorT> &CallsiteContext) {
2652 std::vector<ContextNode *> StackNodes;
2653 for (auto IdOrIndex : CallsiteContext) {
2654 auto StackId = getStackId(IdOrIndex);
2655 ContextNode *Node = getNodeForStackId(StackId);
2656 if (!Node)
2657 break;
2658 StackNodes.push_back(Node);
2659 }
2660 return StackNodes;
2661}
2662
2663ModuleCallsiteContextGraph::ModuleCallsiteContextGraph(
2664 Module &M,
2665 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter)
2666 : Mod(M), OREGetter(OREGetter) {
2667 // Map for keeping track of the largest cold contexts up to the number given
2668 // by MemProfTopNImportant. Must be a std::map (not DenseMap) because keys
2669 // must be sorted.
2670 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2671 for (auto &F : M) {
2672 std::vector<CallInfo> CallsWithMetadata;
2673 for (auto &BB : F) {
2674 for (auto &I : BB) {
2675 if (!isa<CallBase>(I))
2676 continue;
2677 if (auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof)) {
2678 CallsWithMetadata.push_back(&I);
2679 auto *AllocNode = addAllocNode(&I, &F);
2680 auto *CallsiteMD = I.getMetadata(LLVMContext::MD_callsite);
2681 assert(CallsiteMD);
2682 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(CallsiteMD);
2683 // Add all of the MIBs and their stack nodes.
2684 for (auto &MDOp : MemProfMD->operands()) {
2685 auto *MIBMD = cast<const MDNode>(MDOp);
2686 std::vector<ContextTotalSize> ContextSizeInfo;
2687 // Collect the context size information if it exists.
2688 if (MIBMD->getNumOperands() > 2) {
2689 for (unsigned I = 2; I < MIBMD->getNumOperands(); I++) {
2690 MDNode *ContextSizePair =
2691 dyn_cast<MDNode>(MIBMD->getOperand(I));
2692 assert(ContextSizePair->getNumOperands() == 2);
2694 ContextSizePair->getOperand(0))
2695 ->getZExtValue();
2697 ContextSizePair->getOperand(1))
2698 ->getZExtValue();
2699 ContextSizeInfo.push_back({FullStackId, TotalSize});
2700 }
2701 }
2705 addStackNodesForMIB<MDNode, MDNode::op_iterator>(
2706 AllocNode, StackContext, CallsiteContext,
2707 getMIBAllocType(MIBMD), ContextSizeInfo,
2708 TotalSizeToContextIdTopNCold);
2709 }
2710 // If exporting the graph to dot and an allocation id of interest was
2711 // specified, record all the context ids for this allocation node.
2712 if (ExportToDot && AllocNode->OrigStackOrAllocId == AllocIdForDot)
2713 DotAllocContextIds = AllocNode->getContextIds();
2714 assert(AllocNode->AllocTypes != (uint8_t)AllocationType::None);
2715 // Memprof and callsite metadata on memory allocations no longer
2716 // needed.
2717 I.setMetadata(LLVMContext::MD_memprof, nullptr);
2718 I.setMetadata(LLVMContext::MD_callsite, nullptr);
2719 }
2720 // For callsite metadata, add to list for this function for later use.
2721 else if (I.getMetadata(LLVMContext::MD_callsite)) {
2722 CallsWithMetadata.push_back(&I);
2723 }
2724 }
2725 }
2726 if (!CallsWithMetadata.empty())
2727 FuncToCallsWithMetadata[&F] = CallsWithMetadata;
2728 }
2729
2730 if (DumpCCG) {
2731 dbgs() << "CCG before updating call stack chains:\n";
2732 dbgs() << *this;
2733 }
2734
2735 if (ExportToDot)
2736 exportToDot("prestackupdate");
2737
2738 updateStackNodes();
2739
2740 if (ExportToDot)
2741 exportToDot("poststackupdate");
2742
2743 handleCallsitesWithMultipleTargets();
2744
2745 markBackedges();
2746
2747 // Strip off remaining callsite metadata, no longer needed.
2748 for (auto &FuncEntry : FuncToCallsWithMetadata)
2749 for (auto &Call : FuncEntry.second)
2750 Call.call()->setMetadata(LLVMContext::MD_callsite, nullptr);
2751}
2752
2753// Finds the set of GUIDs for weak aliasees that are prevailing in different
2754// modules than any of their aliases. We need to handle these specially.
2756IndexCallsiteContextGraph::findAliaseeGUIDsPrevailingInDifferentModule() {
2757 DenseSet<GlobalValue::GUID> AliaseeGUIDs;
2758 for (auto &I : Index) {
2759 auto VI = Index.getValueInfo(I);
2760 for (auto &S : VI.getSummaryList()) {
2761 // We only care about aliases to functions.
2762 auto *AS = dyn_cast<AliasSummary>(S.get());
2763 if (!AS)
2764 continue;
2765 auto *AliaseeSummary = &AS->getAliasee();
2766 auto *AliaseeFS = dyn_cast<FunctionSummary>(AliaseeSummary);
2767 if (!AliaseeFS)
2768 continue;
2769 // Skip this summary if it is not for the prevailing symbol for this GUID.
2770 // The linker doesn't resolve local linkage values so don't check whether
2771 // those are prevailing.
2772 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
2773 !isPrevailing(VI.getGUID(), S.get()))
2774 continue;
2775 // Prevailing aliasee could be in a different module only if it is weak.
2776 if (!GlobalValue::isWeakForLinker(AliaseeSummary->linkage()))
2777 continue;
2778 auto AliaseeGUID = AS->getAliaseeGUID();
2779 // If the aliasee copy in this module is not prevailing, record it.
2780 if (!isPrevailing(AliaseeGUID, AliaseeSummary))
2781 AliaseeGUIDs.insert(AliaseeGUID);
2782 }
2783 }
2784 AliaseesPrevailingInDiffModuleFromAlias += AliaseeGUIDs.size();
2785 return AliaseeGUIDs;
2786}
2787
2788IndexCallsiteContextGraph::IndexCallsiteContextGraph(
2789 ModuleSummaryIndex &Index,
2790 llvm::function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
2791 isPrevailing)
2792 : Index(Index), isPrevailing(isPrevailing) {
2793 // Since we use the aliasee summary info to create the necessary clones for
2794 // its aliases, conservatively skip recording the aliasee function's callsites
2795 // in the CCG for any that are prevailing in a different module than one of
2796 // its aliases. We could record the necessary information to do this in the
2797 // summary, but this case should not be common.
2798 DenseSet<GlobalValue::GUID> GUIDsToSkip =
2799 findAliaseeGUIDsPrevailingInDifferentModule();
2800 // Map for keeping track of the largest cold contexts up to the number given
2801 // by MemProfTopNImportant. Must be a std::map (not DenseMap) because keys
2802 // must be sorted.
2803 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2804 // Sort by GUID for deterministic graph construction order.
2805 // TODO: This sort has a measurable cost on the thin link when memprof is
2806 // enabled. Investigate gating it behind an option that is only enabled for
2807 // tests that check internal state.
2808 for (const auto &I : Index.sortedGlobalValueSummariesRange()) {
2809 auto VI = Index.getValueInfo(I);
2810 if (GUIDsToSkip.contains(VI.getGUID()))
2811 continue;
2812 for (auto &S : VI.getSummaryList()) {
2813 // We should only add the prevailing nodes. Otherwise we may try to clone
2814 // in a weak copy that won't be linked (and may be different than the
2815 // prevailing version).
2816 // We only keep the memprof summary on the prevailing copy now when
2817 // building the combined index, as a space optimization, however don't
2818 // rely on this optimization. The linker doesn't resolve local linkage
2819 // values so don't check whether those are prevailing.
2820 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
2821 !isPrevailing(VI.getGUID(), S.get()))
2822 continue;
2823 auto *FS = dyn_cast<FunctionSummary>(S.get());
2824 if (!FS)
2825 continue;
2826 std::vector<CallInfo> CallsWithMetadata;
2827 if (!FS->allocs().empty()) {
2828 for (auto &AN : FS->mutableAllocs()) {
2829 // This can happen because of recursion elimination handling that
2830 // currently exists in ModuleSummaryAnalysis. Skip these for now.
2831 // We still added them to the summary because we need to be able to
2832 // correlate properly in applyImport in the backends.
2833 if (AN.MIBs.empty())
2834 continue;
2835 IndexCall AllocCall(&AN);
2836 CallsWithMetadata.push_back(AllocCall);
2837 auto *AllocNode = addAllocNode(AllocCall, FS);
2838 // Pass an empty CallStack to the CallsiteContext (second)
2839 // parameter, since for ThinLTO we already collapsed out the inlined
2840 // stack ids on the allocation call during ModuleSummaryAnalysis.
2842 EmptyContext;
2843 unsigned I = 0;
2845 AN.ContextSizeInfos.size() == AN.MIBs.size());
2846 // Now add all of the MIBs and their stack nodes.
2847 for (auto &MIB : AN.MIBs) {
2849 StackContext(&MIB);
2850 std::vector<ContextTotalSize> ContextSizeInfo;
2851 if (!AN.ContextSizeInfos.empty()) {
2852 for (auto [FullStackId, TotalSize] : AN.ContextSizeInfos[I])
2853 ContextSizeInfo.push_back({FullStackId, TotalSize});
2854 }
2855 addStackNodesForMIB<MIBInfo, SmallVector<unsigned>::const_iterator>(
2856 AllocNode, StackContext, EmptyContext, MIB.AllocType,
2857 ContextSizeInfo, TotalSizeToContextIdTopNCold);
2858 I++;
2859 }
2860 // If exporting the graph to dot and an allocation id of interest was
2861 // specified, record all the context ids for this allocation node.
2862 if (ExportToDot && AllocNode->OrigStackOrAllocId == AllocIdForDot)
2863 DotAllocContextIds = AllocNode->getContextIds();
2864 assert(AllocNode->AllocTypes != (uint8_t)AllocationType::None);
2865 // Initialize version 0 on the summary alloc node to the current alloc
2866 // type, unless it has both types in which case make it default, so
2867 // that in the case where we aren't able to clone the original version
2868 // always ends up with the default allocation behavior.
2869 AN.Versions[0] = (uint8_t)allocTypeToUse(AllocNode->AllocTypes);
2870 }
2871 }
2872 // For callsite metadata, add to list for this function for later use.
2873 if (!FS->callsites().empty())
2874 for (auto &SN : FS->mutableCallsites()) {
2875 IndexCall StackNodeCall(&SN);
2876 CallsWithMetadata.push_back(StackNodeCall);
2877 }
2878
2879 if (!CallsWithMetadata.empty())
2880 FuncToCallsWithMetadata[FS] = CallsWithMetadata;
2881
2882 if (!FS->allocs().empty() || !FS->callsites().empty())
2883 FSToVIMap[FS] = VI;
2884 }
2885 }
2886
2887 if (DumpCCG) {
2888 dbgs() << "CCG before updating call stack chains:\n";
2889 dbgs() << *this;
2890 }
2891
2892 if (ExportToDot)
2893 exportToDot("prestackupdate");
2894
2895 updateStackNodes();
2896
2897 if (ExportToDot)
2898 exportToDot("poststackupdate");
2899
2900 handleCallsitesWithMultipleTargets();
2901
2902 markBackedges();
2903}
2904
2905template <typename DerivedCCG, typename FuncTy, typename CallTy>
2906void CallsiteContextGraph<DerivedCCG, FuncTy,
2907 CallTy>::handleCallsitesWithMultipleTargets() {
2908 // Look for and workaround callsites that call multiple functions.
2909 // This can happen for indirect calls, which needs better handling, and in
2910 // more rare cases (e.g. macro expansion).
2911 // TODO: To fix this for indirect calls we will want to perform speculative
2912 // devirtualization using either the normal PGO info with ICP, or using the
2913 // information in the profiled MemProf contexts. We can do this prior to
2914 // this transformation for regular LTO, and for ThinLTO we can simulate that
2915 // effect in the summary and perform the actual speculative devirtualization
2916 // while cloning in the ThinLTO backend.
2917
2918 // Keep track of the new nodes synthesized for discovered tail calls missing
2919 // from the profiled contexts.
2920 MapVector<CallInfo, ContextNode *> TailCallToContextNodeMap;
2921
2922 std::vector<std::pair<CallInfo, ContextNode *>> NewCallToNode;
2923 for (auto &Entry : NonAllocationCallToContextNodeMap) {
2924 auto *Node = Entry.second;
2925 assert(Node->Clones.empty());
2926 // Check all node callees and see if in the same function.
2927 // We need to check all of the calls recorded in this Node, because in some
2928 // cases we may have had multiple calls with the same debug info calling
2929 // different callees. This can happen, for example, when an object is
2930 // constructed in the paramter list - the destructor call of the object has
2931 // the same debug info (line/col) as the call the object was passed to.
2932 // Here we will prune any that don't match all callee nodes.
2933 std::vector<CallInfo> AllCalls;
2934 AllCalls.reserve(Node->MatchingCalls.size() + 1);
2935 AllCalls.push_back(Node->Call);
2936 llvm::append_range(AllCalls, Node->MatchingCalls);
2937
2938 // First see if we can partition the calls by callee function, creating new
2939 // nodes to host each set of calls calling the same callees. This is
2940 // necessary for support indirect calls with ThinLTO, for which we
2941 // synthesized CallsiteInfo records for each target. They will all have the
2942 // same callsite stack ids and would be sharing a context node at this
2943 // point. We need to perform separate cloning for each, which will be
2944 // applied along with speculative devirtualization in the ThinLTO backends
2945 // as needed. Note this does not currently support looking through tail
2946 // calls, it is unclear if we need that for indirect call targets.
2947 // First partition calls by callee func. Map indexed by func, value is
2948 // struct with list of matching calls, assigned node.
2949 if (partitionCallsByCallee(Node, AllCalls, NewCallToNode))
2950 continue;
2951
2952 auto It = AllCalls.begin();
2953 // Iterate through the calls until we find the first that matches.
2954 for (; It != AllCalls.end(); ++It) {
2955 auto ThisCall = *It;
2956 bool Match = true;
2957 for (auto EI = Node->CalleeEdges.begin(); EI != Node->CalleeEdges.end();
2958 ++EI) {
2959 auto Edge = *EI;
2960 if (!Edge->Callee->hasCall())
2961 continue;
2962 assert(NodeToCallingFunc.count(Edge->Callee));
2963 // Check if the called function matches that of the callee node.
2964 if (!calleesMatch(ThisCall.call(), EI, TailCallToContextNodeMap)) {
2965 Match = false;
2966 break;
2967 }
2968 }
2969 // Found a call that matches the callee nodes, we can quit now.
2970 if (Match) {
2971 // If the first match is not the primary call on the Node, update it
2972 // now. We will update the list of matching calls further below.
2973 if (Node->Call != ThisCall) {
2974 Node->setCall(ThisCall);
2975 // We need to update the NonAllocationCallToContextNodeMap, but don't
2976 // want to do this during iteration over that map, so save the calls
2977 // that need updated entries.
2978 NewCallToNode.push_back({ThisCall, Node});
2979 }
2980 break;
2981 }
2982 }
2983 // We will update this list below (or leave it cleared if there was no
2984 // match found above).
2985 Node->MatchingCalls.clear();
2986 // If we hit the end of the AllCalls vector, no call matching the callee
2987 // nodes was found, clear the call information in the node.
2988 if (It == AllCalls.end()) {
2989 RemovedEdgesWithMismatchedCallees++;
2990 // Work around by setting Node to have a null call, so it gets
2991 // skipped during cloning. Otherwise assignFunctions will assert
2992 // because its data structures are not designed to handle this case.
2993 Node->setCall(CallInfo());
2994 continue;
2995 }
2996 // Now add back any matching calls that call the same function as the
2997 // matching primary call on Node.
2998 for (++It; It != AllCalls.end(); ++It) {
2999 auto ThisCall = *It;
3000 if (!sameCallee(Node->Call.call(), ThisCall.call()))
3001 continue;
3002 Node->MatchingCalls.push_back(ThisCall);
3003 }
3004 }
3005
3006 // Remove all mismatched nodes identified in the above loop from the node map
3007 // (checking whether they have a null call which is set above). For a
3008 // MapVector like NonAllocationCallToContextNodeMap it is much more efficient
3009 // to do the removal via remove_if than by individually erasing entries above.
3010 // Also remove any entries if we updated the node's primary call above.
3011 NonAllocationCallToContextNodeMap.remove_if([](const auto &it) {
3012 return !it.second->hasCall() || it.second->Call != it.first;
3013 });
3014
3015 // Add entries for any new primary calls recorded above.
3016 for (auto &[Call, Node] : NewCallToNode)
3017 NonAllocationCallToContextNodeMap[Call] = Node;
3018
3019 // Add the new nodes after the above loop so that the iteration is not
3020 // invalidated.
3021 for (auto &[Call, Node] : TailCallToContextNodeMap)
3022 NonAllocationCallToContextNodeMap[Call] = Node;
3023}
3024
3025template <typename DerivedCCG, typename FuncTy, typename CallTy>
3026bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::partitionCallsByCallee(
3027 ContextNode *Node, ArrayRef<CallInfo> AllCalls,
3028 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode) {
3029 // Struct to keep track of all the calls having the same callee function,
3030 // and the node we eventually assign to them. Eventually we will record the
3031 // context node assigned to this group of calls.
3032 struct CallsWithSameCallee {
3033 std::vector<CallInfo> Calls;
3034 ContextNode *Node = nullptr;
3035 };
3036
3037 // First partition calls by callee function. Build map from each function
3038 // to the list of matching calls.
3040 for (auto ThisCall : AllCalls) {
3041 auto *F = getCalleeFunc(ThisCall.call());
3042 if (F)
3043 CalleeFuncToCallInfo[F].Calls.push_back(ThisCall);
3044 }
3045
3046 // Next, walk through all callee edges. For each callee node, get its
3047 // containing function and see if it was recorded in the above map (meaning we
3048 // have at least one matching call). Build another map from each callee node
3049 // with a matching call to the structure instance created above containing all
3050 // the calls.
3052 for (const auto &Edge : Node->CalleeEdges) {
3053 if (!Edge->Callee->hasCall())
3054 continue;
3055 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[Edge->Callee];
3056 if (CalleeFuncToCallInfo.contains(ProfiledCalleeFunc))
3057 CalleeNodeToCallInfo[Edge->Callee] =
3058 &CalleeFuncToCallInfo[ProfiledCalleeFunc];
3059 }
3060
3061 // If there are entries in the second map, then there were no matching
3062 // calls/callees, nothing to do here. Return so we can go to the handling that
3063 // looks through tail calls.
3064 if (CalleeNodeToCallInfo.empty())
3065 return false;
3066
3067 // Walk through all callee edges again. Any and all callee edges that didn't
3068 // match any calls (callee not in the CalleeNodeToCallInfo map) are moved to a
3069 // new caller node (UnmatchedCalleesNode) which gets a null call so that it is
3070 // ignored during cloning. If it is in the map, then we use the node recorded
3071 // in that entry (creating it if needed), and move the callee edge to it.
3072 // The first callee will use the original node instead of creating a new one.
3073 // Note that any of the original calls on this node (in AllCalls) that didn't
3074 // have a callee function automatically get dropped from the node as part of
3075 // this process.
3076 ContextNode *UnmatchedCalleesNode = nullptr;
3077 // Track whether we already assigned original node to a callee.
3078 bool UsedOrigNode = false;
3079 assert(NodeToCallingFunc[Node]);
3080 // Iterate over a copy of Node's callee edges, since we may need to remove
3081 // edges in moveCalleeEdgeToNewCaller, and this simplifies the handling and
3082 // makes it less error-prone.
3083 auto CalleeEdges = Node->CalleeEdges;
3084 for (auto &Edge : CalleeEdges) {
3085 if (!Edge->Callee->hasCall())
3086 continue;
3087
3088 // Will be updated below to point to whatever (caller) node this callee edge
3089 // should be moved to.
3090 ContextNode *CallerNodeToUse = nullptr;
3091
3092 // Handle the case where there were no matching calls first. Move this
3093 // callee edge to the UnmatchedCalleesNode, creating it if needed.
3094 if (!CalleeNodeToCallInfo.contains(Edge->Callee)) {
3095 if (!UnmatchedCalleesNode)
3096 UnmatchedCalleesNode =
3097 createNewNode(/*IsAllocation=*/false, NodeToCallingFunc[Node]);
3098 CallerNodeToUse = UnmatchedCalleesNode;
3099 } else {
3100 // Look up the information recorded for this callee node, and use the
3101 // recorded caller node (creating it if needed).
3102 auto *Info = CalleeNodeToCallInfo[Edge->Callee];
3103 if (!Info->Node) {
3104 // If we haven't assigned any callees to the original node use it.
3105 if (!UsedOrigNode) {
3106 Info->Node = Node;
3107 // Clear the set of matching calls which will be updated below.
3108 Node->MatchingCalls.clear();
3109 UsedOrigNode = true;
3110 } else
3111 Info->Node =
3112 createNewNode(/*IsAllocation=*/false, NodeToCallingFunc[Node]);
3113 assert(!Info->Calls.empty());
3114 // The first call becomes the primary call for this caller node, and the
3115 // rest go in the matching calls list.
3116 Info->Node->setCall(Info->Calls.front());
3117 llvm::append_range(Info->Node->MatchingCalls,
3118 llvm::drop_begin(Info->Calls));
3119 // Save the primary call to node correspondence so that we can update
3120 // the NonAllocationCallToContextNodeMap, which is being iterated in the
3121 // caller of this function.
3122 NewCallToNode.push_back({Info->Node->Call, Info->Node});
3123 }
3124 CallerNodeToUse = Info->Node;
3125 }
3126
3127 // Don't need to move edge if we are using the original node;
3128 if (CallerNodeToUse == Node)
3129 continue;
3130
3131 moveCalleeEdgeToNewCaller(Edge, CallerNodeToUse);
3132 }
3133 // Now that we are done moving edges, clean up any caller edges that ended
3134 // up with no type or context ids. During moveCalleeEdgeToNewCaller all
3135 // caller edges from Node are replicated onto the new callers, and it
3136 // simplifies the handling to leave them until we have moved all
3137 // edges/context ids.
3138 for (auto &I : CalleeNodeToCallInfo)
3139 removeNoneTypeCallerEdges(I.second->Node);
3140 if (UnmatchedCalleesNode)
3141 removeNoneTypeCallerEdges(UnmatchedCalleesNode);
3142 removeNoneTypeCallerEdges(Node);
3143
3144 return true;
3145}
3146
3147uint64_t ModuleCallsiteContextGraph::getStackId(uint64_t IdOrIndex) const {
3148 // In the Module (IR) case this is already the Id.
3149 return IdOrIndex;
3150}
3151
3152uint64_t IndexCallsiteContextGraph::getStackId(uint64_t IdOrIndex) const {
3153 // In the Index case this is an index into the stack id list in the summary
3154 // index, convert it to an Id.
3155 return Index.getStackIdAtIndex(IdOrIndex);
3156}
3157
3158template <typename DerivedCCG, typename FuncTy, typename CallTy>
3159bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::calleesMatch(
3160 CallTy Call, EdgeIter &EI,
3161 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap) {
3162 auto Edge = *EI;
3163 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[Edge->Callee];
3164 const FuncTy *CallerFunc = NodeToCallingFunc[Edge->Caller];
3165 // Will be populated in order of callee to caller if we find a chain of tail
3166 // calls between the profiled caller and callee.
3167 std::vector<std::pair<CallTy, FuncTy *>> FoundCalleeChain;
3168 if (!calleeMatchesFunc(Call, ProfiledCalleeFunc, CallerFunc,
3169 FoundCalleeChain))
3170 return false;
3171
3172 // The usual case where the profiled callee matches that of the IR/summary.
3173 if (FoundCalleeChain.empty())
3174 return true;
3175
3176 auto AddEdge = [Edge, &EI](ContextNode *Caller, ContextNode *Callee) {
3177 auto *CurEdge = Callee->findEdgeFromCaller(Caller);
3178 // If there is already an edge between these nodes, simply update it and
3179 // return.
3180 if (CurEdge) {
3181 CurEdge->ContextIds.insert_range(Edge->ContextIds);
3182 CurEdge->AllocTypes |= Edge->AllocTypes;
3183 return;
3184 }
3185 // Otherwise, create a new edge and insert it into the caller and callee
3186 // lists.
3187 auto NewEdge = std::make_shared<ContextEdge>(
3188 Callee, Caller, Edge->AllocTypes, Edge->ContextIds);
3189 Callee->CallerEdges.push_back(NewEdge);
3190 if (Caller == Edge->Caller) {
3191 // If we are inserting the new edge into the current edge's caller, insert
3192 // the new edge before the current iterator position, and then increment
3193 // back to the current edge.
3194 EI = Caller->CalleeEdges.insert(EI, NewEdge);
3195 ++EI;
3196 assert(*EI == Edge &&
3197 "Iterator position not restored after insert and increment");
3198 } else
3199 Caller->CalleeEdges.push_back(NewEdge);
3200 };
3201
3202 // Create new nodes for each found callee and connect in between the profiled
3203 // caller and callee.
3204 auto *CurCalleeNode = Edge->Callee;
3205 for (auto &[NewCall, Func] : FoundCalleeChain) {
3206 ContextNode *NewNode = nullptr;
3207 // First check if we have already synthesized a node for this tail call.
3208 if (TailCallToContextNodeMap.count(NewCall)) {
3209 NewNode = TailCallToContextNodeMap[NewCall];
3210 NewNode->AllocTypes |= Edge->AllocTypes;
3211 } else {
3212 FuncToCallsWithMetadata[Func].push_back({NewCall});
3213 // Create Node and record node info.
3214 NewNode = createNewNode(/*IsAllocation=*/false, Func, NewCall);
3215 TailCallToContextNodeMap[NewCall] = NewNode;
3216 NewNode->AllocTypes = Edge->AllocTypes;
3217 }
3218
3219 // Hook up node to its callee node
3220 AddEdge(NewNode, CurCalleeNode);
3221
3222 CurCalleeNode = NewNode;
3223 }
3224
3225 // Hook up edge's original caller to new callee node.
3226 AddEdge(Edge->Caller, CurCalleeNode);
3227
3228#ifndef NDEBUG
3229 // Save this because Edge's fields get cleared below when removed.
3230 auto *Caller = Edge->Caller;
3231#endif
3232
3233 // Remove old edge
3234 removeEdgeFromGraph(Edge.get(), &EI, /*CalleeIter=*/true);
3235
3236 // To simplify the increment of EI in the caller, subtract one from EI.
3237 // In the final AddEdge call we would have either added a new callee edge,
3238 // to Edge->Caller, or found an existing one. Either way we are guaranteed
3239 // that there is at least one callee edge.
3240 assert(!Caller->CalleeEdges.empty());
3241 --EI;
3242
3243 return true;
3244}
3245
3246bool ModuleCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3247 const Function *ProfiledCallee, Value *CurCallee, unsigned Depth,
3248 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
3249 bool &FoundMultipleCalleeChains) {
3250 // Stop recursive search if we have already explored the maximum specified
3251 // depth.
3253 return false;
3254
3255 auto SaveCallsiteInfo = [&](Instruction *Callsite, Function *F) {
3256 FoundCalleeChain.push_back({Callsite, F});
3257 };
3258
3259 auto *CalleeFunc = dyn_cast<Function>(CurCallee);
3260 if (!CalleeFunc) {
3261 auto *Alias = dyn_cast<GlobalAlias>(CurCallee);
3262 assert(Alias);
3263 CalleeFunc = dyn_cast<Function>(Alias->getAliasee());
3264 assert(CalleeFunc);
3265 }
3266
3267 // Look for tail calls in this function, and check if they either call the
3268 // profiled callee directly, or indirectly (via a recursive search).
3269 // Only succeed if there is a single unique tail call chain found between the
3270 // profiled caller and callee, otherwise we could perform incorrect cloning.
3271 bool FoundSingleCalleeChain = false;
3272 for (auto &BB : *CalleeFunc) {
3273 for (auto &I : BB) {
3274 auto *CB = dyn_cast<CallBase>(&I);
3275 if (!CB || !CB->isTailCall())
3276 continue;
3277 auto *CalledValue = CB->getCalledOperand();
3278 auto *CalledFunction = CB->getCalledFunction();
3279 if (CalledValue && !CalledFunction) {
3280 CalledValue = CalledValue->stripPointerCasts();
3281 // Stripping pointer casts can reveal a called function.
3282 CalledFunction = dyn_cast<Function>(CalledValue);
3283 }
3284 // Check if this is an alias to a function. If so, get the
3285 // called aliasee for the checks below.
3286 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
3287 assert(!CalledFunction &&
3288 "Expected null called function in callsite for alias");
3289 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
3290 }
3291 if (!CalledFunction)
3292 continue;
3293 if (CalledFunction == ProfiledCallee) {
3294 if (FoundSingleCalleeChain) {
3295 FoundMultipleCalleeChains = true;
3296 return false;
3297 }
3298 FoundSingleCalleeChain = true;
3299 FoundProfiledCalleeCount++;
3300 FoundProfiledCalleeDepth += Depth;
3301 if (Depth > FoundProfiledCalleeMaxDepth)
3302 FoundProfiledCalleeMaxDepth = Depth;
3303 SaveCallsiteInfo(&I, CalleeFunc);
3304 } else if (findProfiledCalleeThroughTailCalls(
3305 ProfiledCallee, CalledFunction, Depth + 1,
3306 FoundCalleeChain, FoundMultipleCalleeChains)) {
3307 // findProfiledCalleeThroughTailCalls should not have returned
3308 // true if FoundMultipleCalleeChains.
3309 assert(!FoundMultipleCalleeChains);
3310 if (FoundSingleCalleeChain) {
3311 FoundMultipleCalleeChains = true;
3312 return false;
3313 }
3314 FoundSingleCalleeChain = true;
3315 SaveCallsiteInfo(&I, CalleeFunc);
3316 } else if (FoundMultipleCalleeChains)
3317 return false;
3318 }
3319 }
3320
3321 return FoundSingleCalleeChain;
3322}
3323
3324const Function *ModuleCallsiteContextGraph::getCalleeFunc(Instruction *Call) {
3325 auto *CB = dyn_cast<CallBase>(Call);
3326 if (!CB->getCalledOperand() || CB->isIndirectCall())
3327 return nullptr;
3328 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3329 auto *Alias = dyn_cast<GlobalAlias>(CalleeVal);
3330 if (Alias)
3331 return dyn_cast<Function>(Alias->getAliasee());
3332 return dyn_cast<Function>(CalleeVal);
3333}
3334
3335bool ModuleCallsiteContextGraph::calleeMatchesFunc(
3336 Instruction *Call, const Function *Func, const Function *CallerFunc,
3337 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain) {
3338 auto *CB = dyn_cast<CallBase>(Call);
3339 if (!CB->getCalledOperand() || CB->isIndirectCall())
3340 return false;
3341 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3342 auto *CalleeFunc = dyn_cast<Function>(CalleeVal);
3343 if (CalleeFunc == Func)
3344 return true;
3345 auto *Alias = dyn_cast<GlobalAlias>(CalleeVal);
3346 if (Alias && Alias->getAliasee() == Func)
3347 return true;
3348
3349 // Recursively search for the profiled callee through tail calls starting with
3350 // the actual Callee. The discovered tail call chain is saved in
3351 // FoundCalleeChain, and we will fixup the graph to include these callsites
3352 // after returning.
3353 // FIXME: We will currently redo the same recursive walk if we find the same
3354 // mismatched callee from another callsite. We can improve this with more
3355 // bookkeeping of the created chain of new nodes for each mismatch.
3356 unsigned Depth = 1;
3357 bool FoundMultipleCalleeChains = false;
3358 if (!findProfiledCalleeThroughTailCalls(Func, CalleeVal, Depth,
3359 FoundCalleeChain,
3360 FoundMultipleCalleeChains)) {
3361 LLVM_DEBUG(dbgs() << "Not found through unique tail call chain: "
3362 << Func->getName() << " from " << CallerFunc->getName()
3363 << " that actually called " << CalleeVal->getName()
3364 << (FoundMultipleCalleeChains
3365 ? " (found multiple possible chains)"
3366 : "")
3367 << "\n");
3368 if (FoundMultipleCalleeChains)
3369 FoundProfiledCalleeNonUniquelyCount++;
3370 return false;
3371 }
3372
3373 return true;
3374}
3375
3376bool ModuleCallsiteContextGraph::sameCallee(Instruction *Call1,
3377 Instruction *Call2) {
3378 auto *CB1 = cast<CallBase>(Call1);
3379 if (!CB1->getCalledOperand() || CB1->isIndirectCall())
3380 return false;
3381 auto *CalleeVal1 = CB1->getCalledOperand()->stripPointerCasts();
3382 auto *CalleeFunc1 = dyn_cast<Function>(CalleeVal1);
3383 auto *CB2 = cast<CallBase>(Call2);
3384 if (!CB2->getCalledOperand() || CB2->isIndirectCall())
3385 return false;
3386 auto *CalleeVal2 = CB2->getCalledOperand()->stripPointerCasts();
3387 auto *CalleeFunc2 = dyn_cast<Function>(CalleeVal2);
3388 return CalleeFunc1 == CalleeFunc2;
3389}
3390
3391bool IndexCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3392 ValueInfo ProfiledCallee, ValueInfo CurCallee, unsigned Depth,
3393 std::vector<std::pair<ValueInfo, FunctionSummary *>> &FoundCalleeChain,
3394 bool &FoundMultipleCalleeChains) {
3395 // Stop recursive search if we have already explored the maximum specified
3396 // depth.
3398 return false;
3399
3400 // Record each discovered tail call (callee and calling function) in the
3401 // chain. The CallsiteInfo records are only synthesized by the caller once
3402 // the search succeeds, since the chain is discarded if the profiled callee
3403 // is found through multiple chains.
3404 auto SaveTailCall = [&](ValueInfo Callee, FunctionSummary *FS) {
3405 FoundCalleeChain.push_back({Callee, FS});
3406 };
3407
3408 // Look for tail calls in this function, and check if they either call the
3409 // profiled callee directly, or indirectly (via a recursive search).
3410 // Only succeed if there is a single unique tail call chain found between the
3411 // profiled caller and callee, otherwise we could perform incorrect cloning.
3412 bool FoundSingleCalleeChain = false;
3413 for (auto &S : CurCallee.getSummaryList()) {
3414 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
3415 !isPrevailing(CurCallee.getGUID(), S.get()))
3416 continue;
3417 auto *FS = dyn_cast<FunctionSummary>(S->getBaseObject());
3418 if (!FS)
3419 continue;
3420 auto FSVI = CurCallee;
3421 auto *AS = dyn_cast<AliasSummary>(S.get());
3422 if (AS)
3423 FSVI = AS->getAliaseeVI();
3424 for (auto &CallEdge : FS->calls()) {
3425 if (!CallEdge.second.hasTailCall())
3426 continue;
3427 // Edges marked indirect are the profiled targets of indirect calls.
3428 // If the tail call is indirect, the ThinLTO backend will perform
3429 // ICP to the target in order to call a clone of it.
3430 if (CallEdge.second.hasIndirectCall() && !IndirectTailCallSearch)
3431 continue;
3432 if (CallEdge.first == ProfiledCallee) {
3433 if (FoundSingleCalleeChain) {
3434 FoundMultipleCalleeChains = true;
3435 return false;
3436 }
3437 FoundSingleCalleeChain = true;
3438 FoundProfiledCalleeCount++;
3439 FoundProfiledCalleeDepth += Depth;
3440 if (Depth > FoundProfiledCalleeMaxDepth)
3441 FoundProfiledCalleeMaxDepth = Depth;
3442 if (CallEdge.second.hasIndirectCall())
3443 FoundProfiledCalleeIndirectTailCallCount++;
3444 SaveTailCall(CallEdge.first, FS);
3445 // Add FS to FSToVIMap in case it isn't already there.
3446 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3447 FSToVIMap[FS] = FSVI;
3448 } else if (findProfiledCalleeThroughTailCalls(
3449 ProfiledCallee, CallEdge.first, Depth + 1,
3450 FoundCalleeChain, FoundMultipleCalleeChains)) {
3451 // findProfiledCalleeThroughTailCalls should not have returned
3452 // true if FoundMultipleCalleeChains.
3453 assert(!FoundMultipleCalleeChains);
3454 if (FoundSingleCalleeChain) {
3455 FoundMultipleCalleeChains = true;
3456 return false;
3457 }
3458 FoundSingleCalleeChain = true;
3459 if (CallEdge.second.hasIndirectCall())
3460 FoundProfiledCalleeIndirectTailCallCount++;
3461 SaveTailCall(CallEdge.first, FS);
3462 // Add FS to FSToVIMap in case it isn't already there.
3463 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3464 FSToVIMap[FS] = FSVI;
3465 } else if (FoundMultipleCalleeChains)
3466 return false;
3467 }
3468 }
3469
3470 return FoundSingleCalleeChain;
3471}
3472
3473const FunctionSummary *
3474IndexCallsiteContextGraph::getCalleeFunc(IndexCall &Call) {
3475 ValueInfo Callee = dyn_cast_if_present<CallsiteInfo *>(Call)->Callee;
3476 if (Callee.getSummaryList().empty())
3477 return nullptr;
3478 return dyn_cast<FunctionSummary>(Callee.getSummaryList()[0]->getBaseObject());
3479}
3480
3481bool IndexCallsiteContextGraph::calleeMatchesFunc(
3482 IndexCall &Call, const FunctionSummary *Func,
3483 const FunctionSummary *CallerFunc,
3484 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain) {
3485 ValueInfo Callee = dyn_cast_if_present<CallsiteInfo *>(Call)->Callee;
3486 // If there is no summary list then this is a call to an externally defined
3487 // symbol.
3488 AliasSummary *Alias =
3489 Callee.getSummaryList().empty()
3490 ? nullptr
3491 : dyn_cast<AliasSummary>(Callee.getSummaryList()[0].get());
3492 assert(FSToVIMap.count(Func));
3493 auto FuncVI = FSToVIMap[Func];
3494 if (Callee == FuncVI ||
3495 // If callee is an alias, check the aliasee, since only function
3496 // summary base objects will contain the stack node summaries and thus
3497 // get a context node.
3498 (Alias && Alias->getAliaseeVI() == FuncVI))
3499 return true;
3500
3501 // Recursively search for the profiled callee through tail calls starting with
3502 // the actual Callee. The discovered tail call chain is saved in
3503 // FoundCalleeChain, and we will fixup the graph to include these callsites
3504 // after returning.
3505 // FIXME: We will currently redo the same recursive walk if we find the same
3506 // mismatched callee from another callsite. We can improve this with more
3507 // bookkeeping of the created chain of new nodes for each mismatch.
3508 unsigned Depth = 1;
3509 bool FoundMultipleCalleeChains = false;
3510 std::vector<std::pair<ValueInfo, FunctionSummary *>> FoundCalleeVIChain;
3511 if (!findProfiledCalleeThroughTailCalls(FuncVI, Callee, Depth,
3512 FoundCalleeVIChain,
3513 FoundMultipleCalleeChains)) {
3514 LLVM_DEBUG(dbgs() << "Not found through unique tail call chain: " << FuncVI
3515 << " from " << FSToVIMap[CallerFunc]
3516 << " that actually called " << Callee
3517 << (FoundMultipleCalleeChains
3518 ? " (found multiple possible chains)"
3519 : "")
3520 << "\n");
3521 if (FoundMultipleCalleeChains)
3522 FoundProfiledCalleeNonUniquelyCount++;
3523 return false;
3524 }
3525
3526 // Now that we know the chain is unique, synthesize a CallsiteInfo for each
3527 // tail call in it, if one hasn't already been synthesized (e.g. for a chain
3528 // to a different profiled callee through the same tail call). These are only
3529 // added to the function summaries once the graph is destroyed (see
3530 // ~IndexCallsiteContextGraph).
3531 for (auto &[CalleeVI, FS] : FoundCalleeVIChain) {
3532 auto &CallsiteInfoPtr =
3533 FunctionCalleesToSynthesizedCallsiteInfos[FS][CalleeVI];
3534 if (!CallsiteInfoPtr)
3535 // StackIds is empty (we don't have debug info available in the index for
3536 // these callsites)
3537 CallsiteInfoPtr =
3538 std::make_unique<CallsiteInfo>(CalleeVI, SmallVector<unsigned>());
3539 FoundCalleeChain.push_back({CallsiteInfoPtr.get(), FS});
3540 }
3541
3542 return true;
3543}
3544
3545bool IndexCallsiteContextGraph::sameCallee(IndexCall &Call1, IndexCall &Call2) {
3546 ValueInfo Callee1 = dyn_cast_if_present<CallsiteInfo *>(Call1)->Callee;
3547 ValueInfo Callee2 = dyn_cast_if_present<CallsiteInfo *>(Call2)->Callee;
3548 return Callee1 == Callee2;
3549}
3550
3551template <typename DerivedCCG, typename FuncTy, typename CallTy>
3552void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::dump()
3553 const {
3554 print(dbgs());
3555 dbgs() << "\n";
3556}
3557
3558template <typename DerivedCCG, typename FuncTy, typename CallTy>
3559void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::print(
3560 raw_ostream &OS) const {
3561 OS << "Node " << this << "\n";
3562 OS << "\t";
3563 printCall(OS);
3564 if (Recursive)
3565 OS << " (recursive)";
3566 OS << "\n";
3567 if (!MatchingCalls.empty()) {
3568 OS << "\tMatchingCalls:\n";
3569 for (auto &MatchingCall : MatchingCalls) {
3570 OS << "\t";
3571 MatchingCall.print(OS);
3572 OS << "\n";
3573 }
3574 }
3575 OS << "\tNodeId: " << NodeId << "\n";
3576 OS << "\tAllocTypes: " << getAllocTypeString(AllocTypes) << "\n";
3577 OS << "\tContextIds:";
3578 // Make a copy of the computed context ids that we can sort for stability.
3579 auto ContextIds = getContextIds();
3580 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3581 std::sort(SortedIds.begin(), SortedIds.end());
3582 for (auto Id : SortedIds)
3583 OS << " " << Id;
3584 OS << "\n";
3585 OS << "\tCalleeEdges:\n";
3586 for (auto &Edge : CalleeEdges)
3587 OS << "\t\t" << *Edge << " (Callee NodeId: " << Edge->Callee->NodeId
3588 << ")\n";
3589 OS << "\tCallerEdges:\n";
3590 for (auto &Edge : CallerEdges)
3591 OS << "\t\t" << *Edge << " (Caller NodeId: " << Edge->Caller->NodeId
3592 << ")\n";
3593 if (!Clones.empty()) {
3594 OS << "\tClones: ";
3595 ListSeparator LS;
3596 for (auto *C : Clones)
3597 OS << LS << C << " NodeId: " << C->NodeId;
3598 OS << "\n";
3599 } else if (CloneOf) {
3600 OS << "\tClone of " << CloneOf << " NodeId: " << CloneOf->NodeId << "\n";
3601 }
3602}
3603
3604template <typename DerivedCCG, typename FuncTy, typename CallTy>
3605void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::dump()
3606 const {
3607 print(dbgs());
3608 dbgs() << "\n";
3609}
3610
3611template <typename DerivedCCG, typename FuncTy, typename CallTy>
3612void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::print(
3613 raw_ostream &OS) const {
3614 OS << "Edge from Callee " << Callee << " to Caller: " << Caller
3615 << (IsBackedge ? " (BE)" : "")
3616 << " AllocTypes: " << getAllocTypeString(AllocTypes);
3617 OS << " ContextIds:";
3618 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3619 std::sort(SortedIds.begin(), SortedIds.end());
3620 for (auto Id : SortedIds)
3621 OS << " " << Id;
3622}
3623
3624template <typename DerivedCCG, typename FuncTy, typename CallTy>
3625void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::dump() const {
3626 print(dbgs());
3627}
3628
3629template <typename DerivedCCG, typename FuncTy, typename CallTy>
3630void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::print(
3631 raw_ostream &OS) const {
3632 OS << "Callsite Context Graph:\n";
3633 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3634 for (const auto Node : nodes<GraphType>(this)) {
3635 if (Node->isRemoved())
3636 continue;
3637 Node->print(OS);
3638 OS << "\n";
3639 }
3640}
3641
3642template <typename DerivedCCG, typename FuncTy, typename CallTy>
3643void CallsiteContextGraph<DerivedCCG, FuncTy,
3644 CallTy>::capturePreCloningContextInfo() {
3645 for (const auto &Entry : AllocationCallToContextNodeMap) {
3646 const ContextNode *AllocNode = Entry.second;
3647 // Remember whether any caller of this allocation matched a call, so that
3648 // the report can distinguish "no matched callers" from an allocation whose
3649 // callers are simply not part of this context.
3650 for (const auto &Edge : AllocNode->CallerEdges) {
3651 if (!Edge->isRemoved() && Edge->Caller->hasCall()) {
3652 PreCloningAllocHasMatchedCaller.insert(AllocNode);
3653 break;
3654 }
3655 }
3656 DenseSet<uint32_t> ContextIds = AllocNode->getContextIds();
3657 for (uint32_t Id : ContextIds) {
3658 PreCloningContextInfo Info;
3659 // Walk the caller edges carrying this context id from the allocation
3660 // node outwards to build the chain of nodes for this context. Each node
3661 // is visited once; backedges (recursive cycles) are only followed when
3662 // no other caller edge carries the id, so that the chain reflects the
3663 // context's stack order rather than looping.
3664 Info.Chain.push_back(AllocNode);
3665 SmallPtrSet<const ContextNode *, 16> Visited;
3666 Visited.insert(AllocNode);
3667 const ContextNode *Cur = AllocNode;
3668 while (true) {
3669 const ContextNode *Next = nullptr;
3670 for (const auto &Edge : Cur->CallerEdges) {
3671 if (Edge->isRemoved() || Edge->IsBackedge)
3672 continue;
3673 if (Edge->getContextIds().contains(Id) &&
3674 !Visited.contains(Edge->Caller)) {
3675 Next = Edge->Caller;
3676 break;
3677 }
3678 }
3679 if (!Next) {
3680 for (const auto &Edge : Cur->CallerEdges) {
3681 if (Edge->isRemoved())
3682 continue;
3683 if (Edge->getContextIds().contains(Id) &&
3684 !Visited.contains(Edge->Caller)) {
3685 Next = Edge->Caller;
3686 break;
3687 }
3688 }
3689 }
3690 if (!Next)
3691 break;
3692 Visited.insert(Next);
3693 Info.Chain.push_back(Next);
3694 Cur = Next;
3695 }
3696
3697 // Find the outermost node (walking from the allocation) such that it
3698 // and all nodes below it matched a call, and record why the first
3699 // unmatched node (if any) did not match.
3700 Info.MaxMatchedFrame = 0;
3701 for (unsigned I = 1; I < Info.Chain.size(); ++I) {
3702 if (Info.Chain[I]->hasCall()) {
3703 Info.MaxMatchedFrame = I;
3704 } else {
3705 const ContextNode *Unmatched = Info.Chain[I];
3706 Info.UnmatchedStackId = Unmatched->OrigStackOrAllocId;
3707 Info.StoppedAtRecursive = Unmatched->Recursive;
3708 // A calling function is known for the unmatched node only when a
3709 // call in that function was considered and rejected because its
3710 // callee did not match the node's callee.
3711 if (auto It = NodeToCallingFunc.find(Unmatched);
3712 It != NodeToCallingFunc.end()) {
3713 Info.StoppedAtMismatchedCallee = true;
3714 Info.UnmatchedCallingFunc = It->second;
3715 }
3716 break;
3717 }
3718 }
3719
3720 // If the whole context matched, check whether its outermost node has
3721 // matched callers reached by other contexts: then this context was
3722 // trimmed below them, and clones of those callers can change which
3723 // allocation clone it reaches.
3724 if (Info.MaxMatchedFrame > 0 &&
3725 Info.MaxMatchedFrame + 1 == Info.Chain.size()) {
3726 const ContextNode *OutermostMatchedNode =
3727 Info.Chain[Info.MaxMatchedFrame];
3728 for (const auto &Edge : OutermostMatchedNode->CallerEdges) {
3729 if (!Edge->isRemoved() && Edge->Caller->hasCall()) {
3730 Info.OutermostMatchedNodeHasOtherCallers = true;
3731 break;
3732 }
3733 }
3734 }
3735
3736 PreCloningContextInfoMap[Id] = std::move(Info);
3737 }
3738 }
3739}
3740
3741template <typename DerivedCCG, typename FuncTy, typename CallTy>
3742std::string
3743CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::formatContextReportSuffix(
3744 const ContextNode *Node, uint32_t Id) const {
3745 auto InfoIt = PreCloningContextInfoMap.find(Id);
3746 if (InfoIt == PreCloningContextInfoMap.end())
3747 return "";
3748 const PreCloningContextInfo &Info = InfoIt->second;
3749
3750 // 1. The allocation function (clone) the context's allocation node ended up
3751 // in, with a qualifier when it is dead, or when the context has callers in
3752 // the profile but none of the allocation's callers matched (either because
3753 // nothing references the function at all, or because the references did not
3754 // match the profiled callsites).
3755 const ContextNode *OrigAlloc = Node->getOrigNode();
3756 const FuncTy *AllocFunc = getCallingFunc(OrigAlloc);
3757 unsigned AllocCloneNo = Node->Call.cloneNo();
3758 std::string AllocFuncStr = getFuncName(AllocFunc, AllocCloneNo);
3759 if (isFuncDead(AllocFunc)) {
3760 AllocFuncStr += " (dead)";
3761 } else if (!PreCloningAllocHasMatchedCaller.contains(OrigAlloc) &&
3762 Info.Chain.size() > 1) {
3763 // Distinguish a function with no references in the IR/summary (it may
3764 // still be referenced from native objects) from one whose references did
3765 // not match.
3766 AllocFuncStr += AllocFunc && !FunctionsWithCallers.contains(AllocFunc)
3767 ? " (no references in IR/summary)"
3768 : " (no matched callers)";
3769 }
3770
3771 // 2. How far the context matched: all of it ("matched N frames to F", or
3772 // "trimmed at frame N in F" when F has callers above that the context does
3773 // not cover), or up to an unmatched node (with the reason and stack id).
3774 unsigned TotalFrames = Info.Chain.size() > 0 ? Info.Chain.size() - 1 : 0;
3775 unsigned Matched = Info.MaxMatchedFrame;
3776 std::string StatusStr;
3777 if (TotalFrames == 0) {
3778 StatusStr = "inlined into leaf";
3779 } else if (Matched < TotalFrames) {
3780 // Where and why matching stopped: the first unmatched node was either a
3781 // recursive callsite (not matched when recursive callsites are disabled),
3782 // a callsite whose IR callee did not match the profiled callee, or a
3783 // callsite with no matching call at all.
3784 if (Info.StoppedAtRecursive)
3785 StatusStr = "unmatched recursive callsite";
3786 else if (Info.StoppedAtMismatchedCallee)
3787 StatusStr = "unmatched callsite (mismatched callee in " +
3788 getFuncName(Info.UnmatchedCallingFunc, 0) + ")";
3789 else
3790 StatusStr = "unmatched callsite";
3791 StatusStr += " at frame " + std::to_string(Matched + 1) + "/" +
3792 std::to_string(TotalFrames) + " (stack id " +
3793 std::to_string(Info.UnmatchedStackId) + ")";
3794 } else {
3795 const ContextNode *OutermostMatchedNode = Info.Chain[Matched];
3796 const FuncTy *OutermostMatchedFunc = getCallingFunc(OutermostMatchedNode);
3797 unsigned NumOutermostMatchedFuncClones =
3798 std::max<unsigned>(1, FuncToNumClones.lookup(OutermostMatchedFunc));
3799 bool HasCallersAbove =
3800 NumOutermostMatchedFuncClones > 1 ||
3801 Info.OutermostMatchedNodeHasOtherCallers ||
3802 (OutermostMatchedFunc &&
3803 FunctionsWithCallers.contains(OutermostMatchedFunc));
3804 if (HasCallersAbove) {
3805 StatusStr = "trimmed at frame " + std::to_string(Matched) + " in " +
3806 getFuncName(OutermostMatchedFunc, 0);
3807 } else {
3808 StatusStr = "matched " + std::to_string(Matched) + " frames to " +
3809 getFuncName(OutermostMatchedFunc, 0);
3810 }
3811 }
3812
3813 // 3. The post-cloning call paths: starting from each function clone of the
3814 // outermost matched caller, follow the callee clones assigned to the
3815 // context's callsites down to the allocation clone reached, and report the
3816 // hint that clone ended up with. Paths reaching the same allocation clone
3817 // are reported once.
3818 std::string ReachesStr;
3819 if (Matched >= 1) {
3820 const ContextNode *OutermostMatchedNode = Info.Chain[Matched];
3821 const FuncTy *OutermostMatchedFunc = getCallingFunc(OutermostMatchedNode);
3822 unsigned NumOutermostMatchedFuncClones =
3823 std::max<unsigned>(1, FuncToNumClones.lookup(OutermostMatchedFunc));
3824 ReachesStr = "; reaches ";
3825 // Allocation clones (by clone number) already reported for this context.
3826 // Different function clones of the outermost matched caller often lead to
3827 // the same allocation clone; such paths are reported only once, for the
3828 // first caller clone reaching that allocation clone.
3829 SmallSet<unsigned, 4> ReportedAllocClones;
3830 bool FirstPath = true;
3831 for (unsigned OutermostMatchedFuncClone = 0;
3832 OutermostMatchedFuncClone < NumOutermostMatchedFuncClones;
3833 ++OutermostMatchedFuncClone) {
3834 // PathFuncs/PathClones[S] is the function and clone number at step S of
3835 // the path, from the outermost matched caller (S = 0) down to the
3836 // allocation function (S = Matched).
3837 std::vector<const FuncTy *> PathFuncs(Matched + 1);
3838 std::vector<unsigned> PathClones(Matched + 1);
3839 PathFuncs[0] = OutermostMatchedFunc;
3840 PathClones[0] = OutermostMatchedFuncClone;
3841 unsigned CurClone = OutermostMatchedFuncClone;
3842 for (unsigned Step = 0; Step < Matched; ++Step) {
3843 unsigned FrameIdx = Matched - Step;
3844 const ContextNode *CallNode = Info.Chain[FrameIdx];
3845 unsigned NextClone =
3846 OrigNodeAndCloneToCalleeClone.lookup({CallNode, CurClone});
3847 const FuncTy *CalleeFunc = getCallingFunc(Info.Chain[FrameIdx - 1]);
3848 PathFuncs[Step + 1] = CalleeFunc;
3849 PathClones[Step + 1] = NextClone;
3850 CurClone = NextClone;
3851 }
3852
3853 if (!ReportedAllocClones.insert(CurClone).second)
3854 continue;
3855 if (!FirstPath)
3856 ReachesStr += ", ";
3857 FirstPath = false;
3858
3859 const ContextNode *ReachedAlloc =
3860 OrigAllocAndCloneToNode.lookup({OrigAlloc, CurClone});
3861 // Report the hint actually applied to the reached allocation clone
3862 // (which accounts for allocTypeToUse and MinClonedColdBytePercent),
3863 // rather than the graph node's (possibly ambiguous) AllocTypes.
3864 std::string ReachedTypeStr;
3865 if (ReachedAlloc)
3866 ReachedTypeStr = getAllocTypeString(
3867 (uint8_t)getAllocationCallType(ReachedAlloc->Call));
3868 else if (CurClone == 0)
3869 ReachedTypeStr =
3870 getAllocTypeString((uint8_t)getAllocationCallType(OrigAlloc->Call));
3871 else
3872 ReachedTypeStr = "None";
3873
3874 // Print the path, eliding runs of uncloned (or cloned) functions in the
3875 // middle of paths longer than MemProfReportHintedSizesDetailMaxPathLen;
3876 // the ends and every transition between cloned and uncloned functions
3877 // are kept.
3878 std::string PathStr;
3879 bool SkippedPrev = false;
3880 bool PrintFullPath =
3882 for (unsigned S = 0; S <= Matched; ++S) {
3883 bool IsCloned = PathClones[S] > 0;
3884 bool PrevCloned = S > 0 ? (PathClones[S - 1] > 0) : IsCloned;
3885 bool NextCloned = S + 1 <= Matched ? (PathClones[S + 1] > 0) : IsCloned;
3886 bool Include = PrintFullPath || (S <= 1) || (S + 1 >= Matched) ||
3887 (IsCloned != PrevCloned) || (IsCloned != NextCloned);
3888 if (!Include) {
3889 if (!SkippedPrev) {
3890 PathStr += " -> ...";
3891 SkippedPrev = true;
3892 }
3893 continue;
3894 }
3895 SkippedPrev = false;
3896 if (!PathStr.empty())
3897 PathStr += " -> ";
3898 PathStr += getFuncName(PathFuncs[S], PathClones[S]);
3899 }
3900 ReachesStr += ReachedTypeStr + " via " + PathStr;
3901 }
3902 }
3903
3904 return " [alloc in " + AllocFuncStr + "; " + StatusStr + ReachesStr + "]";
3905}
3906
3907template <typename DerivedCCG, typename FuncTy, typename CallTy>
3908void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::printTotalSizes(
3909 raw_ostream &OS,
3910 function_ref<void(StringRef, StringRef, const Twine &)> EmitRemark) const {
3911 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3912 for (const auto Node : nodes<GraphType>(this)) {
3913 if (Node->isRemoved())
3914 continue;
3915 if (!Node->IsAllocation)
3916 continue;
3917 DenseSet<uint32_t> ContextIds = Node->getContextIds();
3918 auto AllocTypeFromCall = getAllocationCallType(Node->Call);
3919 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3920 std::sort(SortedIds.begin(), SortedIds.end());
3921 for (auto Id : SortedIds) {
3922 auto TypeI = ContextIdToAllocationType.find(Id);
3923 assert(TypeI != ContextIdToAllocationType.end());
3924 std::string Suffix;
3925 bool ComputedSuffix = false;
3926 auto GetSuffix = [&]() -> const std::string & {
3927 if (!ComputedSuffix) {
3929 ? formatContextReportSuffix(Node, Id)
3930 : "";
3931 ComputedSuffix = true;
3932 }
3933 return Suffix;
3934 };
3935 auto CSI = ContextIdToContextSizeInfos.find(Id);
3936 if (CSI != ContextIdToContextSizeInfos.end()) {
3937 for (auto &Info : CSI->second) {
3938 std::string Msg =
3939 "MemProf hinting: " + getAllocTypeString((uint8_t)TypeI->second) +
3940 " full allocation context " + std::to_string(Info.FullStackId) +
3941 " with total size " + std::to_string(Info.TotalSize) + " is " +
3942 getAllocTypeString(Node->AllocTypes) + " after cloning";
3943 if (allocTypeToUse(Node->AllocTypes) !=
3944 allocTypeToUse((uint8_t)AllocTypeFromCall))
3945 Msg += " marked " + getAllocTypeString((uint8_t)AllocTypeFromCall) +
3946 " due to cold byte percent";
3947 // Print the internal context id to aid debugging and visualization.
3948 Msg += " (internal context id " + std::to_string(Id) + ")";
3950 OS << Msg << GetSuffix() << "\n";
3951 if (EmitRemark)
3952 EmitRemark(DEBUG_TYPE, "MemProfReport", Msg);
3953 }
3954 } else {
3955 // This is only emitted if the context size info is not present.
3956 std::string Msg =
3957 "MemProf hinting: " + getAllocTypeString((uint8_t)TypeI->second) +
3958 " context is " + getAllocTypeString(Node->AllocTypes) +
3959 " after cloning";
3960 if (allocTypeToUse(Node->AllocTypes) !=
3961 allocTypeToUse((uint8_t)AllocTypeFromCall))
3962 Msg += " marked " + getAllocTypeString((uint8_t)AllocTypeFromCall) +
3963 " due to cold byte percent";
3964 // Print the internal context id to aid debugging and visualization.
3965 Msg += " (internal context id " + std::to_string(Id) + ")";
3967 OS << Msg << GetSuffix() << "\n";
3968 if (EmitRemark)
3969 EmitRemark(DEBUG_TYPE, "MemProfReport", Msg);
3970 }
3971 }
3972 }
3973}
3974
3975template <typename DerivedCCG, typename FuncTy, typename CallTy>
3976void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::check() const {
3977 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3978 for (const auto Node : nodes<GraphType>(this)) {
3979 checkNode<DerivedCCG, FuncTy, CallTy>(Node, /*CheckEdges=*/false);
3980 for (auto &Edge : Node->CallerEdges)
3982 }
3983}
3984
3985template <typename DerivedCCG, typename FuncTy, typename CallTy>
3986struct GraphTraits<const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *> {
3987 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3988 using NodeRef = const ContextNode<DerivedCCG, FuncTy, CallTy> *;
3989
3990 using NodePtrTy = std::unique_ptr<ContextNode<DerivedCCG, FuncTy, CallTy>>;
3991 static NodeRef getNode(const NodePtrTy &P) { return P.get(); }
3992
3995 decltype(&getNode)>;
3996
3998 return nodes_iterator(G->NodeOwner.begin(), &getNode);
3999 }
4000
4002 return nodes_iterator(G->NodeOwner.end(), &getNode);
4003 }
4004
4006 return G->NodeOwner.begin()->get();
4007 }
4008
4009 using EdgePtrTy = std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>;
4010 static const ContextNode<DerivedCCG, FuncTy, CallTy> *
4012 return P->Callee;
4013 }
4014
4016 mapped_iterator<typename std::vector<std::shared_ptr<ContextEdge<
4017 DerivedCCG, FuncTy, CallTy>>>::const_iterator,
4018 decltype(&GetCallee)>;
4019
4021 return ChildIteratorType(N->CalleeEdges.begin(), &GetCallee);
4022 }
4023
4025 return ChildIteratorType(N->CalleeEdges.end(), &GetCallee);
4026 }
4027};
4028
4029template <typename DerivedCCG, typename FuncTy, typename CallTy>
4030struct DOTGraphTraits<const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>
4031 : public DefaultDOTGraphTraits {
4032 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {
4033 // If the user requested the full graph to be exported, but provided an
4034 // allocation id, or if the user gave a context id and requested more than
4035 // just a specific context to be exported, note that highlighting is
4036 // enabled.
4037 DoHighlight =
4038 (AllocIdForDot.getNumOccurrences() && DotGraphScope == DotScope::All) ||
4039 (ContextIdForDot.getNumOccurrences() &&
4041 }
4042
4043 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4045 using NodeRef = typename GTraits::NodeRef;
4046 using ChildIteratorType = typename GTraits::ChildIteratorType;
4047
4048 static std::string getNodeLabel(NodeRef Node, GraphType G) {
4049 std::string LabelString =
4050 (Twine("OrigId: ") + (Node->IsAllocation ? "Alloc" : "") +
4051 Twine(Node->OrigStackOrAllocId) + " NodeId: " + Twine(Node->NodeId))
4052 .str();
4053 LabelString += "\n";
4054 if (Node->hasCall()) {
4055 auto Func = G->NodeToCallingFunc.find(Node);
4056 assert(Func != G->NodeToCallingFunc.end());
4057 LabelString +=
4058 G->getLabel(Func->second, Node->Call.call(), Node->Call.cloneNo());
4059 for (auto &MatchingCall : Node->MatchingCalls) {
4060 LabelString += "\n";
4061 LabelString += G->getLabel(Func->second, MatchingCall.call(),
4062 MatchingCall.cloneNo());
4063 }
4064 } else {
4065 LabelString += "null call";
4066 if (Node->Recursive)
4067 LabelString += " (recursive)";
4068 else
4069 LabelString += " (external)";
4070 }
4071 return LabelString;
4072 }
4073
4075 auto ContextIds = Node->getContextIds();
4076 // If highlighting enabled, see if this node contains any of the context ids
4077 // of interest. If so, it will use a different color and a larger fontsize
4078 // (which makes the node larger as well).
4079 bool Highlight = false;
4080 if (DoHighlight) {
4081 assert(ContextIdForDot.getNumOccurrences() ||
4082 AllocIdForDot.getNumOccurrences());
4083 if (ContextIdForDot.getNumOccurrences())
4084 Highlight = ContextIds.contains(ContextIdForDot);
4085 else
4086 Highlight = set_intersects(ContextIds, G->DotAllocContextIds);
4087 }
4088 std::string AttributeString = (Twine("tooltip=\"") + getNodeId(Node) + " " +
4089 getContextIds(ContextIds) + "\"")
4090 .str();
4091 // Default fontsize is 14
4092 if (Highlight)
4093 AttributeString += ",fontsize=\"30\"";
4094 AttributeString +=
4095 (Twine(",fillcolor=\"") + getColor(Node->AllocTypes, Highlight) + "\"")
4096 .str();
4097 if (Node->CloneOf) {
4098 AttributeString += ",color=\"blue\"";
4099 AttributeString += ",style=\"filled,bold,dashed\"";
4100 } else
4101 AttributeString += ",style=\"filled\"";
4102 return AttributeString;
4103 }
4104
4105 static std::string getEdgeAttributes(NodeRef, ChildIteratorType ChildIter,
4106 GraphType G) {
4107 auto &Edge = *(ChildIter.getCurrent());
4108 // If highlighting enabled, see if this edge contains any of the context ids
4109 // of interest. If so, it will use a different color and a heavier arrow
4110 // size and weight (the larger weight makes the highlighted path
4111 // straighter).
4112 bool Highlight = false;
4113 if (DoHighlight) {
4114 assert(ContextIdForDot.getNumOccurrences() ||
4115 AllocIdForDot.getNumOccurrences());
4116 if (ContextIdForDot.getNumOccurrences())
4117 Highlight = Edge->ContextIds.contains(ContextIdForDot);
4118 else
4119 Highlight = set_intersects(Edge->ContextIds, G->DotAllocContextIds);
4120 }
4121 auto Color = getColor(Edge->AllocTypes, Highlight);
4122 std::string AttributeString =
4123 (Twine("tooltip=\"") + getContextIds(Edge->ContextIds) + "\"" +
4124 // fillcolor is the arrow head and color is the line
4125 Twine(",fillcolor=\"") + Color + "\"" + Twine(",color=\"") + Color +
4126 "\"")
4127 .str();
4128 if (Edge->IsBackedge)
4129 AttributeString += ",style=\"dotted\"";
4130 // Default penwidth and weight are both 1.
4131 if (Highlight)
4132 AttributeString += ",penwidth=\"2.0\",weight=\"2\"";
4133 return AttributeString;
4134 }
4135
4136 // Since the NodeOwners list includes nodes that are no longer connected to
4137 // the graph, skip them here.
4139 if (Node->isRemoved())
4140 return true;
4141 // If a scope smaller than the full graph was requested, see if this node
4142 // contains any of the context ids of interest.
4144 return !set_intersects(Node->getContextIds(), G->DotAllocContextIds);
4146 return !Node->getContextIds().contains(ContextIdForDot);
4147 return false;
4148 }
4149
4150private:
4151 static std::string getContextIds(const DenseSet<uint32_t> &ContextIds) {
4152 std::string IdString = "ContextIds:";
4153 if (ContextIds.size() < 100) {
4154 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
4155 std::sort(SortedIds.begin(), SortedIds.end());
4156 for (auto Id : SortedIds)
4157 IdString += (" " + Twine(Id)).str();
4158 } else {
4159 IdString += (" (" + Twine(ContextIds.size()) + " ids)").str();
4160 }
4161 return IdString;
4162 }
4163
4164 static std::string getColor(uint8_t AllocTypes, bool Highlight) {
4165 // If DoHighlight is not enabled, we want to use the highlight colors for
4166 // NotCold and Cold, and the non-highlight color for NotCold+Cold. This is
4167 // both compatible with the color scheme before highlighting was supported,
4168 // and for the NotCold+Cold color the non-highlight color is a bit more
4169 // readable.
4170 if (AllocTypes == (uint8_t)AllocationType::NotCold)
4171 // Color "brown1" actually looks like a lighter red.
4172 return !DoHighlight || Highlight ? "brown1" : "lightpink";
4173 if (AllocTypes == (uint8_t)AllocationType::Cold)
4174 return !DoHighlight || Highlight ? "cyan" : "lightskyblue";
4175 if (AllocTypes ==
4176 ((uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold))
4177 return Highlight ? "magenta" : "mediumorchid1";
4178 return "gray";
4179 }
4180
4181 static std::string getNodeId(NodeRef Node) {
4182 std::stringstream SStream;
4183 SStream << std::hex << "N0x" << (unsigned long long)Node;
4184 std::string Result = SStream.str();
4185 return Result;
4186 }
4187
4188 // True if we should highlight a specific context or allocation's contexts in
4189 // the emitted graph.
4190 static bool DoHighlight;
4191};
4192
4193template <typename DerivedCCG, typename FuncTy, typename CallTy>
4194bool DOTGraphTraits<
4195 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>::DoHighlight =
4196 false;
4197
4198template <typename DerivedCCG, typename FuncTy, typename CallTy>
4199void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::exportToDot(
4200 std::string Label) const {
4201 WriteGraph(this, "", false, Label,
4202 DotFilePathPrefix + "ccg." + Label + ".dot");
4203}
4204
4205template <typename DerivedCCG, typename FuncTy, typename CallTy>
4206typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
4207CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::moveEdgeToNewCalleeClone(
4208 const std::shared_ptr<ContextEdge> &Edge,
4209 DenseSet<uint32_t> ContextIdsToMove) {
4210 ContextNode *Node = Edge->Callee;
4211 assert(NodeToCallingFunc.count(Node));
4212 ContextNode *Clone =
4213 createNewNode(Node->IsAllocation, NodeToCallingFunc[Node], Node->Call);
4214 Node->addClone(Clone);
4215 Clone->MatchingCalls = Node->MatchingCalls;
4216 moveEdgeToExistingCalleeClone(Edge, Clone, /*NewClone=*/true,
4217 ContextIdsToMove);
4218 return Clone;
4219}
4220
4221template <typename DerivedCCG, typename FuncTy, typename CallTy>
4222void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4223 moveEdgeToExistingCalleeClone(const std::shared_ptr<ContextEdge> &Edge,
4224 ContextNode *NewCallee, bool NewClone,
4225 DenseSet<uint32_t> ContextIdsToMove) {
4226 // NewCallee and Edge's current callee must be clones of the same original
4227 // node (Edge's current callee may be the original node too).
4228 assert(NewCallee->getOrigNode() == Edge->Callee->getOrigNode());
4229
4230 bool EdgeIsRecursive = Edge->Callee == Edge->Caller;
4231
4232 ContextNode *OldCallee = Edge->Callee;
4233
4234 // We might already have an edge to the new callee from earlier cloning for a
4235 // different allocation. If one exists we will reuse it.
4236 auto ExistingEdgeToNewCallee = NewCallee->findEdgeFromCaller(Edge->Caller);
4237
4238 // Callers will pass an empty ContextIdsToMove set when they want to move the
4239 // edge. Copy in Edge's ids for simplicity.
4240 if (ContextIdsToMove.empty())
4241 ContextIdsToMove = Edge->getContextIds();
4242
4243 // If we are moving all of Edge's ids, then just move the whole Edge.
4244 // Otherwise only move the specified subset, to a new edge if needed.
4245 if (Edge->getContextIds().size() == ContextIdsToMove.size()) {
4246 // First, update the alloc types on New Callee from Edge.
4247 // Do this before we potentially clear Edge's fields below!
4248 NewCallee->AllocTypes |= Edge->AllocTypes;
4249 // Moving the whole Edge.
4250 if (ExistingEdgeToNewCallee) {
4251 // Since we already have an edge to NewCallee, simply move the ids
4252 // onto it, and remove the existing Edge.
4253 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
4254 ExistingEdgeToNewCallee->AllocTypes |= Edge->AllocTypes;
4255 assert(Edge->ContextIds == ContextIdsToMove);
4256 removeEdgeFromGraph(Edge.get());
4257 } else {
4258 // Otherwise just reconnect Edge to NewCallee.
4259 Edge->Callee = NewCallee;
4260 NewCallee->CallerEdges.push_back(Edge);
4261 // Remove it from callee where it was previously connected.
4262 OldCallee->eraseCallerEdge(Edge.get());
4263 // Don't need to update Edge's context ids since we are simply
4264 // reconnecting it.
4265 }
4266 } else {
4267 // Only moving a subset of Edge's ids.
4268 // Compute the alloc type of the subset of ids being moved.
4269 auto CallerEdgeAllocType = computeAllocType(ContextIdsToMove);
4270 if (ExistingEdgeToNewCallee) {
4271 // Since we already have an edge to NewCallee, simply move the ids
4272 // onto it.
4273 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
4274 ExistingEdgeToNewCallee->AllocTypes |= CallerEdgeAllocType;
4275 } else {
4276 // Otherwise, create a new edge to NewCallee for the ids being moved.
4277 auto NewEdge = std::make_shared<ContextEdge>(
4278 NewCallee, Edge->Caller, CallerEdgeAllocType, ContextIdsToMove);
4279 Edge->Caller->CalleeEdges.push_back(NewEdge);
4280 NewCallee->CallerEdges.push_back(NewEdge);
4281 }
4282 // In either case, need to update the alloc types on NewCallee, and remove
4283 // those ids and update the alloc type on the original Edge.
4284 NewCallee->AllocTypes |= CallerEdgeAllocType;
4285 set_subtract(Edge->ContextIds, ContextIdsToMove);
4286 Edge->AllocTypes = computeAllocType(Edge->ContextIds);
4287 }
4288 // Now walk the old callee node's callee edges and move Edge's context ids
4289 // over to the corresponding edge into the clone (which is created here if
4290 // this is a newly created clone).
4291 for (auto &OldCalleeEdge : OldCallee->CalleeEdges) {
4292 ContextNode *CalleeToUse = OldCalleeEdge->Callee;
4293 // If this is a direct recursion edge, use NewCallee (the clone) as the
4294 // callee as well, so that any edge updated/created here is also direct
4295 // recursive.
4296 if (CalleeToUse == OldCallee) {
4297 // If this is a recursive edge, see if we already moved a recursive edge
4298 // (which would have to have been this one) - if we were only moving a
4299 // subset of context ids it would still be on OldCallee.
4300 if (EdgeIsRecursive) {
4301 assert(OldCalleeEdge == Edge);
4302 continue;
4303 }
4304 CalleeToUse = NewCallee;
4305 }
4306 // The context ids moving to the new callee are the subset of this edge's
4307 // context ids and the context ids on the caller edge being moved.
4308 DenseSet<uint32_t> EdgeContextIdsToMove =
4309 set_intersection(OldCalleeEdge->getContextIds(), ContextIdsToMove);
4310 set_subtract(OldCalleeEdge->getContextIds(), EdgeContextIdsToMove);
4311 OldCalleeEdge->AllocTypes =
4312 computeAllocType(OldCalleeEdge->getContextIds());
4313 if (!NewClone) {
4314 // Update context ids / alloc type on corresponding edge to NewCallee.
4315 // There is a chance this may not exist if we are reusing an existing
4316 // clone, specifically during function assignment, where we would have
4317 // removed none type edges after creating the clone. If we can't find
4318 // a corresponding edge there, fall through to the cloning below.
4319 if (auto *NewCalleeEdge = NewCallee->findEdgeFromCallee(CalleeToUse)) {
4320 NewCalleeEdge->getContextIds().insert_range(EdgeContextIdsToMove);
4321 NewCalleeEdge->AllocTypes |= computeAllocType(EdgeContextIdsToMove);
4322 continue;
4323 }
4324 }
4325 auto NewEdge = std::make_shared<ContextEdge>(
4326 CalleeToUse, NewCallee, computeAllocType(EdgeContextIdsToMove),
4327 EdgeContextIdsToMove);
4328 NewCallee->CalleeEdges.push_back(NewEdge);
4329 NewEdge->Callee->CallerEdges.push_back(NewEdge);
4330 }
4331 // Recompute the node alloc type now that its callee edges have been
4332 // updated (since we will compute from those edges).
4333 OldCallee->AllocTypes = OldCallee->computeAllocType();
4334 // OldCallee alloc type should be None iff its context id set is now empty.
4335 assert((OldCallee->AllocTypes == (uint8_t)AllocationType::None) ==
4336 OldCallee->emptyContextIds());
4337 if (VerifyCCG) {
4338 checkNode<DerivedCCG, FuncTy, CallTy>(OldCallee, /*CheckEdges=*/false);
4339 checkNode<DerivedCCG, FuncTy, CallTy>(NewCallee, /*CheckEdges=*/false);
4340 for (const auto &OldCalleeEdge : OldCallee->CalleeEdges)
4341 checkNode<DerivedCCG, FuncTy, CallTy>(OldCalleeEdge->Callee,
4342 /*CheckEdges=*/false);
4343 for (const auto &NewCalleeEdge : NewCallee->CalleeEdges)
4344 checkNode<DerivedCCG, FuncTy, CallTy>(NewCalleeEdge->Callee,
4345 /*CheckEdges=*/false);
4346 }
4347}
4348
4349template <typename DerivedCCG, typename FuncTy, typename CallTy>
4350void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4351 moveCalleeEdgeToNewCaller(const std::shared_ptr<ContextEdge> &Edge,
4352 ContextNode *NewCaller) {
4353 auto *OldCallee = Edge->Callee;
4354 auto *NewCallee = OldCallee;
4355 // If this edge was direct recursive, make any new/updated edge also direct
4356 // recursive to NewCaller.
4357 bool Recursive = Edge->Caller == Edge->Callee;
4358 if (Recursive)
4359 NewCallee = NewCaller;
4360
4361 ContextNode *OldCaller = Edge->Caller;
4362 OldCaller->eraseCalleeEdge(Edge.get());
4363
4364 // We might already have an edge to the new caller. If one exists we will
4365 // reuse it.
4366 auto ExistingEdgeToNewCaller = NewCaller->findEdgeFromCallee(NewCallee);
4367
4368 if (ExistingEdgeToNewCaller) {
4369 // Since we already have an edge to NewCaller, simply move the ids
4370 // onto it, and remove the existing Edge.
4371 ExistingEdgeToNewCaller->getContextIds().insert_range(
4372 Edge->getContextIds());
4373 ExistingEdgeToNewCaller->AllocTypes |= Edge->AllocTypes;
4374 Edge->ContextIds.clear();
4375 Edge->AllocTypes = (uint8_t)AllocationType::None;
4376 OldCallee->eraseCallerEdge(Edge.get());
4377 } else {
4378 // Otherwise just reconnect Edge to NewCaller.
4379 Edge->Caller = NewCaller;
4380 NewCaller->CalleeEdges.push_back(Edge);
4381 if (Recursive) {
4382 assert(NewCallee == NewCaller);
4383 // In the case of (direct) recursive edges, we update the callee as well
4384 // so that it becomes recursive on the new caller.
4385 Edge->Callee = NewCallee;
4386 NewCallee->CallerEdges.push_back(Edge);
4387 OldCallee->eraseCallerEdge(Edge.get());
4388 }
4389 // Don't need to update Edge's context ids since we are simply
4390 // reconnecting it.
4391 }
4392 // In either case, need to update the alloc types on New Caller.
4393 NewCaller->AllocTypes |= Edge->AllocTypes;
4394
4395 // Now walk the old caller node's caller edges and move Edge's context ids
4396 // over to the corresponding edge into the node (which is created here if
4397 // this is a newly created node). We can tell whether this is a newly created
4398 // node by seeing if it has any caller edges yet.
4399#ifndef NDEBUG
4400 bool IsNewNode = NewCaller->CallerEdges.empty();
4401#endif
4402 // If we just moved a direct recursive edge, presumably its context ids should
4403 // also flow out of OldCaller via some other non-recursive callee edge. We
4404 // don't want to remove the recursive context ids from other caller edges yet,
4405 // otherwise the context ids get into an inconsistent state on OldCaller.
4406 // We will update these context ids on the non-recursive caller edge when and
4407 // if they are updated on the non-recursive callee.
4408 if (!Recursive) {
4409 for (auto &OldCallerEdge : OldCaller->CallerEdges) {
4410 auto OldCallerCaller = OldCallerEdge->Caller;
4411 // The context ids moving to the new caller are the subset of this edge's
4412 // context ids and the context ids on the callee edge being moved.
4413 DenseSet<uint32_t> EdgeContextIdsToMove = set_intersection(
4414 OldCallerEdge->getContextIds(), Edge->getContextIds());
4415 if (OldCaller == OldCallerCaller) {
4416 OldCallerCaller = NewCaller;
4417 // Don't actually move this one. The caller will move it directly via a
4418 // call to this function with this as the Edge if it is appropriate to
4419 // move to a diff node that has a matching callee (itself).
4420 continue;
4421 }
4422 set_subtract(OldCallerEdge->getContextIds(), EdgeContextIdsToMove);
4423 OldCallerEdge->AllocTypes =
4424 computeAllocType(OldCallerEdge->getContextIds());
4425 // In this function we expect that any pre-existing node already has edges
4426 // from the same callers as the old node. That should be true in the
4427 // current use case, where we will remove None-type edges after copying
4428 // over all caller edges from the callee.
4429 auto *ExistingCallerEdge = NewCaller->findEdgeFromCaller(OldCallerCaller);
4430 // Since we would have skipped caller edges when moving a direct recursive
4431 // edge, this may not hold true when recursive handling enabled.
4432 assert(IsNewNode || ExistingCallerEdge || AllowRecursiveCallsites);
4433 if (ExistingCallerEdge) {
4434 ExistingCallerEdge->getContextIds().insert_range(EdgeContextIdsToMove);
4435 ExistingCallerEdge->AllocTypes |=
4436 computeAllocType(EdgeContextIdsToMove);
4437 continue;
4438 }
4439 auto NewEdge = std::make_shared<ContextEdge>(
4440 NewCaller, OldCallerCaller, computeAllocType(EdgeContextIdsToMove),
4441 EdgeContextIdsToMove);
4442 NewCaller->CallerEdges.push_back(NewEdge);
4443 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
4444 }
4445 }
4446 // Recompute the node alloc type now that its caller edges have been
4447 // updated (since we will compute from those edges).
4448 OldCaller->AllocTypes = OldCaller->computeAllocType();
4449 // OldCaller alloc type should be None iff its context id set is now empty.
4450 assert((OldCaller->AllocTypes == (uint8_t)AllocationType::None) ==
4451 OldCaller->emptyContextIds());
4452 if (VerifyCCG) {
4453 checkNode<DerivedCCG, FuncTy, CallTy>(OldCaller, /*CheckEdges=*/false);
4454 checkNode<DerivedCCG, FuncTy, CallTy>(NewCaller, /*CheckEdges=*/false);
4455 for (const auto &OldCallerEdge : OldCaller->CallerEdges)
4456 checkNode<DerivedCCG, FuncTy, CallTy>(OldCallerEdge->Caller,
4457 /*CheckEdges=*/false);
4458 for (const auto &NewCallerEdge : NewCaller->CallerEdges)
4459 checkNode<DerivedCCG, FuncTy, CallTy>(NewCallerEdge->Caller,
4460 /*CheckEdges=*/false);
4461 }
4462}
4463
4464template <typename DerivedCCG, typename FuncTy, typename CallTy>
4465void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4466 recursivelyRemoveNoneTypeCalleeEdges(
4467 ContextNode *Node, DenseSet<const ContextNode *> &Visited) {
4468 auto Inserted = Visited.insert(Node);
4469 if (!Inserted.second)
4470 return;
4471
4472 removeNoneTypeCalleeEdges(Node);
4473
4474 for (auto *Clone : Node->Clones)
4475 recursivelyRemoveNoneTypeCalleeEdges(Clone, Visited);
4476
4477 // The recursive call may remove some of this Node's caller edges.
4478 // Iterate over a copy and skip any that were removed.
4479 auto CallerEdges = Node->CallerEdges;
4480 for (auto &Edge : CallerEdges) {
4481 // Skip any that have been removed by an earlier recursive call.
4482 if (Edge->isRemoved()) {
4483 assert(!is_contained(Node->CallerEdges, Edge));
4484 continue;
4485 }
4486 recursivelyRemoveNoneTypeCalleeEdges(Edge->Caller, Visited);
4487 }
4488}
4489
4490// This is the standard DFS based backedge discovery algorithm.
4491template <typename DerivedCCG, typename FuncTy, typename CallTy>
4492void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges() {
4493 // If we are cloning recursive contexts, find and mark backedges from all root
4494 // callers, using the typical DFS based backedge analysis.
4496 return;
4497 DenseSet<const ContextNode *> Visited;
4498 DenseSet<const ContextNode *> CurrentStack;
4499 for (auto &Entry : NonAllocationCallToContextNodeMap) {
4500 auto *Node = Entry.second;
4501 if (Node->isRemoved())
4502 continue;
4503 // It is a root if it doesn't have callers.
4504 if (!Node->CallerEdges.empty())
4505 continue;
4506 markBackedges(Node, Visited, CurrentStack);
4507 assert(CurrentStack.empty());
4508 }
4509}
4510
4511// Recursive helper for above markBackedges method.
4512template <typename DerivedCCG, typename FuncTy, typename CallTy>
4513void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges(
4514 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4515 DenseSet<const ContextNode *> &CurrentStack) {
4516 auto I = Visited.insert(Node);
4517 // We should only call this for unvisited nodes.
4518 assert(I.second);
4519 (void)I;
4520 for (auto &CalleeEdge : Node->CalleeEdges) {
4521 auto *Callee = CalleeEdge->Callee;
4522 if (Visited.count(Callee)) {
4523 // Since this was already visited we need to check if it is currently on
4524 // the recursive stack in which case it is a backedge.
4525 if (CurrentStack.count(Callee))
4526 CalleeEdge->IsBackedge = true;
4527 continue;
4528 }
4529 CurrentStack.insert(Callee);
4530 markBackedges(Callee, Visited, CurrentStack);
4531 CurrentStack.erase(Callee);
4532 }
4533}
4534
4535template <typename DerivedCCG, typename FuncTy, typename CallTy>
4536void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones() {
4537 DenseSet<const ContextNode *> Visited;
4538 for (auto &Entry : AllocationCallToContextNodeMap) {
4539 Visited.clear();
4540 identifyClones(Entry.second, Visited, Entry.second->getContextIds());
4541 }
4542 Visited.clear();
4543 for (auto &Entry : AllocationCallToContextNodeMap)
4544 recursivelyRemoveNoneTypeCalleeEdges(Entry.second, Visited);
4545 if (VerifyCCG)
4546 check();
4547}
4548
4549// helper function to check an AllocType is cold or notcold or both.
4556
4557template <typename DerivedCCG, typename FuncTy, typename CallTy>
4558void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones(
4559 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4560 const DenseSet<uint32_t> &AllocContextIds) {
4561 if (VerifyNodes)
4562 checkNode<DerivedCCG, FuncTy, CallTy>(Node, /*CheckEdges=*/false);
4563 assert(!Node->CloneOf);
4564
4565 // If Node as a null call, then either it wasn't found in the module (regular
4566 // LTO) or summary index (ThinLTO), or there were other conditions blocking
4567 // cloning (e.g. recursion, calls multiple targets, etc).
4568 // Do this here so that we don't try to recursively clone callers below, which
4569 // isn't useful at least for this node.
4570 if (!Node->hasCall())
4571 return;
4572
4573 // No need to look at any callers if allocation type already unambiguous.
4574 if (hasSingleAllocType(Node->AllocTypes))
4575 return;
4576
4577#ifndef NDEBUG
4578 auto Insert =
4579#endif
4580 Visited.insert(Node);
4581 // We should not have visited this node yet.
4582 assert(Insert.second);
4583 // The recursive call to identifyClones may delete the current edge from the
4584 // CallerEdges vector. Make a copy and iterate on that, simpler than passing
4585 // in an iterator and having recursive call erase from it. Other edges may
4586 // also get removed during the recursion, which will have null Callee and
4587 // Caller pointers (and are deleted later), so we skip those below.
4588 {
4589 auto CallerEdges = Node->CallerEdges;
4590 for (auto &Edge : CallerEdges) {
4591 // Skip any that have been removed by an earlier recursive call.
4592 if (Edge->isRemoved()) {
4593 assert(!is_contained(Node->CallerEdges, Edge));
4594 continue;
4595 }
4596 // Defer backedges. See comments further below where these edges are
4597 // handled during the cloning of this Node.
4598 if (Edge->IsBackedge) {
4599 // We should only mark these if cloning recursive contexts, where we
4600 // need to do this deferral.
4602 continue;
4603 }
4604 // Ignore any caller we previously visited via another edge.
4605 if (!Visited.count(Edge->Caller) && !Edge->Caller->CloneOf) {
4606 identifyClones(Edge->Caller, Visited, AllocContextIds);
4607 }
4608 }
4609 }
4610
4611 // Check if we reached an unambiguous call or have have only a single caller.
4612 if (hasSingleAllocType(Node->AllocTypes) || Node->CallerEdges.size() <= 1)
4613 return;
4614
4615 // We need to clone.
4616
4617 // Try to keep the original version as alloc type NotCold. This will make
4618 // cases with indirect calls or any other situation with an unknown call to
4619 // the original function get the default behavior. We do this by sorting the
4620 // CallerEdges of the Node we will clone by alloc type.
4621 //
4622 // Give NotCold edge the lowest sort priority so those edges are at the end of
4623 // the caller edges vector, and stay on the original version (since the below
4624 // code clones greedily until it finds all remaining edges have the same type
4625 // and leaves the remaining ones on the original Node).
4626 //
4627 // We shouldn't actually have any None type edges, so the sorting priority for
4628 // that is arbitrary, and we assert in that case below.
4629 const unsigned AllocTypeCloningPriority[] = {/*None*/ 3, /*NotCold*/ 4,
4630 /*Cold*/ 1,
4631 /*NotColdCold*/ 2};
4632 llvm::stable_sort(Node->CallerEdges,
4633 [&](const std::shared_ptr<ContextEdge> &A,
4634 const std::shared_ptr<ContextEdge> &B) {
4635 // Nodes with non-empty context ids should be sorted
4636 // before those with empty context ids.
4637 if (A->ContextIds.empty())
4638 // Either B ContextIds are non-empty (in which case we
4639 // should return false because B < A), or B ContextIds
4640 // are empty, in which case they are equal, and we
4641 // should maintain the original relative ordering.
4642 return false;
4643 if (B->ContextIds.empty())
4644 return true;
4645
4646 if (A->AllocTypes == B->AllocTypes)
4647 // Use the caller node id as a deterministic
4648 // tie-breaker.
4649 return A->Caller->NodeId < B->Caller->NodeId;
4650 return AllocTypeCloningPriority[A->AllocTypes] <
4651 AllocTypeCloningPriority[B->AllocTypes];
4652 });
4653
4654 assert(Node->AllocTypes != (uint8_t)AllocationType::None);
4655
4656 DenseSet<uint32_t> RecursiveContextIds;
4658 // If we are allowing recursive callsites, but have also disabled recursive
4659 // contexts, look for context ids that show up in multiple caller edges.
4661 DenseSet<uint32_t> AllCallerContextIds;
4662 for (auto &CE : Node->CallerEdges) {
4663 // Resize to the largest set of caller context ids, since we know the
4664 // final set will be at least that large.
4665 AllCallerContextIds.reserve(CE->getContextIds().size());
4666 for (auto Id : CE->getContextIds())
4667 if (!AllCallerContextIds.insert(Id).second)
4668 RecursiveContextIds.insert(Id);
4669 }
4670 }
4671
4672 // Iterate until we find no more opportunities for disambiguating the alloc
4673 // types via cloning. In most cases this loop will terminate once the Node
4674 // has a single allocation type, in which case no more cloning is needed.
4675 // Iterate over a copy of Node's caller edges, since we may need to remove
4676 // edges in the moveEdgeTo* methods, and this simplifies the handling and
4677 // makes it less error-prone.
4678 auto CallerEdges = Node->CallerEdges;
4679 for (auto &CallerEdge : CallerEdges) {
4680 // Skip any that have been removed by an earlier recursive call.
4681 if (CallerEdge->isRemoved()) {
4682 assert(!is_contained(Node->CallerEdges, CallerEdge));
4683 continue;
4684 }
4685 assert(CallerEdge->Callee == Node);
4686
4687 // See if cloning the prior caller edge left this node with a single alloc
4688 // type or a single caller. In that case no more cloning of Node is needed.
4689 if (hasSingleAllocType(Node->AllocTypes) || Node->CallerEdges.size() <= 1)
4690 break;
4691
4692 // If the caller was not successfully matched to a call in the IR/summary,
4693 // there is no point in trying to clone for it as we can't update that call.
4694 if (!CallerEdge->Caller->hasCall())
4695 continue;
4696
4697 // Only need to process the ids along this edge pertaining to the given
4698 // allocation.
4699 auto CallerEdgeContextsForAlloc =
4700 set_intersection(CallerEdge->getContextIds(), AllocContextIds);
4701 if (!RecursiveContextIds.empty())
4702 CallerEdgeContextsForAlloc =
4703 set_difference(CallerEdgeContextsForAlloc, RecursiveContextIds);
4704 if (CallerEdgeContextsForAlloc.empty())
4705 continue;
4706
4707 auto CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
4708
4709 // Compute the node callee edge alloc types corresponding to the context ids
4710 // for this caller edge.
4711 std::vector<uint8_t> CalleeEdgeAllocTypesForCallerEdge;
4712 CalleeEdgeAllocTypesForCallerEdge.reserve(Node->CalleeEdges.size());
4713 for (auto &CalleeEdge : Node->CalleeEdges)
4714 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
4715 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
4716
4717 // Don't clone if doing so will not disambiguate any alloc types amongst
4718 // caller edges (including the callee edges that would be cloned).
4719 // Otherwise we will simply move all edges to the clone.
4720 //
4721 // First check if by cloning we will disambiguate the caller allocation
4722 // type from node's allocation type. Query allocTypeToUse so that we don't
4723 // bother cloning to distinguish NotCold+Cold from NotCold. Note that
4724 // neither of these should be None type.
4725 //
4726 // Then check if by cloning node at least one of the callee edges will be
4727 // disambiguated by splitting out different context ids.
4728 //
4729 // However, always do the cloning if this is a backedge, in which case we
4730 // have not yet cloned along this caller edge.
4731 assert(CallerEdge->AllocTypes != (uint8_t)AllocationType::None);
4732 assert(Node->AllocTypes != (uint8_t)AllocationType::None);
4733 if (!CallerEdge->IsBackedge &&
4734 allocTypeToUse(CallerAllocTypeForAlloc) ==
4735 allocTypeToUse(Node->AllocTypes) &&
4736 allocTypesMatch<DerivedCCG, FuncTy, CallTy>(
4737 CalleeEdgeAllocTypesForCallerEdge, Node->CalleeEdges)) {
4738 continue;
4739 }
4740
4741 if (CallerEdge->IsBackedge) {
4742 // We should only mark these if cloning recursive contexts, where we
4743 // need to do this deferral.
4745 DeferredBackedges++;
4746 }
4747
4748 // If this is a backedge, we now do recursive cloning starting from its
4749 // caller since we may have moved unambiguous caller contexts to a clone
4750 // of this Node in a previous iteration of the current loop, giving more
4751 // opportunity for cloning through the backedge. Because we sorted the
4752 // caller edges earlier so that cold caller edges are first, we would have
4753 // visited and cloned this node for any unamibiguously cold non-recursive
4754 // callers before any ambiguous backedge callers. Note that we don't do this
4755 // if the caller is already cloned or visited during cloning (e.g. via a
4756 // different context path from the allocation).
4757 // TODO: Can we do better in the case where the caller was already visited?
4758 if (CallerEdge->IsBackedge && !CallerEdge->Caller->CloneOf &&
4759 !Visited.count(CallerEdge->Caller)) {
4760 const auto OrigIdCount = CallerEdge->getContextIds().size();
4761 // Now do the recursive cloning of this backedge's caller, which was
4762 // deferred earlier.
4763 identifyClones(CallerEdge->Caller, Visited, CallerEdgeContextsForAlloc);
4764 removeNoneTypeCalleeEdges(CallerEdge->Caller);
4765 // See if the recursive call to identifyClones moved the context ids to a
4766 // new edge from this node to a clone of caller, and switch to looking at
4767 // that new edge so that we clone Node for the new caller clone.
4768 bool UpdatedEdge = false;
4769 if (OrigIdCount > CallerEdge->getContextIds().size()) {
4770 for (auto E : Node->CallerEdges) {
4771 // Only interested in clones of the current edges caller.
4772 if (E->Caller->CloneOf != CallerEdge->Caller)
4773 continue;
4774 // See if this edge contains any of the context ids originally on the
4775 // current caller edge.
4776 auto CallerEdgeContextsForAllocNew =
4777 set_intersection(CallerEdgeContextsForAlloc, E->getContextIds());
4778 if (CallerEdgeContextsForAllocNew.empty())
4779 continue;
4780 // Make sure we don't pick a previously existing caller edge of this
4781 // Node, which would be processed on a different iteration of the
4782 // outer loop over the saved CallerEdges.
4783 if (llvm::is_contained(CallerEdges, E))
4784 continue;
4785 // The CallerAllocTypeForAlloc and CalleeEdgeAllocTypesForCallerEdge
4786 // are updated further below for all cases where we just invoked
4787 // identifyClones recursively.
4788 CallerEdgeContextsForAlloc.swap(CallerEdgeContextsForAllocNew);
4789 CallerEdge = E;
4790 UpdatedEdge = true;
4791 break;
4792 }
4793 }
4794 // If cloning removed this edge (and we didn't update it to a new edge
4795 // above), we're done with this edge. It's possible we moved all of the
4796 // context ids to an existing clone, in which case there's no need to do
4797 // further processing for them.
4798 if (CallerEdge->isRemoved())
4799 continue;
4800
4801 // Now we need to update the information used for the cloning decisions
4802 // further below, as we may have modified edges and their context ids.
4803
4804 // Note if we changed the CallerEdge above we would have already updated
4805 // the context ids.
4806 if (!UpdatedEdge) {
4807 CallerEdgeContextsForAlloc = set_intersection(
4808 CallerEdgeContextsForAlloc, CallerEdge->getContextIds());
4809 if (CallerEdgeContextsForAlloc.empty())
4810 continue;
4811 }
4812 // Update the other information that depends on the edges and on the now
4813 // updated CallerEdgeContextsForAlloc.
4814 CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
4815 CalleeEdgeAllocTypesForCallerEdge.clear();
4816 for (auto &CalleeEdge : Node->CalleeEdges) {
4817 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
4818 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
4819 }
4820 }
4821
4822 // First see if we can use an existing clone. Check each clone and its
4823 // callee edges for matching alloc types.
4824 ContextNode *Clone = nullptr;
4825 for (auto *CurClone : Node->Clones) {
4826 if (allocTypeToUse(CurClone->AllocTypes) !=
4827 allocTypeToUse(CallerAllocTypeForAlloc))
4828 continue;
4829
4830 bool BothSingleAlloc = hasSingleAllocType(CurClone->AllocTypes) &&
4831 hasSingleAllocType(CallerAllocTypeForAlloc);
4832 // The above check should mean that if both have single alloc types that
4833 // they should be equal.
4834 assert(!BothSingleAlloc ||
4835 CurClone->AllocTypes == CallerAllocTypeForAlloc);
4836
4837 // If either both have a single alloc type (which are the same), or if the
4838 // clone's callee edges have the same alloc types as those for the current
4839 // allocation on Node's callee edges (CalleeEdgeAllocTypesForCallerEdge),
4840 // then we can reuse this clone.
4841 if (BothSingleAlloc || allocTypesMatchClone<DerivedCCG, FuncTy, CallTy>(
4842 CalleeEdgeAllocTypesForCallerEdge, CurClone)) {
4843 Clone = CurClone;
4844 break;
4845 }
4846 }
4847
4848 // The edge iterator is adjusted when we move the CallerEdge to the clone.
4849 if (Clone)
4850 moveEdgeToExistingCalleeClone(CallerEdge, Clone, /*NewClone=*/false,
4851 CallerEdgeContextsForAlloc);
4852 else
4853 Clone = moveEdgeToNewCalleeClone(CallerEdge, CallerEdgeContextsForAlloc);
4854
4855 // Sanity check that no alloc types on clone or its edges are None.
4856 assert(Clone->AllocTypes != (uint8_t)AllocationType::None);
4857 }
4858
4859 // We should still have some context ids on the original Node.
4860 assert(!Node->emptyContextIds());
4861
4862 // Sanity check that no alloc types on node or edges are None.
4863 assert(Node->AllocTypes != (uint8_t)AllocationType::None);
4864
4865 if (VerifyNodes)
4866 checkNode<DerivedCCG, FuncTy, CallTy>(Node, /*CheckEdges=*/false);
4867}
4868
4869void ModuleCallsiteContextGraph::updateAllocationCall(
4870 CallInfo &Call, AllocationType AllocType) {
4871 std::string AllocTypeString = getAllocTypeAttributeString(AllocType);
4872 auto *CB = cast<CallBase>(Call.call());
4873 if (isAmbiguousAllocType((uint8_t)AllocType)) {
4874 // The contexts reaching this allocation could not be disambiguated, so it
4875 // keeps (or gets) the ambiguous attribute added during matching rather than
4876 // the default not cold attribute.
4878 } else {
4880 auto A = llvm::Attribute::get(CB->getFunction()->getContext(), "memprof",
4881 AllocTypeString);
4882 CB->addFnAttr(A);
4883 }
4884 OREGetter(Call.call()->getFunction())
4885 .emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", Call.call())
4886 << ore::NV("AllocationCall", Call.call()) << " in clone "
4887 << ore::NV("Caller", Call.call()->getFunction())
4888 << " marked with memprof allocation attribute "
4889 << ore::NV("Attribute", AllocTypeString));
4890}
4891
4892void IndexCallsiteContextGraph::updateAllocationCall(CallInfo &Call,
4894 auto *AI = cast<AllocInfo *>(Call.call());
4895 assert(AI);
4896 assert(AI->Versions.size() > Call.cloneNo());
4897 AI->Versions[Call.cloneNo()] = (uint8_t)AllocType;
4898}
4899
4901ModuleCallsiteContextGraph::getAllocationCallType(const CallInfo &Call) const {
4902 const auto *CB = cast<CallBase>(Call.call());
4903 if (!CB->getAttributes().hasFnAttr("memprof"))
4904 return AllocationType::None;
4905 StringRef AllocTypeString =
4906 CB->getAttributes().getFnAttr("memprof").getValueAsString();
4907 if (AllocTypeString == "cold")
4908 return AllocationType::Cold;
4909 if (AllocTypeString == "ambiguous")
4910 return (AllocationType)((uint8_t)AllocationType::NotCold |
4911 (uint8_t)AllocationType::Cold);
4912 return AllocationType::NotCold;
4913}
4914
4916IndexCallsiteContextGraph::getAllocationCallType(const CallInfo &Call) const {
4917 const auto *AI = cast<AllocInfo *>(Call.call());
4918 assert(AI->Versions.size() > Call.cloneNo());
4919 return (AllocationType)AI->Versions[Call.cloneNo()];
4920}
4921
4922void ModuleCallsiteContextGraph::updateCall(CallInfo &CallerCall,
4923 FuncInfo CalleeFunc) {
4924 auto *CurF = getCalleeFunc(CallerCall.call());
4925 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
4926 if (isMemProfClone(*CurF)) {
4927 // If we already assigned this callsite to call a specific non-default
4928 // clone (i.e. not the original function which is clone 0), ensure that we
4929 // aren't trying to now update it to call a different clone, which is
4930 // indicative of a bug in the graph or function assignment.
4931 auto CurCalleeCloneNo = getMemProfCloneNum(*CurF);
4932 if (CurCalleeCloneNo != NewCalleeCloneNo) {
4933 LLVM_DEBUG(dbgs() << "Mismatch in call clone assignment: was "
4934 << CurCalleeCloneNo << " now " << NewCalleeCloneNo
4935 << "\n");
4936 MismatchedCloneAssignments++;
4937 }
4938 }
4939 if (NewCalleeCloneNo > 0)
4940 cast<CallBase>(CallerCall.call())->setCalledFunction(CalleeFunc.func());
4941 OREGetter(CallerCall.call()->getFunction())
4942 .emit(OptimizationRemark(DEBUG_TYPE, "MemprofCall", CallerCall.call())
4943 << ore::NV("Call", CallerCall.call()) << " in clone "
4944 << ore::NV("Caller", CallerCall.call()->getFunction())
4945 << " assigned to call function clone "
4946 << ore::NV("Callee", CalleeFunc.func()));
4947}
4948
4949void IndexCallsiteContextGraph::updateCall(CallInfo &CallerCall,
4950 FuncInfo CalleeFunc) {
4951 auto *CI = cast<CallsiteInfo *>(CallerCall.call());
4952 assert(CI &&
4953 "Caller cannot be an allocation which should not have profiled calls");
4954 assert(CI->Clones.size() > CallerCall.cloneNo());
4955 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
4956 auto &CurCalleeCloneNo = CI->Clones[CallerCall.cloneNo()];
4957 // If we already assigned this callsite to call a specific non-default
4958 // clone (i.e. not the original function which is clone 0), ensure that we
4959 // aren't trying to now update it to call a different clone, which is
4960 // indicative of a bug in the graph or function assignment.
4961 if (CurCalleeCloneNo != 0 && CurCalleeCloneNo != NewCalleeCloneNo) {
4962 LLVM_DEBUG(dbgs() << "Mismatch in call clone assignment: was "
4963 << CurCalleeCloneNo << " now " << NewCalleeCloneNo
4964 << "\n");
4965 MismatchedCloneAssignments++;
4966 }
4967 CurCalleeCloneNo = NewCalleeCloneNo;
4968}
4969
4970// Update the debug information attached to NewFunc to use the clone Name. Note
4971// this needs to be done for both any existing DISubprogram for the definition,
4972// as well as any separate declaration DISubprogram.
4974 assert(Name == NewFunc->getName());
4975 auto *SP = NewFunc->getSubprogram();
4976 if (!SP)
4977 return;
4978 auto *MDName = MDString::get(NewFunc->getParent()->getContext(), Name);
4979 SP->replaceLinkageName(MDName);
4980 DISubprogram *Decl = SP->getDeclaration();
4981 if (!Decl)
4982 return;
4983 TempDISubprogram NewDecl = Decl->clone();
4984 NewDecl->replaceLinkageName(MDName);
4985 SP->replaceDeclaration(MDNode::replaceWithUniqued(std::move(NewDecl)));
4986}
4987
4988CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
4989 Instruction *>::FuncInfo
4990ModuleCallsiteContextGraph::cloneFunctionForCallsite(
4991 FuncInfo &Func, CallInfo &Call, DenseMap<CallInfo, CallInfo> &CallMap,
4992 std::vector<CallInfo> &CallsWithMetadataInFunc, unsigned CloneNo) {
4993 // Use existing LLVM facilities for cloning and obtaining Call in clone
4994 ValueToValueMapTy VMap;
4995 auto *NewFunc = CloneFunction(Func.func(), VMap);
4996 std::string Name = getMemProfFuncName(Func.func()->getName(), CloneNo);
4997 assert(!Func.func()->getParent()->getFunction(Name));
4998 NewFunc->setName(Name);
4999 updateSubprogramLinkageName(NewFunc, Name);
5000 for (auto &Inst : CallsWithMetadataInFunc) {
5001 // This map always has the initial version in it.
5002 assert(Inst.cloneNo() == 0);
5003 CallMap[Inst] = {cast<Instruction>(VMap[Inst.call()]), CloneNo};
5004 }
5005 OREGetter(Func.func())
5006 .emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", Func.func())
5007 << "created clone " << ore::NV("NewFunction", NewFunc));
5008 return {NewFunc, CloneNo};
5009}
5010
5011CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
5012 IndexCall>::FuncInfo
5013IndexCallsiteContextGraph::cloneFunctionForCallsite(
5014 FuncInfo &Func, CallInfo &Call, DenseMap<CallInfo, CallInfo> &CallMap,
5015 std::vector<CallInfo> &CallsWithMetadataInFunc, unsigned CloneNo) {
5016 // Check how many clones we have of Call (and therefore function).
5017 // The next clone number is the current size of versions array.
5018 // Confirm this matches the CloneNo provided by the caller, which is based on
5019 // the number of function clones we have.
5020 assert(CloneNo == (isa<AllocInfo *>(Call.call())
5021 ? cast<AllocInfo *>(Call.call())->Versions.size()
5022 : cast<CallsiteInfo *>(Call.call())->Clones.size()));
5023 // Walk all the instructions in this function. Create a new version for
5024 // each (by adding an entry to the Versions/Clones summary array), and copy
5025 // over the version being called for the function clone being cloned here.
5026 // Additionally, add an entry to the CallMap for the new function clone,
5027 // mapping the original call (clone 0, what is in CallsWithMetadataInFunc)
5028 // to the new call clone.
5029 for (auto &Inst : CallsWithMetadataInFunc) {
5030 // This map always has the initial version in it.
5031 assert(Inst.cloneNo() == 0);
5032 if (auto *AI = dyn_cast<AllocInfo *>(Inst.call())) {
5033 assert(AI->Versions.size() == CloneNo);
5034 // We assign the allocation type later (in updateAllocationCall), just add
5035 // an entry for it here.
5036 AI->Versions.push_back(0);
5037 } else {
5038 auto *CI = cast<CallsiteInfo *>(Inst.call());
5039 assert(CI && CI->Clones.size() == CloneNo);
5040 // We assign the clone number later (in updateCall), just add an entry for
5041 // it here.
5042 CI->Clones.push_back(0);
5043 }
5044 CallMap[Inst] = {Inst.call(), CloneNo};
5045 }
5046 return {Func.func(), CloneNo};
5047}
5048
5049// We perform cloning for each allocation node separately. However, this
5050// sometimes results in a situation where the same node calls multiple
5051// clones of the same callee, created for different allocations. This
5052// causes issues when assigning functions to these clones, as each node can
5053// in reality only call a single callee clone.
5054//
5055// To address this, before assigning functions, merge callee clone nodes as
5056// needed using a post order traversal from the allocations. We attempt to
5057// use existing clones as the merge node when legal, and to share them
5058// among callers with the same properties (callers calling the same set of
5059// callee clone nodes for the same allocations).
5060//
5061// Without this fix, in some cases incorrect function assignment will lead
5062// to calling the wrong allocation clone.
5063template <typename DerivedCCG, typename FuncTy, typename CallTy>
5064void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones() {
5065 if (!MergeClones)
5066 return;
5067
5068 // Generate a map from context id to the associated allocation node for use
5069 // when merging clones.
5070 DenseMap<uint32_t, ContextNode *> ContextIdToAllocationNode;
5071 for (auto &Entry : AllocationCallToContextNodeMap) {
5072 auto *Node = Entry.second;
5073 for (auto Id : Node->getContextIds())
5074 ContextIdToAllocationNode[Id] = Node->getOrigNode();
5075 for (auto *Clone : Node->Clones) {
5076 for (auto Id : Clone->getContextIds())
5077 ContextIdToAllocationNode[Id] = Clone->getOrigNode();
5078 }
5079 }
5080
5081 // Post order traversal starting from allocations to ensure each callsite
5082 // calls a single clone of its callee. Callee nodes that are clones of each
5083 // other are merged (via new merge nodes if needed) to achieve this.
5084 DenseSet<const ContextNode *> Visited;
5085 for (auto &Entry : AllocationCallToContextNodeMap) {
5086 auto *Node = Entry.second;
5087
5088 mergeClones(Node, Visited, ContextIdToAllocationNode);
5089
5090 // Make a copy so the recursive post order traversal that may create new
5091 // clones doesn't mess up iteration. Note that the recursive traversal
5092 // itself does not call mergeClones on any of these nodes, which are all
5093 // (clones of) allocations.
5094 auto Clones = Node->Clones;
5095 for (auto *Clone : Clones)
5096 mergeClones(Clone, Visited, ContextIdToAllocationNode);
5097 }
5098
5099 if (DumpCCG) {
5100 dbgs() << "CCG after merging:\n";
5101 dbgs() << *this;
5102 }
5103 if (ExportToDot)
5104 exportToDot("aftermerge");
5105
5106 if (VerifyCCG) {
5107 check();
5108 }
5109}
5110
5111// Recursive helper for above mergeClones method.
5112template <typename DerivedCCG, typename FuncTy, typename CallTy>
5113void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones(
5114 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
5115 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
5116 auto Inserted = Visited.insert(Node);
5117 if (!Inserted.second)
5118 return;
5119
5120 // Iteratively perform merging on this node to handle new caller nodes created
5121 // during the recursive traversal. We could do something more elegant such as
5122 // maintain a worklist, but this is a simple approach that doesn't cause a
5123 // measureable compile time effect, as most nodes don't have many caller
5124 // edges to check.
5125 bool FoundUnvisited = true;
5126 unsigned Iters = 0;
5127 while (FoundUnvisited) {
5128 Iters++;
5129 FoundUnvisited = false;
5130 // Make a copy since the recursive call may move a caller edge to a new
5131 // callee, messing up the iterator.
5132 auto CallerEdges = Node->CallerEdges;
5133 for (auto CallerEdge : CallerEdges) {
5134 // Skip any caller edge moved onto a different callee during recursion.
5135 if (CallerEdge->Callee != Node)
5136 continue;
5137 // If we found an unvisited caller, note that we should check the caller
5138 // edges again as mergeClones may add or change caller nodes.
5139 if (DoMergeIteration && !Visited.contains(CallerEdge->Caller))
5140 FoundUnvisited = true;
5141 mergeClones(CallerEdge->Caller, Visited, ContextIdToAllocationNode);
5142 }
5143 }
5144
5145 TotalMergeInvokes++;
5146 TotalMergeIters += Iters;
5147 if (Iters > MaxMergeIters)
5148 MaxMergeIters = Iters;
5149
5150 // Merge for this node after we handle its callers.
5151 mergeNodeCalleeClones(Node, Visited, ContextIdToAllocationNode);
5152}
5153
5154template <typename DerivedCCG, typename FuncTy, typename CallTy>
5155void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeNodeCalleeClones(
5156 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
5157 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
5158 // Ignore Node if we moved all of its contexts to clones.
5159 if (Node->emptyContextIds())
5160 return;
5161
5162 // First identify groups of clones among Node's callee edges, by building
5163 // a map from each callee base node to the associated callee edges from Node.
5164 MapVector<ContextNode *, std::vector<std::shared_ptr<ContextEdge>>>
5165 OrigNodeToCloneEdges;
5166 for (const auto &E : Node->CalleeEdges) {
5167 auto *Callee = E->Callee;
5168 if (!Callee->CloneOf && Callee->Clones.empty())
5169 continue;
5170 ContextNode *Base = Callee->getOrigNode();
5171 OrigNodeToCloneEdges[Base].push_back(E);
5172 }
5173
5174 // Helper for callee edge sorting below. Return true if A's callee has fewer
5175 // caller edges than B, or if A is a clone and B is not, or if A's callee
5176 // node id is smaller than B's.
5177 auto CalleeCallerEdgeLessThan = [](const std::shared_ptr<ContextEdge> &A,
5178 const std::shared_ptr<ContextEdge> &B) {
5179 if (A->Callee->CallerEdges.size() != B->Callee->CallerEdges.size())
5180 return A->Callee->CallerEdges.size() < B->Callee->CallerEdges.size();
5181 if (A->Callee->CloneOf && !B->Callee->CloneOf)
5182 return true;
5183 else if (!A->Callee->CloneOf && B->Callee->CloneOf)
5184 return false;
5185 // Use the callee node id as a deterministic tie-breaker.
5186 return A->Callee->NodeId < B->Callee->NodeId;
5187 };
5188
5189 // Process each set of callee clones called by Node, performing the needed
5190 // merging.
5191 for (auto Entry : OrigNodeToCloneEdges) {
5192 // CalleeEdges is the set of edges from Node reaching callees that are
5193 // mutual clones of each other.
5194 auto &CalleeEdges = Entry.second;
5195 auto NumCalleeClones = CalleeEdges.size();
5196 // A single edge means there is no merging needed.
5197 if (NumCalleeClones == 1)
5198 continue;
5199 // Sort the CalleeEdges calling this group of clones in ascending order of
5200 // their caller edge counts, putting the original non-clone node first in
5201 // cases of a tie. This simplifies finding an existing node to use as the
5202 // merge node.
5203 llvm::stable_sort(CalleeEdges, CalleeCallerEdgeLessThan);
5204
5205 /// Find other callers of the given set of callee edges that can
5206 /// share the same callee merge node. See the comments at this method
5207 /// definition for details.
5208 DenseSet<ContextNode *> OtherCallersToShareMerge;
5209 findOtherCallersToShareMerge(Node, CalleeEdges, ContextIdToAllocationNode,
5210 OtherCallersToShareMerge);
5211
5212 // Now do the actual merging. Identify existing or create a new MergeNode
5213 // during the first iteration. Move each callee over, along with edges from
5214 // other callers we've determined above can share the same merge node.
5215 ContextNode *MergeNode = nullptr;
5216 DenseMap<ContextNode *, unsigned> CallerToMoveCount;
5217 for (auto CalleeEdge : CalleeEdges) {
5218 auto *OrigCallee = CalleeEdge->Callee;
5219 // If we don't have a MergeNode yet (only happens on the first iteration,
5220 // as a new one will be created when we go to move the first callee edge
5221 // over as needed), see if we can use this callee.
5222 if (!MergeNode) {
5223 // If there are no other callers, simply use this callee.
5224 if (CalleeEdge->Callee->CallerEdges.size() == 1) {
5225 MergeNode = OrigCallee;
5226 NonNewMergedNodes++;
5227 continue;
5228 }
5229 // Otherwise, if we have identified other caller nodes that can share
5230 // the merge node with Node, see if all of OrigCallee's callers are
5231 // going to share the same merge node. In that case we can use callee
5232 // (since all of its callers would move to the new merge node).
5233 if (!OtherCallersToShareMerge.empty()) {
5234 bool MoveAllCallerEdges = true;
5235 for (auto CalleeCallerE : OrigCallee->CallerEdges) {
5236 if (CalleeCallerE == CalleeEdge)
5237 continue;
5238 if (!OtherCallersToShareMerge.contains(CalleeCallerE->Caller)) {
5239 MoveAllCallerEdges = false;
5240 break;
5241 }
5242 }
5243 // If we are going to move all callers over, we can use this callee as
5244 // the MergeNode.
5245 if (MoveAllCallerEdges) {
5246 MergeNode = OrigCallee;
5247 NonNewMergedNodes++;
5248 continue;
5249 }
5250 }
5251 }
5252 // Move this callee edge, creating a new merge node if necessary.
5253 if (MergeNode) {
5254 assert(MergeNode != OrigCallee);
5255 moveEdgeToExistingCalleeClone(CalleeEdge, MergeNode,
5256 /*NewClone*/ false);
5257 } else {
5258 MergeNode = moveEdgeToNewCalleeClone(CalleeEdge);
5259 NewMergedNodes++;
5260 }
5261 // Now move all identified edges from other callers over to the merge node
5262 // as well.
5263 if (!OtherCallersToShareMerge.empty()) {
5264 // Make and iterate over a copy of OrigCallee's caller edges because
5265 // some of these will be moved off of the OrigCallee and that would mess
5266 // up the iteration from OrigCallee.
5267 auto OrigCalleeCallerEdges = OrigCallee->CallerEdges;
5268 for (auto &CalleeCallerE : OrigCalleeCallerEdges) {
5269 if (CalleeCallerE == CalleeEdge)
5270 continue;
5271 if (!OtherCallersToShareMerge.contains(CalleeCallerE->Caller))
5272 continue;
5273 CallerToMoveCount[CalleeCallerE->Caller]++;
5274 moveEdgeToExistingCalleeClone(CalleeCallerE, MergeNode,
5275 /*NewClone*/ false);
5276 }
5277 }
5278 removeNoneTypeCalleeEdges(OrigCallee);
5279 removeNoneTypeCalleeEdges(MergeNode);
5280 }
5281 }
5282}
5283
5284// Look for other nodes that have edges to the same set of callee
5285// clones as the current Node. Those can share the eventual merge node
5286// (reducing cloning and binary size overhead) iff:
5287// - they have edges to the same set of callee clones
5288// - each callee edge reaches a subset of the same allocations as Node's
5289// corresponding edge to the same callee clone.
5290// The second requirement is to ensure that we don't undo any of the
5291// necessary cloning to distinguish contexts with different allocation
5292// behavior.
5293// FIXME: This is somewhat conservative, as we really just need to ensure
5294// that they don't reach the same allocations as contexts on edges from Node
5295// going to any of the *other* callee clones being merged. However, that
5296// requires more tracking and checking to get right.
5297template <typename DerivedCCG, typename FuncTy, typename CallTy>
5298void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
5299 findOtherCallersToShareMerge(
5300 ContextNode *Node,
5301 std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
5302 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
5303 DenseSet<ContextNode *> &OtherCallersToShareMerge) {
5304 auto NumCalleeClones = CalleeEdges.size();
5305 // This map counts how many edges to the same callee clone exist for other
5306 // caller nodes of each callee clone.
5307 DenseMap<ContextNode *, unsigned> OtherCallersToSharedCalleeEdgeCount;
5308 // Counts the number of other caller nodes that have edges to all callee
5309 // clones that don't violate the allocation context checking.
5310 unsigned PossibleOtherCallerNodes = 0;
5311
5312 // We only need to look at other Caller nodes if the first callee edge has
5313 // multiple callers (recall they are sorted in ascending order above).
5314 if (CalleeEdges[0]->Callee->CallerEdges.size() < 2)
5315 return;
5316
5317 // For each callee edge:
5318 // - Collect the count of other caller nodes calling the same callees.
5319 // - Collect the alloc nodes reached by contexts on each callee edge.
5320 DenseMap<ContextEdge *, DenseSet<ContextNode *>> CalleeEdgeToAllocNodes;
5321 for (auto CalleeEdge : CalleeEdges) {
5322 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
5323 // For each other caller of the same callee, increment the count of
5324 // edges reaching the same callee clone.
5325 for (auto CalleeCallerEdges : CalleeEdge->Callee->CallerEdges) {
5326 if (CalleeCallerEdges->Caller == Node) {
5327 assert(CalleeCallerEdges == CalleeEdge);
5328 continue;
5329 }
5330 OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller]++;
5331 // If this caller edge now reaches all of the same callee clones,
5332 // increment the count of candidate other caller nodes.
5333 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller] ==
5334 NumCalleeClones)
5335 PossibleOtherCallerNodes++;
5336 }
5337 // Collect the alloc nodes reached by contexts on each callee edge, for
5338 // later analysis.
5339 for (auto Id : CalleeEdge->getContextIds()) {
5340 auto *Alloc = ContextIdToAllocationNode.lookup(Id);
5341 if (!Alloc) {
5342 // FIXME: unclear why this happens occasionally, presumably
5343 // imperfect graph updates possibly with recursion.
5344 MissingAllocForContextId++;
5345 continue;
5346 }
5347 CalleeEdgeToAllocNodes[CalleeEdge.get()].insert(Alloc);
5348 }
5349 }
5350
5351 // Now walk the callee edges again, and make sure that for each candidate
5352 // caller node all of its edges to the callees reach the same allocs (or
5353 // a subset) as those along the corresponding callee edge from Node.
5354 for (auto CalleeEdge : CalleeEdges) {
5355 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
5356 // Stop if we do not have any (more) candidate other caller nodes.
5357 if (!PossibleOtherCallerNodes)
5358 break;
5359 auto &CurCalleeAllocNodes = CalleeEdgeToAllocNodes[CalleeEdge.get()];
5360 // Check each other caller of this callee clone.
5361 for (auto &CalleeCallerE : CalleeEdge->Callee->CallerEdges) {
5362 // Not interested in the callee edge from Node itself.
5363 if (CalleeCallerE == CalleeEdge)
5364 continue;
5365 // Skip any callers that didn't have callee edges to all the same
5366 // callee clones.
5367 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] !=
5368 NumCalleeClones)
5369 continue;
5370 // Make sure that each context along edge from candidate caller node
5371 // reaches an allocation also reached by this callee edge from Node.
5372 for (auto Id : CalleeCallerE->getContextIds()) {
5373 auto *Alloc = ContextIdToAllocationNode.lookup(Id);
5374 if (!Alloc)
5375 continue;
5376 // If not, simply reset the map entry to 0 so caller is ignored, and
5377 // reduce the count of candidate other caller nodes.
5378 if (!CurCalleeAllocNodes.contains(Alloc)) {
5379 OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] = 0;
5380 PossibleOtherCallerNodes--;
5381 break;
5382 }
5383 }
5384 }
5385 }
5386
5387 if (!PossibleOtherCallerNodes)
5388 return;
5389
5390 // Build the set of other caller nodes that can use the same callee merge
5391 // node.
5392 for (auto &[OtherCaller, Count] : OtherCallersToSharedCalleeEdgeCount) {
5393 if (Count != NumCalleeClones)
5394 continue;
5395 OtherCallersToShareMerge.insert(OtherCaller);
5396 }
5397}
5398
5399template <typename DerivedCCG, typename FuncTy, typename CallTy>
5400const typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
5401CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::resolveImplicitSource(
5402 const ContextNode *Node, const ImplicitSource &Src) {
5403 if (!Src.Source->emptyContextIds())
5404 return Src.Source;
5405 // Src.Source lost its contexts to another clone (e.g. its last caller was
5406 // moved to a new clone when specializing a function clone further). The
5407 // trimmed contexts stay together, so the clone carrying one of them is the
5408 // version the implicit caller requires.
5409 if (Node->hasContextId(Src.ContextId))
5410 return Node;
5411 for (const ContextNode *C : Node->Clones)
5412 if (C->hasContextId(Src.ContextId))
5413 return C;
5414 // Context ids only move between the clones of a node during function
5415 // assignment, so the id should still be on one of them. Return null, which
5416 // makes the call follow the original node, rather than an emptied clone.
5417 assert(false && "trimmed context id on no clone of its callsite node");
5418 return nullptr;
5419}
5420
5421// Contexts whose call stacks were trimmed at a callsite node's frame are on
5422// its callee edges but on none of its caller edges. When that node, or one
5423// below it on the path of such a context, is cloned for the contexts of
5424// another allocation reaching it through a caller edge, the trimmed contexts
5425// stay with the node that was cloned, and the clone gets no edge to the callee
5426// nodes the trimmed contexts flow through. The clone is therefore not a caller
5427// of any clone of such a callee node, and would otherwise be assigned a
5428// function clone of the callee without regard to it, possibly one calling the
5429// wrong version of the callee for the trimmed contexts, which are agnostic to
5430// the callers of the node they were trimmed at and apply to the clone equally.
5431//
5432// This is called once the clones of callsite Node have been assigned to
5433// function clones. For each caller Y of a clone of Node whose edge carries
5434// trimmed contexts, each clone K of Y's original node that has no edge to any
5435// clone of Node, and which some of those trimmed contexts would reach (see
5436// ImpliesContextIds), is an implicit caller of Node. For example, with a
5437// context t trimmed at the frame of Y's callsite:
5438//
5439// (callers of Y) (callers of K)
5440// | |
5441// Y K clones of the same callsite node
5442// | \
5443// t | \ K has no edge to any clone of Node
5444// v v
5445// Required (other callsites in Node's function)
5446// (clone of Node called
5447// by Y, assigned to
5448// Y's function clone)
5449//
5450// Had t not been trimmed, it would also be on an edge from K, so K should get
5451// the same version of Node's function as Y:
5452// - If K was not yet assigned a function clone, assign it Y's, so that the
5453// assignment of the callsites it does have edges to takes it into account
5454// (creating further function clones derived from it if needed).
5455// - If K was already assigned to a function clone without a clone of Node,
5456// record that the Node call in that function clone should follow Required.
5457// - Otherwise K's function clone calls a conflicting clone of Node, which is
5458// left as is (and counted).
5459template <typename DerivedCCG, typename FuncTy, typename CallTy>
5460void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignImplicitCallers(
5461 ContextNode *Node, const DenseSet<uint32_t> &TrimmedContextIds,
5462 DenseMap<ContextNode *, FuncInfo> &CallsiteToCalleeFuncCloneMap,
5463 const std::map<FuncInfo, ContextNode *> &FuncCloneToCurNodeCloneMap,
5464 ImplicitSourceMap &ImplicitSources) {
5465 auto HasEdgeToNodeFamily = [&](const ContextNode *N) {
5466 return llvm::any_of(N->CalleeEdges,
5467 [&](const std::shared_ptr<ContextEdge> &E) {
5468 return E->Callee->getOrigNode() == Node;
5469 });
5470 };
5471 // Returns true if any of the trimmed context ids Ids, which are on (the
5472 // clone) Y but not on K, a clone of the same callsite node, would reach K had
5473 // they not been trimmed:
5474 // - An id terminating at Y applies to all clones of Y's original node (see
5475 // the example above assignImplicitCallers).
5476 // - An id reaching Y from a caller Z applies to K only if it would equally
5477 // apply to some caller C of K that is a clone of Z's original node, i.e.
5478 // it is not on C (if it were, C explicitly directs it to a callee other
5479 // than K) and, recursively, it applies to C the way it applies to Z (e.g.
5480 // because it terminates at Z, so it applies to all clones of Z's original
5481 // node). The id would then flow from C to K just as it flows from Z to Y,
5482 // had it not been trimmed:
5483 //
5484 // ... ... t terminates at Z or one of its callers
5485 // |
5486 // Z C clones of the same callsite node
5487 // | :
5488 // t | : (t) t is not on C or K; it applies to them
5489 // v v because it was trimmed above
5490 // Y K clones of the same callsite node
5491 // |
5492 // t v
5493 // Required
5494 //
5495 // This is checked recursively on (C, Z) with the ids not on C. If C == Z,
5496 // Z explicitly directs the ids to Y rather than K, so they don't apply to
5497 // K.
5498 //
5499 // Visited records the ids already examined for each (K, Y) pair, which
5500 // guards against cycles from recursion while still examining ids first seen
5501 // for the pair on a reconverging caller chain.
5502 auto ImpliesContextIds =
5503 [&](ContextNode *K, ContextNode *Y, const DenseSet<uint32_t> &Ids,
5504 DenseMap<std::pair<ContextNode *, ContextNode *>, DenseSet<uint32_t>>
5505 &Visited,
5506 auto &&ImpliesContextIds) -> bool {
5507 assert(K->getOrigNode() == Y->getOrigNode());
5508 DenseSet<uint32_t> &VisitedIds = Visited[{K, Y}];
5509 DenseSet<uint32_t> NewIds;
5510 for (auto Id : Ids)
5511 if (VisitedIds.insert(Id).second)
5512 NewIds.insert(Id);
5513 if (NewIds.empty())
5514 return false;
5515 // The ids found on each caller edge of Y, with that edge's caller Z, and
5516 // their union (a set rather than a count, as a recursive context can put
5517 // the same id on several caller edges).
5519 DenseSet<uint32_t> IdsOnCallerEdges;
5520 for (auto &YEdge : Y->CallerEdges) {
5521 DenseSet<uint32_t> IdsFromZ =
5522 set_intersection(NewIds, YEdge->getContextIds());
5523 if (IdsFromZ.empty())
5524 continue;
5525 set_union(IdsOnCallerEdges, IdsFromZ);
5526 IdsFromCallers.push_back({YEdge->Caller, std::move(IdsFromZ)});
5527 }
5528 // Any ids on none of Y's caller edges terminate at Y, and so apply to all
5529 // clones of Y's original node, including K.
5530 if (IdsOnCallerEdges.size() < NewIds.size())
5531 return true;
5532 // Otherwise check whether the ids reaching Y from a caller Z also apply to
5533 // K through a caller C of K that is a clone of Z's original node.
5534 for (auto &[Z, IdsFromZ] : IdsFromCallers) {
5535 for (auto &KEdge : K->CallerEdges) {
5536 ContextNode *C = KEdge->Caller;
5537 if (C == Z || C->getOrigNode() != Z->getOrigNode())
5538 continue;
5539 // Only the ids not on C can apply to C implicitly (C directs the ones
5540 // it has elsewhere); recursively check whether they do.
5541 DenseSet<uint32_t> IdsNotOnC;
5542 for (auto Id : IdsFromZ)
5543 if (!C->hasContextId(Id))
5544 IdsNotOnC.insert(Id);
5545 if (!IdsNotOnC.empty() &&
5546 ImpliesContextIds(C, Z, IdsNotOnC, Visited, ImpliesContextIds))
5547 return true;
5548 }
5549 }
5550 return false;
5551 };
5552 // Returns true if the given clones of Node are interchangeable for an
5553 // implicit caller: the same clone, allocations with the same hint, or
5554 // callsites already assigned to call the same function clone.
5555 auto SameVersion = [&](const ContextNode *A, const ContextNode *B) {
5556 if (A == B)
5557 return true;
5558 if (Node->IsAllocation)
5559 return allocTypeToUse(A->AllocTypes) == allocTypeToUse(B->AllocTypes);
5560 auto AIt = CallsiteToCalleeFuncCloneMap.find(A);
5561 auto BIt = CallsiteToCalleeFuncCloneMap.find(B);
5562 return AIt != CallsiteToCalleeFuncCloneMap.end() &&
5563 BIt != CallsiteToCalleeFuncCloneMap.end() &&
5564 AIt->second == BIt->second;
5565 };
5566 // The clones already identified as implicit callers of Node, so that each is
5567 // handled once (for the first caller edge whose trimmed contexts reach it).
5568 DenseSet<const ContextNode *> ImplicitCallers;
5569 // Handles the caller edge Edge of a clone of Node (or of Node itself): finds
5570 // the implicit callers among the clones of its caller Y's original node, and
5571 // assigns them, or records the clone of Node their calls must follow, as
5572 // described above.
5573 auto ProcessCaller = [&](const std::shared_ptr<ContextEdge> &Edge) {
5574 ContextNode *Y = Edge->Caller;
5575 ContextNode *Orig = Y->getOrigNode();
5576 if (!Y->hasCall() || Orig->Clones.empty())
5577 return;
5578 DenseSet<uint32_t> TrimmedIds =
5579 set_intersection(Edge->getContextIds(), TrimmedContextIds);
5580 if (TrimmedIds.empty())
5581 return;
5582 auto YIt = CallsiteToCalleeFuncCloneMap.find(Y);
5583 if (YIt == CallsiteToCalleeFuncCloneMap.end())
5584 return;
5585 // Copy, as recording assignments below may grow the map.
5586 const FuncInfo YFuncClone = YIt->second;
5587 // The clone of Node called by Y, which must be assigned to the same
5588 // function clone.
5589 auto RequiredIt = FuncCloneToCurNodeCloneMap.find(YFuncClone);
5590 assert(RequiredIt != FuncCloneToCurNodeCloneMap.end());
5591 const ContextNode *Required = RequiredIt->second;
5592 // Record in ImplicitSources that the Node call in function clone F must
5593 // follow the callsite clone Src. This is consulted when the calls in
5594 // function clones without their own clone of Node are collected (see
5595 // UnassignedCallClones in assignFunctions), and makes the requirement
5596 // survive if Src is later moved to another function clone derived from F
5597 // (when one of its callers conflicts at another callsite), after which the
5598 // call in F would otherwise follow the function clone F was derived from.
5599 auto RecordImplicitSource = [&](const FuncInfo &F, const ContextNode *Src) {
5600 // The calls in the original function (clone 0) are not collected there,
5601 // so nothing can be recorded for it.
5602 if (F.cloneNo() != 0)
5603 ImplicitSources.try_emplace({Node, F.cloneNo()},
5604 ImplicitSource{Src, *TrimmedIds.begin()});
5605 };
5606 // Check each clone of Y's original node (and the original itself) without
5607 // an edge to any clone of Node.
5608 for (ContextNode *K : llvm::concat<ContextNode *const>(
5609 Orig->Clones, ArrayRef<ContextNode *>(Orig))) {
5610 if (K == Y || !K->hasCall() || K->emptyContextIds() ||
5611 HasEdgeToNodeFamily(K) || ImplicitCallers.contains(K))
5612 continue;
5613 DenseMap<std::pair<ContextNode *, ContextNode *>, DenseSet<uint32_t>>
5614 Visited;
5615 if (!ImpliesContextIds(K, Y, TrimmedIds, Visited, ImpliesContextIds))
5616 continue;
5617 // K is an implicit caller of Node.
5618 ImplicitCallers.insert(K);
5619 auto KIt = CallsiteToCalleeFuncCloneMap.find(K);
5620 if (KIt == CallsiteToCalleeFuncCloneMap.end()) {
5621 // Not yet assigned: give it Y's function clone, in which the Node call
5622 // then follows Required.
5623 CallsiteToCalleeFuncCloneMap[K] = YFuncClone;
5624 RecordImplicitSource(YFuncClone, Required);
5625 NumImplicitCallersAssigned++;
5626 continue;
5627 }
5628 const FuncInfo KFuncClone = KIt->second;
5629 if (KFuncClone == YFuncClone) {
5630 // Already in Y's function clone.
5631 RecordImplicitSource(YFuncClone, Required);
5632 continue;
5633 }
5634 unsigned KCloneNo = KFuncClone.cloneNo();
5635 auto KNodeCloneIt = FuncCloneToCurNodeCloneMap.find(KFuncClone);
5636 if (KNodeCloneIt == FuncCloneToCurNodeCloneMap.end()) {
5637 // K's function clone has no clone of Node.
5638 if (KCloneNo == 0) {
5639 // The call in the original function keeps calling the original
5640 // callee function, or stays unhinted for an allocation. That
5641 // satisfies the requirement only if Required is that version.
5642 if (Node->IsAllocation) {
5643 if (allocTypeToUse(Required->AllocTypes) == AllocationType::NotCold)
5644 continue;
5645 } else if (auto It = CallsiteToCalleeFuncCloneMap.find(Required);
5646 It != CallsiteToCalleeFuncCloneMap.end() &&
5647 It->second.cloneNo() == 0)
5648 continue;
5649 } else {
5650 // Record that the Node call in K's function clone must follow
5651 // Required, unless an earlier implicit caller already recorded a
5652 // conflicting clone.
5653 auto [It, Inserted] = ImplicitSources.try_emplace(
5654 {Node, KCloneNo}, ImplicitSource{Required, *TrimmedIds.begin()});
5655 if (Inserted)
5656 NumImplicitCallersSourced++;
5657 if (SameVersion(It->second.Source, Required))
5658 continue;
5659 }
5660 } else if (SameVersion(KNodeCloneIt->second, Required)) {
5661 // K's function clone has a clone of Node interchangeable with
5662 // Required.
5663 RecordImplicitSource(KFuncClone, KNodeCloneIt->second);
5664 continue;
5665 }
5666 // K's function clone calls a conflicting clone of Node.
5667 NumImplicitCallersUnresolved++;
5668 }
5669 };
5670 // Process the caller edges of Node itself and of each of its clones: any of
5671 // them may carry trimmed contexts (a trimmed context stays with the clone
5672 // that was cloned, which may be Node or a clone made earlier).
5673 for (auto &Edge : Node->CallerEdges)
5674 ProcessCaller(Edge);
5675 for (auto *Clone : Node->Clones)
5676 for (auto &Edge : Clone->CallerEdges)
5677 ProcessCaller(Edge);
5678}
5679
5680// This method assigns cloned callsites to functions, cloning the functions as
5681// needed. The assignment is greedy and proceeds roughly as follows:
5682//
5683// For each function Func:
5684// For each call with graph Node having clones:
5685// Initialize ClonesWorklist to Node and its clones
5686// Initialize NodeCloneCount to 0
5687// While ClonesWorklist is not empty:
5688// Clone = pop front ClonesWorklist
5689// NodeCloneCount++
5690// If Func has been cloned less than NodeCloneCount times:
5691// If NodeCloneCount is 1:
5692// Assign Clone to original Func
5693// Continue
5694// Create a new function clone
5695// If other callers not assigned to call a function clone yet:
5696// Assign them to call new function clone
5697// Continue
5698// Assign any other caller calling the cloned version to new clone
5699//
5700// For each caller of Clone:
5701// If caller is assigned to call a specific function clone:
5702// If we cannot assign Clone to that function clone:
5703// Create new callsite Clone NewClone
5704// Add NewClone to ClonesWorklist
5705// Continue
5706// Assign Clone to existing caller's called function clone
5707// Else:
5708// If Clone not already assigned to a function clone:
5709// Assign to first function clone without assignment
5710// Assign caller to selected function clone
5711// For each call with graph Node having clones:
5712// If number func clones > number call's callsite Node clones:
5713// Record func CallInfo clones without Node clone in UnassignedCallClones
5714// For callsite Nodes in DFS order from allocations:
5715// If IsAllocation:
5716// Update allocation with alloc type
5717// Else:
5718// For Call, all MatchingCalls, and associated UnnassignedCallClones:
5719// Update call to call recorded callee clone
5720//
5721template <typename DerivedCCG, typename FuncTy, typename CallTy>
5722bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignFunctions() {
5723 bool Changed = false;
5724
5725 mergeClones();
5726
5727 // Context ids terminating at a non-allocation node which has or had callers
5728 // (i.e. is not a root), meaning their call stacks were trimmed there. Used
5729 // to identify implicit callers (see assignImplicitCallers).
5730 DenseSet<uint32_t> TrimmedContextIds;
5731 for (auto &NodePtr : NodeOwner) {
5732 ContextNode *N = NodePtr.get();
5733 if (N->IsAllocation || N->CalleeEdges.empty() ||
5734 (N->CallerEdges.empty() && N->Clones.empty() && !N->CloneOf))
5735 continue;
5736 // A context id trimmed at N is on a callee edge but on no caller edge.
5737 // Compare distinct ids rather than edge sizes: a recursive context can put
5738 // the same id on several callee and caller edges of N.
5739 DenseSet<uint32_t> CallerIds;
5740 for (auto &E : N->CallerEdges)
5741 set_union(CallerIds, E->getContextIds());
5742 for (auto &CalleeEdge : N->CalleeEdges)
5743 for (auto Id : CalleeEdge->getContextIds())
5744 if (!CallerIds.contains(Id))
5745 TrimmedContextIds.insert(Id);
5746 }
5747 NumTrimmedContextIds += TrimmedContextIds.size();
5748
5749 // Keep track of the assignment of nodes (callsites) to function clones they
5750 // call.
5751 DenseMap<ContextNode *, FuncInfo> CallsiteToCalleeFuncCloneMap;
5752
5753 // Update caller node to call function version CalleeFunc, by recording the
5754 // assignment in CallsiteToCalleeFuncCloneMap.
5755 auto RecordCalleeFuncOfCallsite = [&](ContextNode *Caller,
5756 const FuncInfo &CalleeFunc) {
5757 assert(Caller->hasCall());
5758 CallsiteToCalleeFuncCloneMap[Caller] = CalleeFunc;
5759 };
5760
5761 // Information for a single clone of this Func.
5762 struct FuncCloneInfo {
5763 // The function clone.
5764 FuncInfo FuncClone;
5765 // Remappings of each call of interest (from original uncloned call to the
5766 // corresponding cloned call in this function clone).
5767 DenseMap<CallInfo, CallInfo> CallMap;
5768 };
5769
5770 // Map to keep track of information needed to update calls in function clones
5771 // when their corresponding callsite node was not itself cloned for that
5772 // function clone. Because of call context trimming (i.e. we only keep as much
5773 // caller information as needed to distinguish hot vs cold), we may not have
5774 // caller edges coming to each callsite node from all possible function
5775 // callers. A function clone may get created for other callsites in the
5776 // function for which there are caller edges that were not trimmed. Any other
5777 // callsites in that function clone, which were not themselved cloned for
5778 // that function clone, should get updated the same way as the corresponding
5779 // callsite in the original function (which may call a clone of its callee).
5780 //
5781 // We build this map after completing function cloning for each function, so
5782 // that we can record the information from its call maps before they are
5783 // destructed. The map will be used as we update calls to update any still
5784 // unassigned call clones. Note that we may create new node clones as we clone
5785 // other functions, so later on we check which node clones were still not
5786 // created. To this end, the inner map is a map from function clone number to
5787 // the list of calls cloned for that function (can be more than one due to the
5788 // Node's MatchingCalls array).
5789 //
5790 // The alternative is creating new callsite clone nodes below as we clone the
5791 // function, but that is tricker to get right and likely more overhead.
5792 //
5793 // Each entry also records the callsite node whose callee assignment the
5794 // calls should follow (Source). By default that is the callsite clone (if
5795 // any) in the function clone the function clone was derived from, following
5796 // the chain of derivations to the original function, since a function clone
5797 // created to specialize another one should otherwise behave like it. It can
5798 // also be the callsite clone required by an implicit caller (see
5799 // assignImplicitCallers). A null Source means the original node.
5800 //
5801 // Inner map is a std::map so sorted by key (clone number), in order to get
5802 // ordered remarks in the full LTO case.
5803 struct UnassignedCallCloneInfo {
5805 const ContextNode *Source = nullptr;
5806 };
5807 DenseMap<const ContextNode *, std::map<unsigned, UnassignedCallCloneInfo>>
5808 UnassignedCallClones;
5809
5810 // Walk all functions for which we saw calls with memprof metadata, and handle
5811 // cloning for each of its calls.
5812 for (auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
5813 FuncInfo OrigFunc(Func);
5814 // Map from each clone number of OrigFunc to information about that function
5815 // clone (the function clone FuncInfo and call remappings). The index into
5816 // the vector is the clone number, as function clones are created and
5817 // numbered sequentially.
5818 std::vector<FuncCloneInfo> FuncCloneInfos;
5819 // For each function clone number, the clone number of the function clone
5820 // it was derived from (created to further specialize, when a caller
5821 // already assigned to it needed a different clone of some callsite), or 0
5822 // for clones created from the original function. Used to decide which
5823 // callsite clone the calls not themselves cloned for a function clone
5824 // should follow (see UnassignedCallClones).
5825 std::vector<unsigned> FuncCloneParent;
5826 // Callsite clones required for calls in specific function clones by
5827 // implicit callers (see assignImplicitCallers).
5828 ImplicitSourceMap ImplicitSources;
5829 // Map from each original callsite node in this function to its original
5830 // call and matching calls (clone 0). The calls recorded on an original node
5831 // are updated to the calls in a function clone if that node is assigned to
5832 // a function clone, after which they can no longer be used to index the
5833 // function clone CallMaps (which are keyed by the original calls). No node
5834 // in this function has been assigned yet at this point.
5835 struct OrigCallsInfo {
5836 CallInfo Call;
5837 SmallVector<CallInfo, 0> MatchingCalls;
5838 };
5839 DenseMap<const ContextNode *, OrigCallsInfo> OrigNodeToOrigCalls;
5840 for (auto &Call : CallsWithMetadata) {
5841 ContextNode *Node = getNodeForInst(Call);
5842 if (Node && Node->Call == Call)
5843 OrigNodeToOrigCalls[Node] = {Call, Node->MatchingCalls};
5844 }
5845 for (auto &Call : CallsWithMetadata) {
5846 ContextNode *Node = getNodeForInst(Call);
5847 // Skip call if we do not have a node for it (all uses of its stack ids
5848 // were either on inlined chains or trimmed from the MIBs), or if we did
5849 // not create any clones for it.
5850 if (!Node || Node->Clones.empty())
5851 continue;
5852 assert(Node->hasCall() &&
5853 "Not having a call should have prevented cloning");
5854
5855 // Track the assignment of function clones to clones of the current
5856 // callsite Node being handled.
5857 std::map<FuncInfo, ContextNode *> FuncCloneToCurNodeCloneMap;
5858
5859 // Assign callsite version CallsiteClone to function version FuncClone,
5860 // and also assign (possibly cloned) Call to CallsiteClone.
5861 auto AssignCallsiteCloneToFuncClone = [&](const FuncInfo &FuncClone,
5862 CallInfo &Call,
5863 ContextNode *CallsiteClone,
5864 bool IsAlloc) {
5865 // Record the clone of callsite node assigned to this function clone.
5866 FuncCloneToCurNodeCloneMap[FuncClone] = CallsiteClone;
5867
5868 assert(FuncCloneInfos.size() > FuncClone.cloneNo());
5869 DenseMap<CallInfo, CallInfo> &CallMap =
5870 FuncCloneInfos[FuncClone.cloneNo()].CallMap;
5871 CallInfo CallClone(Call);
5872 if (auto It = CallMap.find(Call); It != CallMap.end())
5873 CallClone = It->second;
5874 CallsiteClone->setCall(CallClone);
5875 // Need to do the same for all matching calls. Rebuild the list of
5876 // CallsiteClone from the original matching calls (it may have been
5877 // copied from a node whose calls were already remapped), using the
5878 // same mapping as for Call.
5879 assert(OrigNodeToOrigCalls.count(Node));
5880 CallsiteClone->MatchingCalls.clear();
5881 for (const CallInfo &OrigMatchingCall :
5882 OrigNodeToOrigCalls[Node].MatchingCalls) {
5883 CallInfo CallClone(OrigMatchingCall);
5884 if (auto It = CallMap.find(OrigMatchingCall); It != CallMap.end())
5885 CallClone = It->second;
5886 CallsiteClone->MatchingCalls.push_back(CallClone);
5887 }
5888 };
5889
5890 // Invokes moveEdgeToNewCalleeClone which creates a new clone, and then
5891 // performs the necessary fixups (removing none type edges, and
5892 // importantly, propagating any function call assignment of the original
5893 // node to the new clone).
5894 auto MoveEdgeToNewCalleeCloneAndSetUp =
5895 [&](const std::shared_ptr<ContextEdge> &Edge) {
5896 ContextNode *OrigCallee = Edge->Callee;
5897 ContextNode *NewClone = moveEdgeToNewCalleeClone(Edge);
5898 removeNoneTypeCalleeEdges(NewClone);
5899 assert(NewClone->AllocTypes != (uint8_t)AllocationType::None);
5900 // If the original Callee was already assigned to call a specific
5901 // function version, make sure its new clone is assigned to call
5902 // that same function clone.
5903 if (CallsiteToCalleeFuncCloneMap.count(OrigCallee))
5904 RecordCalleeFuncOfCallsite(
5905 NewClone, CallsiteToCalleeFuncCloneMap[OrigCallee]);
5906 return NewClone;
5907 };
5908
5909 // Keep track of the clones of callsite Node that need to be assigned to
5910 // function clones. This list may be expanded in the loop body below if we
5911 // find additional cloning is required.
5912 std::deque<ContextNode *> ClonesWorklist;
5913 // Ignore original Node if we moved all of its contexts to clones.
5914 if (!Node->emptyContextIds())
5915 ClonesWorklist.push_back(Node);
5916 llvm::append_range(ClonesWorklist, Node->Clones);
5917
5918 // Now walk through all of the clones of this callsite Node that we need,
5919 // and determine the assignment to a corresponding clone of the current
5920 // function (creating new function clones as needed).
5921 unsigned NodeCloneCount = 0;
5922 while (!ClonesWorklist.empty()) {
5923 ContextNode *Clone = ClonesWorklist.front();
5924 ClonesWorklist.pop_front();
5925 NodeCloneCount++;
5926 if (VerifyNodes)
5928
5929 // Need to create a new function clone if we have more callsite clones
5930 // than existing function clones, which would have been assigned to an
5931 // earlier clone in the list (we assign callsite clones to function
5932 // clones greedily).
5933 if (FuncCloneInfos.size() < NodeCloneCount) {
5934 // If this is the first callsite copy, assign to original function.
5935 if (NodeCloneCount == 1) {
5936 // Since FuncCloneInfos is empty in this case, no clones have
5937 // been created for this function yet, and no callers should have
5938 // been assigned a function clone for this callee node yet.
5940 Clone->CallerEdges, [&](const std::shared_ptr<ContextEdge> &E) {
5941 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
5942 }));
5943 // Initialize with empty call map, assign Clone to original function
5944 // and its callers, and skip to the next clone.
5945 FuncCloneInfos.push_back(
5946 {OrigFunc, DenseMap<CallInfo, CallInfo>()});
5947 FuncCloneParent.push_back(0);
5948 AssignCallsiteCloneToFuncClone(
5949 OrigFunc, Call, Clone,
5950 AllocationCallToContextNodeMap.count(Call));
5951 for (auto &CE : Clone->CallerEdges) {
5952 // Ignore any caller that does not have a recorded callsite Call.
5953 if (!CE->Caller->hasCall())
5954 continue;
5955 RecordCalleeFuncOfCallsite(CE->Caller, OrigFunc);
5956 }
5957 continue;
5958 }
5959
5960 // First locate which copy of OrigFunc to clone again. If a caller
5961 // of this callsite clone was already assigned to call a particular
5962 // function clone, we need to redirect all of those callers to the
5963 // new function clone, and update their other callees within this
5964 // function.
5965 FuncInfo PreviousAssignedFuncClone;
5966 auto EI = llvm::find_if(
5967 Clone->CallerEdges, [&](const std::shared_ptr<ContextEdge> &E) {
5968 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
5969 });
5970 bool CallerAssignedToCloneOfFunc = false;
5971 if (EI != Clone->CallerEdges.end()) {
5972 const std::shared_ptr<ContextEdge> &Edge = *EI;
5973 PreviousAssignedFuncClone =
5974 CallsiteToCalleeFuncCloneMap[Edge->Caller];
5975 CallerAssignedToCloneOfFunc = true;
5976 }
5977
5978 // Clone function and save it along with the CallInfo map created
5979 // during cloning in the FuncCloneInfos.
5980 DenseMap<CallInfo, CallInfo> NewCallMap;
5981 unsigned CloneNo = FuncCloneInfos.size();
5982 assert(CloneNo > 0 && "Clone 0 is the original function, which "
5983 "should already exist in the map");
5984 FuncInfo NewFuncClone = cloneFunctionForCallsite(
5985 OrigFunc, Call, NewCallMap, CallsWithMetadata, CloneNo);
5986 FuncCloneInfos.push_back({NewFuncClone, std::move(NewCallMap)});
5987 // Record the function clone it is derived from (if any), whose
5988 // callers it will take over below.
5989 FuncCloneParent.push_back(CallerAssignedToCloneOfFunc
5990 ? PreviousAssignedFuncClone.cloneNo()
5991 : 0);
5992 FunctionClonesAnalysis++;
5993 Changed = true;
5994
5995 // If no caller callsites were already assigned to a clone of this
5996 // function, we can simply assign this clone to the new func clone
5997 // and update all callers to it, then skip to the next clone.
5998 if (!CallerAssignedToCloneOfFunc) {
5999 AssignCallsiteCloneToFuncClone(
6000 NewFuncClone, Call, Clone,
6001 AllocationCallToContextNodeMap.count(Call));
6002 for (auto &CE : Clone->CallerEdges) {
6003 // Ignore any caller that does not have a recorded callsite Call.
6004 if (!CE->Caller->hasCall())
6005 continue;
6006 RecordCalleeFuncOfCallsite(CE->Caller, NewFuncClone);
6007 }
6008 continue;
6009 }
6010
6011 // We may need to do additional node cloning in this case.
6012 // Reset the CallsiteToCalleeFuncCloneMap entry for any callers
6013 // that were previously assigned to call PreviousAssignedFuncClone,
6014 // to record that they now call NewFuncClone.
6015 // The none type edge removal may remove some of this Clone's caller
6016 // edges, if it is reached via another of its caller's callees.
6017 // Iterate over a copy and skip any that were removed.
6018 auto CallerEdges = Clone->CallerEdges;
6019 for (auto CE : CallerEdges) {
6020 // Skip any that have been removed on an earlier iteration.
6021 if (CE->isRemoved()) {
6022 assert(!is_contained(Clone->CallerEdges, CE));
6023 continue;
6024 }
6025 assert(CE);
6026 // Ignore any caller that does not have a recorded callsite Call.
6027 if (!CE->Caller->hasCall())
6028 continue;
6029
6030 if (!CallsiteToCalleeFuncCloneMap.count(CE->Caller) ||
6031 // We subsequently fall through to later handling that
6032 // will perform any additional cloning required for
6033 // callers that were calling other function clones.
6034 CallsiteToCalleeFuncCloneMap[CE->Caller] !=
6035 PreviousAssignedFuncClone)
6036 continue;
6037
6038 RecordCalleeFuncOfCallsite(CE->Caller, NewFuncClone);
6039
6040 // If we are cloning a function that was already assigned to some
6041 // callers, then essentially we are creating new callsite clones
6042 // of the other callsites in that function that are reached by those
6043 // callers. Clone the other callees of the current callsite's caller
6044 // that were already assigned to PreviousAssignedFuncClone
6045 // accordingly. This is important since we subsequently update the
6046 // calls from the nodes in the graph and their assignments to callee
6047 // functions recorded in CallsiteToCalleeFuncCloneMap.
6048 // The none type edge removal may remove some of this caller's
6049 // callee edges, if it is reached via another of its callees.
6050 // Iterate over a copy and skip any that were removed.
6051 auto CalleeEdges = CE->Caller->CalleeEdges;
6052 for (auto CalleeEdge : CalleeEdges) {
6053 // Skip any that have been removed on an earlier iteration when
6054 // cleaning up newly None type callee edges.
6055 if (CalleeEdge->isRemoved()) {
6056 assert(!is_contained(CE->Caller->CalleeEdges, CalleeEdge));
6057 continue;
6058 }
6059 assert(CalleeEdge);
6060 ContextNode *Callee = CalleeEdge->Callee;
6061 // Skip the current callsite, we are looking for other
6062 // callsites Caller calls, as well as any that does not have a
6063 // recorded callsite Call.
6064 if (Callee == Clone || !Callee->hasCall())
6065 continue;
6066 // Skip direct recursive calls. We don't need/want to clone the
6067 // caller node again, and this loop will not behave as expected if
6068 // we tried.
6069 if (Callee == CalleeEdge->Caller)
6070 continue;
6071 ContextNode *NewClone =
6072 MoveEdgeToNewCalleeCloneAndSetUp(CalleeEdge);
6073 // Moving the edge may have resulted in some none type
6074 // callee edges on the original Callee.
6075 removeNoneTypeCalleeEdges(Callee);
6076 // Update NewClone with the new Call clone of this callsite's Call
6077 // created for the new function clone created earlier.
6078 // Recall that we have already ensured when building the graph
6079 // that each caller can only call callsites within the same
6080 // function, so we are guaranteed that Callee Call is in the
6081 // current OrigFunc.
6082 // CallMap is set up as indexed by original calls at clone 0. Note
6083 // that we cannot simply use the calls recorded on Callee's
6084 // original node, as those are updated to the calls in a function
6085 // clone if the original node was itself assigned to a function
6086 // clone.
6087 assert(OrigNodeToOrigCalls.count(Callee->getOrigNode()));
6088 auto &OrigCalls = OrigNodeToOrigCalls[Callee->getOrigNode()];
6089 DenseMap<CallInfo, CallInfo> &CallMap =
6090 FuncCloneInfos[NewFuncClone.cloneNo()].CallMap;
6091 assert(CallMap.count(OrigCalls.Call));
6092 CallInfo NewCall(CallMap[OrigCalls.Call]);
6093 assert(NewCall);
6094 NewClone->setCall(NewCall);
6095 // Need to do the same for all matching calls.
6096 NewClone->MatchingCalls.clear();
6097 for (auto &OrigMatchingCall : OrigCalls.MatchingCalls) {
6098 assert(CallMap.count(OrigMatchingCall));
6099 CallInfo NewCall(CallMap[OrigMatchingCall]);
6100 assert(NewCall);
6101 NewClone->MatchingCalls.push_back(NewCall);
6102 }
6103 }
6104 }
6105 // Fall through to handling below to perform the recording of the
6106 // function for this callsite clone. This enables handling of cases
6107 // where the callers were assigned to different clones of a function.
6108 }
6109
6110 auto FindFirstAvailFuncClone = [&]() {
6111 // Find first function in FuncCloneInfos without an assigned
6112 // clone of this callsite Node. We should always have one
6113 // available at this point due to the earlier cloning when the
6114 // FuncCloneInfos size was smaller than the clone number.
6115 for (auto &CF : FuncCloneInfos) {
6116 if (!FuncCloneToCurNodeCloneMap.count(CF.FuncClone))
6117 return CF.FuncClone;
6118 }
6120 "Expected an available func clone for this callsite clone");
6121 };
6122
6123 // See if we can use existing function clone. Walk through
6124 // all caller edges to see if any have already been assigned to
6125 // a clone of this callsite's function. If we can use it, do so. If not,
6126 // because that function clone is already assigned to a different clone
6127 // of this callsite, then we need to clone again.
6128 // Basically, this checking is needed to handle the case where different
6129 // caller functions/callsites may need versions of this function
6130 // containing different mixes of callsite clones across the different
6131 // callsites within the function. If that happens, we need to create
6132 // additional function clones to handle the various combinations.
6133 //
6134 // Keep track of any new clones of this callsite created by the
6135 // following loop, as well as any existing clone that we decided to
6136 // assign this clone to.
6137 std::map<FuncInfo, ContextNode *> FuncCloneToNewCallsiteCloneMap;
6138 FuncInfo FuncCloneAssignedToCurCallsiteClone;
6139 // Iterate over a copy of Clone's caller edges, since we may need to
6140 // remove edges in the moveEdgeTo* methods, and this simplifies the
6141 // handling and makes it less error-prone.
6142 auto CloneCallerEdges = Clone->CallerEdges;
6143 for (auto &Edge : CloneCallerEdges) {
6144 // Skip removed edges (due to direct recursive edges updated when
6145 // updating callee edges when moving an edge and subsequently
6146 // removed by call to removeNoneTypeCalleeEdges on the Clone).
6147 if (Edge->isRemoved())
6148 continue;
6149 // Ignore any caller that does not have a recorded callsite Call.
6150 if (!Edge->Caller->hasCall())
6151 continue;
6152 // If this caller already assigned to call a version of OrigFunc, need
6153 // to ensure we can assign this callsite clone to that function clone.
6154 if (CallsiteToCalleeFuncCloneMap.count(Edge->Caller)) {
6155 FuncInfo FuncCloneCalledByCaller =
6156 CallsiteToCalleeFuncCloneMap[Edge->Caller];
6157 // First we need to confirm that this function clone is available
6158 // for use by this callsite node clone.
6159 //
6160 // While FuncCloneToCurNodeCloneMap is built only for this Node and
6161 // its callsite clones, one of those callsite clones X could have
6162 // been assigned to the same function clone called by Edge's caller
6163 // - if Edge's caller calls another callsite within Node's original
6164 // function, and that callsite has another caller reaching clone X.
6165 // We need to clone Node again in this case.
6166 if ((FuncCloneToCurNodeCloneMap.count(FuncCloneCalledByCaller) &&
6167 FuncCloneToCurNodeCloneMap[FuncCloneCalledByCaller] !=
6168 Clone) ||
6169 // Detect when we have multiple callers of this callsite that
6170 // have already been assigned to specific, and different, clones
6171 // of OrigFunc (due to other unrelated callsites in Func they
6172 // reach via call contexts). Is this Clone of callsite Node
6173 // assigned to a different clone of OrigFunc? If so, clone Node
6174 // again.
6175 (FuncCloneAssignedToCurCallsiteClone &&
6176 FuncCloneAssignedToCurCallsiteClone !=
6177 FuncCloneCalledByCaller)) {
6178 // We need to use a different newly created callsite clone, in
6179 // order to assign it to another new function clone on a
6180 // subsequent iteration over the Clones array (adjusted below).
6181 // Note we specifically do not reset the
6182 // CallsiteToCalleeFuncCloneMap entry for this caller, so that
6183 // when this new clone is processed later we know which version of
6184 // the function to copy (so that other callsite clones we have
6185 // assigned to that function clone are properly cloned over). See
6186 // comments in the function cloning handling earlier.
6187
6188 // Check if we already have cloned this callsite again while
6189 // walking through caller edges, for a caller calling the same
6190 // function clone. If so, we can move this edge to that new clone
6191 // rather than creating yet another new clone.
6192 if (FuncCloneToNewCallsiteCloneMap.count(
6193 FuncCloneCalledByCaller)) {
6194 ContextNode *NewClone =
6195 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller];
6196 moveEdgeToExistingCalleeClone(Edge, NewClone);
6197 // Cleanup any none type edges cloned over.
6198 removeNoneTypeCalleeEdges(NewClone);
6199 } else {
6200 // Create a new callsite clone.
6201 ContextNode *NewClone = MoveEdgeToNewCalleeCloneAndSetUp(Edge);
6202 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller] =
6203 NewClone;
6204 // Add to list of clones and process later.
6205 ClonesWorklist.push_back(NewClone);
6206 }
6207 // Moving the caller edge may have resulted in some none type
6208 // callee edges.
6209 removeNoneTypeCalleeEdges(Clone);
6210 // We will handle the newly created callsite clone in a subsequent
6211 // iteration over this Node's Clones.
6212 continue;
6213 }
6214
6215 // Otherwise, we can use the function clone already assigned to this
6216 // caller.
6217 if (!FuncCloneAssignedToCurCallsiteClone) {
6218 FuncCloneAssignedToCurCallsiteClone = FuncCloneCalledByCaller;
6219 // Assign Clone to FuncCloneCalledByCaller
6220 AssignCallsiteCloneToFuncClone(
6221 FuncCloneCalledByCaller, Call, Clone,
6222 AllocationCallToContextNodeMap.count(Call));
6223 } else
6224 // Don't need to do anything - callsite is already calling this
6225 // function clone.
6226 assert(FuncCloneAssignedToCurCallsiteClone ==
6227 FuncCloneCalledByCaller);
6228
6229 } else {
6230 // We have not already assigned this caller to a version of
6231 // OrigFunc. Do the assignment now.
6232
6233 // First check if we have already assigned this callsite clone to a
6234 // clone of OrigFunc for another caller during this iteration over
6235 // its caller edges.
6236 if (!FuncCloneAssignedToCurCallsiteClone) {
6237 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
6238 assert(FuncCloneAssignedToCurCallsiteClone);
6239 // Assign Clone to FuncCloneAssignedToCurCallsiteClone
6240 AssignCallsiteCloneToFuncClone(
6241 FuncCloneAssignedToCurCallsiteClone, Call, Clone,
6242 AllocationCallToContextNodeMap.count(Call));
6243 } else
6244 assert(FuncCloneToCurNodeCloneMap
6245 [FuncCloneAssignedToCurCallsiteClone] == Clone);
6246 // Update callers to record function version called.
6247 RecordCalleeFuncOfCallsite(Edge->Caller,
6248 FuncCloneAssignedToCurCallsiteClone);
6249 }
6250 }
6251 // If we didn't assign a function clone to this callsite clone yet, e.g.
6252 // none of its callers has a non-null call, do the assignment here.
6253 // We want to ensure that every callsite clone is assigned to some
6254 // function clone, so that the call updates below work as expected.
6255 // In particular if this is the original callsite, we want to ensure it
6256 // is assigned to the original function, otherwise the original function
6257 // will appear available for assignment to other callsite clones,
6258 // leading to unintended effects. For one, the unknown and not updated
6259 // callers will call into cloned paths leading to the wrong hints,
6260 // because they still call the original function (clone 0). Also,
6261 // because all callsites start out as being clone 0 by default, we can't
6262 // easily distinguish between callsites explicitly assigned to clone 0
6263 // vs those never assigned, which can lead to multiple updates of the
6264 // calls when invoking updateCall below, with mismatched clone values.
6265 // TODO: Add a flag to the callsite nodes or some other mechanism to
6266 // better distinguish and identify callsite clones that are not getting
6267 // assigned to function clones as expected.
6268 if (!FuncCloneAssignedToCurCallsiteClone) {
6269 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
6270 assert(FuncCloneAssignedToCurCallsiteClone &&
6271 "No available func clone for this callsite clone");
6272 AssignCallsiteCloneToFuncClone(
6273 FuncCloneAssignedToCurCallsiteClone, Call, Clone,
6274 /*IsAlloc=*/AllocationCallToContextNodeMap.contains(Call));
6275 }
6276 }
6277 assignImplicitCallers(Node, TrimmedContextIds,
6278 CallsiteToCalleeFuncCloneMap,
6279 FuncCloneToCurNodeCloneMap, ImplicitSources);
6280 if (VerifyCCG) {
6282 for (const auto &PE : Node->CalleeEdges)
6284 for (const auto &CE : Node->CallerEdges)
6286 for (auto *Clone : Node->Clones) {
6288 for (const auto &PE : Clone->CalleeEdges)
6290 for (const auto &CE : Clone->CallerEdges)
6292 }
6293 }
6294 }
6295
6297 FuncToNumClones[Func] = std::max<unsigned>(1, FuncCloneInfos.size());
6298 if (FuncCloneInfos.size() < 2)
6299 continue;
6300
6301 // In this case there is more than just the original function copy.
6302 // Record call clones of any callsite nodes in the function that did not
6303 // themselves get cloned for all of the function clones.
6304 for (auto &Call : CallsWithMetadata) {
6305 ContextNode *Node = getNodeForInst(Call);
6306 if (!Node || !Node->hasCall() || Node->emptyContextIds())
6307 continue;
6308 // First collect the function clones that have a clone of this callsite
6309 // node (or the node itself). They may not be sequential due to empty
6310 // clones e.g.
6311 DenseMap<unsigned, const ContextNode *> FuncCloneToNodeClone;
6312 FuncCloneToNodeClone[Node->Call.cloneNo()] = Node;
6313 // A clone left without context ids (its callers were all moved to other
6314 // clones while assigning function clones) has no edges and is not
6315 // reached by the call updates below, so the call in its function clone
6316 // keeps the original callee. If an implicit caller recorded the callsite
6317 // clone that call must follow, treat the function clone as having no
6318 // clone of this node, so that the call follows the recorded source like
6319 // any other call not cloned for its function clone.
6320 for (auto *C : Node->Clones)
6321 if (!C->emptyContextIds() ||
6322 !ImplicitSources.contains({Node, C->Call.cloneNo()}))
6323 FuncCloneToNodeClone[C->Call.cloneNo()] = C;
6324 // If Node has enough clones already to cover all function clones, we can
6325 // skip it.
6326 if (FuncCloneToNodeClone.size() >= FuncCloneInfos.size())
6327 continue;
6328 // Now check all the function clones.
6329 for (auto &FC : FuncCloneInfos) {
6330 unsigned I = FC.FuncClone.cloneNo();
6331 // Skip the first clone which got the original call.
6332 // Also skip any other clones created for this Node.
6333 if (I == 0 || FuncCloneToNodeClone.contains(I)) {
6334 continue;
6335 }
6336 // Record the call clones created for this callsite in this function
6337 // clone, and the callsite node whose callee they should follow: the
6338 // one required by an implicit caller, if any, else the clone of this
6339 // callsite node in the nearest function clone in the chain of function
6340 // clones this one was derived from (null for the original node).
6341 auto &Info = UnassignedCallClones[Node][I];
6342 auto &CallVector = Info.Calls;
6343 for (unsigned P = I;; P = FuncCloneParent[P]) {
6344 if (auto It = ImplicitSources.find({Node, P});
6345 It != ImplicitSources.end()) {
6346 Info.Source = resolveImplicitSource(Node, It->second);
6347 break;
6348 }
6349 if (auto It = FuncCloneToNodeClone.find(P);
6350 It != FuncCloneToNodeClone.end()) {
6351 Info.Source = It->second;
6352 break;
6353 }
6354 if (P == 0)
6355 break;
6356 }
6357 DenseMap<CallInfo, CallInfo> &CallMap = FC.CallMap;
6358 if (auto It = CallMap.find(Call); It != CallMap.end()) {
6359 CallInfo CallClone = It->second;
6360 CallVector.push_back(CallClone);
6361 } else {
6362 // All but the original clone (skipped earlier) should have an entry
6363 // for all calls.
6364 assert(false && "Expected to find call in CallMap");
6365 }
6366 // Need to do the same for all matching calls. Use the original
6367 // matching calls, as those on Node may have been remapped to the calls
6368 // of a function clone if Node was assigned to one.
6369 assert(OrigNodeToOrigCalls.count(Node));
6370 for (const CallInfo &OrigMatchingCall :
6371 OrigNodeToOrigCalls[Node].MatchingCalls) {
6372 if (auto It = CallMap.find(OrigMatchingCall); It != CallMap.end()) {
6373 CallInfo CallClone = It->second;
6374 CallVector.push_back(CallClone);
6375 } else {
6376 // All but the original clone (skipped earlier) should have an entry
6377 // for all calls.
6378 assert(false && "Expected to find call in CallMap");
6379 }
6380 }
6381 }
6382 }
6383 }
6384
6385 uint8_t BothTypes =
6386 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
6387
6388 auto UpdateCalls = [&](ContextNode *Node,
6389 DenseSet<const ContextNode *> &Visited,
6390 auto &&UpdateCalls) {
6391 auto Inserted = Visited.insert(Node);
6392 if (!Inserted.second)
6393 return;
6394
6395 for (auto *Clone : Node->Clones)
6396 UpdateCalls(Clone, Visited, UpdateCalls);
6397
6398 for (auto &Edge : Node->CallerEdges)
6399 UpdateCalls(Edge->Caller, Visited, UpdateCalls);
6400
6401 // Skip if either no call to update, or if we ended up with no context ids
6402 // (we moved all edges onto other clones).
6403 if (!Node->hasCall() || Node->emptyContextIds())
6404 return;
6405
6406 // Returns the recorded call clones in function clones which don't have a
6407 // clone of this callsite node, along with the node whose decision each
6408 // should follow (the Source recorded earlier, falling back to Node).
6409 auto GetUnassignedCallClones = [&](ContextNode *Node) {
6411 Unassigned;
6412 auto UnassignedIt = UnassignedCallClones.find(Node);
6413 if (UnassignedIt == UnassignedCallClones.end())
6414 return Unassigned;
6415 DenseSet<unsigned> NodeCallClones;
6416 for (auto *C : Node->Clones)
6417 if (!C->emptyContextIds())
6418 NodeCallClones.insert(C->Call.cloneNo());
6419 for (auto &[CloneNo, Info] : UnassignedIt->second) {
6420 // Should start at 1 as we never create an entry for original node.
6421 assert(CloneNo > 0);
6422 // If we subsequently created a clone, skip this one.
6423 if (NodeCallClones.contains(CloneNo))
6424 continue;
6425 Unassigned.push_back({Info.Source ? Info.Source : Node, Info.Calls});
6426 }
6427 return Unassigned;
6428 };
6429
6430 if (Node->IsAllocation) {
6431 auto GetAllocTypeToUse = [&](const ContextNode *Node) {
6432 auto AT = allocTypeToUse(Node->AllocTypes);
6433 // If the allocation type is still ambiguous after cloning, record
6434 // that as the allocation type (the attribute stays "ambiguous") rather
6435 // than falling back to the default not cold, unless ambiguous
6436 // attributes are disabled.
6437 if (Node->AllocTypes == BothTypes && MemProfUseAmbiguousAttributes)
6438 AT = (AllocationType)BothTypes;
6439 // If the allocation type is ambiguous, and more aggressive hinting
6440 // has been enabled via the MinClonedColdBytePercent flag, see if this
6441 // allocation should be hinted cold anyway because its fraction cold
6442 // bytes allocated is at least the given threshold.
6443 if (Node->AllocTypes == BothTypes && MinClonedColdBytePercent < 100 &&
6444 !ContextIdToContextSizeInfos.empty()) {
6445 uint64_t TotalCold = 0;
6446 uint64_t Total = 0;
6447 for (auto Id : Node->getContextIds()) {
6448 auto TypeI = ContextIdToAllocationType.find(Id);
6449 assert(TypeI != ContextIdToAllocationType.end());
6450 auto CSI = ContextIdToContextSizeInfos.find(Id);
6451 if (CSI != ContextIdToContextSizeInfos.end()) {
6452 for (auto &Info : CSI->second) {
6453 Total += Info.TotalSize;
6454 if (TypeI->second == AllocationType::Cold)
6455 TotalCold += Info.TotalSize;
6456 }
6457 }
6458 }
6459 if (TotalCold * 100 >= Total * MinClonedColdBytePercent)
6460 AT = AllocationType::Cold;
6461 }
6462 return AT;
6463 };
6464 updateAllocationCall(Node->Call, GetAllocTypeToUse(Node));
6466 OrigAllocAndCloneToNode[{Node->getOrigNode(), Node->Call.cloneNo()}] =
6467 Node;
6468 assert(Node->MatchingCalls.empty());
6469 // Update the allocation calls in function clones without a clone of this
6470 // node the same way as the node they should follow.
6471 for (auto &[Source, Calls] : GetUnassignedCallClones(Node)) {
6472 auto AT = GetAllocTypeToUse(Source);
6473 for (auto &Call : Calls) {
6474 updateAllocationCall(Call, AT);
6475 // For the report, such an allocation clone follows Source's hint.
6477 OrigAllocAndCloneToNode[{Node->getOrigNode(), Call.cloneNo()}] =
6478 Source;
6479 }
6480 }
6481 return;
6482 }
6483
6484 auto CalleeFuncIt = CallsiteToCalleeFuncCloneMap.find(Node);
6485 if (CalleeFuncIt != CallsiteToCalleeFuncCloneMap.end()) {
6486 auto &CalleeFunc = CalleeFuncIt->second;
6487 updateCall(Node->Call, CalleeFunc);
6489 OrigNodeAndCloneToCalleeClone[{
6490 Node->getOrigNode(), Node->Call.cloneNo()}] = CalleeFunc.cloneNo();
6491 // Update all the matching calls as well.
6492 for (auto &Call : Node->MatchingCalls)
6493 updateCall(Call, CalleeFunc);
6494 }
6495
6496 // Now update all calls recorded earlier that are still in function clones
6497 // which don't have a clone of this callsite node, the same way as the
6498 // node they should follow.
6499 for (auto &[Source, Calls] : GetUnassignedCallClones(Node)) {
6500 auto It = CallsiteToCalleeFuncCloneMap.find(Source);
6501 // Fall back to the original Node's callee function.
6502 if (It == CallsiteToCalleeFuncCloneMap.end())
6503 It = CalleeFuncIt;
6504 if (It == CallsiteToCalleeFuncCloneMap.end())
6505 continue;
6506 for (auto &Call : Calls) {
6507 updateCall(Call, It->second);
6509 OrigNodeAndCloneToCalleeClone[{Node->getOrigNode(), Call.cloneNo()}] =
6510 It->second.cloneNo();
6511 }
6512 }
6513 };
6514
6515 // Performs DFS traversal starting from allocation nodes to update calls to
6516 // reflect cloning decisions recorded earlier. For regular LTO this will
6517 // update the actual calls in the IR to call the appropriate function clone
6518 // (and add attributes to allocation calls), whereas for ThinLTO the decisions
6519 // are recorded in the summary entries.
6520 DenseSet<const ContextNode *> Visited;
6521 for (auto &Entry : AllocationCallToContextNodeMap)
6522 UpdateCalls(Entry.second, Visited, UpdateCalls);
6523
6524 return Changed;
6525}
6526
6527// Compute a SHA1 hash of the callsite and alloc version information of clone I
6528// in the summary, to use in detection of duplicate clones.
6530 SHA1 Hasher;
6531 // Add a record for the callsite or alloc at the given index in the summary,
6532 // with the given version. The index must be included, since two clones that
6533 // assign the same versions to different callsites or allocs are not
6534 // duplicates.
6535 auto AddRecord = [&](char Kind, uint32_t Index, uint32_t Version) {
6536 uint8_t Data[1 + 2 * sizeof(uint32_t)];
6537 Data[0] = Kind;
6538 support::endian::write32le(&Data[1], Index);
6539 support::endian::write32le(&Data[1 + sizeof(uint32_t)], Version);
6540 Hasher.update(Data);
6541 };
6542 // Update hash with any callsites that call non-default (non-zero) callee
6543 // versions.
6544 for (auto [Index, SN] : enumerate(FS->callsites())) {
6545 // In theory all callsites and allocs in this function should have the same
6546 // number of clone entries, but handle any discrepancies gracefully below
6547 // for NDEBUG builds.
6548 assert(
6549 SN.Clones.size() > I &&
6550 "Callsite summary has fewer entries than other summaries in function");
6551 if (SN.Clones.size() <= I || !SN.Clones[I])
6552 continue;
6553 AddRecord('c', Index, SN.Clones[I]);
6554 }
6555 // Update hash with any allocs that have non-default (non-None) hints.
6556 for (auto [Index, AN] : enumerate(FS->allocs())) {
6557 // In theory all callsites and allocs in this function should have the same
6558 // number of clone entries, but handle any discrepancies gracefully below
6559 // for NDEBUG builds.
6560 assert(AN.Versions.size() > I &&
6561 "Alloc summary has fewer entries than other summaries in function");
6562 if (AN.Versions.size() <= I ||
6563 (AllocationType)AN.Versions[I] == AllocationType::None)
6564 continue;
6565 AddRecord('a', Index, AN.Versions[I]);
6566 }
6567 return support::endian::read64le(Hasher.result().data());
6568}
6569
6570#ifndef NDEBUG
6571// Check that clones I and J of FS have identical callsite and alloc versions.
6572static bool clonesHaveSameVersions(const FunctionSummary *FS, unsigned I,
6573 unsigned J) {
6574 for (auto &SN : FS->callsites()) {
6575 assert(SN.Clones.size() > I && SN.Clones.size() > J &&
6576 "Callsite summary has fewer entries than other summaries in "
6577 "function");
6578 if (SN.Clones[I] != SN.Clones[J])
6579 return false;
6580 }
6581 for (auto &AN : FS->allocs()) {
6582 assert(AN.Versions.size() > I && AN.Versions.size() > J &&
6583 "Alloc summary has fewer entries than other summaries in function");
6584 if (AN.Versions[I] != AN.Versions[J])
6585 return false;
6586 }
6587 return true;
6588}
6589#endif
6590
6592 Function &F, unsigned NumClones, Module &M, OptimizationRemarkEmitter &ORE,
6594 &FuncToAliasMap,
6595 FunctionSummary *FS) {
6596 auto TakeDeclNameAndReplace = [](GlobalValue *DeclGV, GlobalValue *NewGV) {
6597 // We might have created this when adjusting callsite in another
6598 // function. It should be a declaration.
6599 assert(DeclGV->isDeclaration());
6600 NewGV->takeName(DeclGV);
6601 DeclGV->replaceAllUsesWith(NewGV);
6602 DeclGV->eraseFromParent();
6603 };
6604
6605 // Handle aliases to this function, and create analogous alias clones to the
6606 // provided clone of this function.
6607 auto CloneFuncAliases = [&](Function *NewF, unsigned I) {
6608 if (!FuncToAliasMap.count(&F))
6609 return;
6610 for (auto *A : FuncToAliasMap[&F]) {
6611 std::string AliasName = getMemProfFuncName(A->getName(), I);
6612 auto *PrevA = M.getNamedAlias(AliasName);
6613 auto *NewA = GlobalAlias::create(A->getValueType(),
6614 A->getType()->getPointerAddressSpace(),
6615 A->getLinkage(), AliasName, NewF);
6616 NewA->copyAttributesFrom(A);
6617 if (PrevA)
6618 TakeDeclNameAndReplace(PrevA, NewA);
6619 }
6620 };
6621
6622 // The first "clone" is the original copy, we should only call this if we
6623 // needed to create new clones.
6624 assert(NumClones > 1);
6626 VMaps.reserve(NumClones - 1);
6627 FunctionsClonedThinBackend++;
6628
6629 // Map of hash of callsite/alloc versions to the instantiated function clone
6630 // (possibly the original) implementing those calls and its clone number. Used
6631 // to avoid instantiating duplicate function clones.
6632 // FIXME: Ideally the thin link would not generate such duplicate clones to
6633 // start with, but right now it happens due to phase ordering in the function
6634 // assignment and possible new clones that produces. We simply make each
6635 // duplicate an alias to the matching instantiated clone recorded in the map
6636 // (except for available_externally which are made declarations as they would
6637 // be aliases in the prevailing module, and available_externally aliases are
6638 // not well supported right now).
6640
6641 // Save the hash of the original function version.
6642 HashToFunc[ComputeHash(FS, 0)] = {&F, 0};
6643
6644 for (unsigned I = 1; I < NumClones; I++) {
6645 VMaps.emplace_back(std::make_unique<ValueToValueMapTy>());
6646 std::string Name = getMemProfFuncName(F.getName(), I);
6647 auto Hash = ComputeHash(FS, I);
6648 // If this clone would duplicate a previously seen clone, don't generate the
6649 // duplicate clone body, just make an alias to satisfy any (potentially
6650 // cross-module) references.
6651 if (auto It = HashToFunc.find(Hash); It != HashToFunc.end()) {
6652 FunctionCloneDuplicatesThinBackend++;
6653 auto [Func, OrigI] = It->second;
6654 assert(clonesHaveSameVersions(FS, I, OrigI) &&
6655 "Duplicate clone hash collision");
6656 if (Func->hasAvailableExternallyLinkage()) {
6657 // Skip these as EliminateAvailableExternallyPass does not handle
6658 // available_externally aliases correctly and we end up with an
6659 // available_externally alias to a declaration. Just create a
6660 // declaration for now as we know we will have a definition in another
6661 // module.
6662 auto Decl = M.getOrInsertFunction(Name, Func->getFunctionType());
6663 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", &F)
6664 << "created clone decl " << ore::NV("Decl", Decl.getCallee()));
6665 continue;
6666 }
6667 auto *PrevF = M.getFunction(Name);
6668 auto *Alias = GlobalAlias::create(Name, Func);
6669 if (PrevF)
6670 TakeDeclNameAndReplace(PrevF, Alias);
6671 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", &F)
6672 << "created clone alias " << ore::NV("Alias", Alias));
6673
6674 // Now handle aliases to this function, and clone those as well.
6675 CloneFuncAliases(Func, I);
6676 continue;
6677 }
6678 auto *NewF = CloneFunction(&F, *VMaps.back());
6679 HashToFunc[Hash] = {NewF, I};
6680 FunctionClonesThinBackend++;
6681 // Strip memprof and callsite metadata from clone as they are no longer
6682 // needed.
6683 for (auto &BB : *NewF) {
6684 for (auto &Inst : BB) {
6685 Inst.setMetadata(LLVMContext::MD_memprof, nullptr);
6686 Inst.setMetadata(LLVMContext::MD_callsite, nullptr);
6687 }
6688 }
6689 auto *PrevF = M.getFunction(Name);
6690 if (PrevF)
6691 TakeDeclNameAndReplace(PrevF, NewF);
6692 else
6693 NewF->setName(Name);
6694 updateSubprogramLinkageName(NewF, Name);
6695 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", &F)
6696 << "created clone " << ore::NV("NewFunction", NewF));
6697
6698 // Now handle aliases to this function, and clone those as well.
6699 CloneFuncAliases(NewF, I);
6700 }
6701 return VMaps;
6702}
6703
6704// If F is an imported copy of an alias (materialized as a Function by
6705// replaceAliasWithAliasee during FunctionImport while preserving the aliasee's
6706// !guid metadata for body-level passes), return the original alias GUID
6707// recorded in its thinlto_alias_guid metadata.
6708static std::optional<GlobalValue::GUID>
6710 if (auto *MD = F.getMetadata("thinlto_alias_guid"))
6711 return mdconst::extract<ConstantInt>(MD->getOperand(0))->getZExtValue();
6712 return std::nullopt;
6713}
6714
6715// Locate the summary for GV. This is complicated by the fact that it might
6716// have been internalized, promoted, or imported as a copy of an alias.
6718 const ModuleSummaryIndex *ImportSummary,
6719 const Function *CallingFunc = nullptr) {
6720 if (const auto *F = dyn_cast<Function>(&GV))
6721 if (auto AliasGUID = getImportedAliasGUID(*F)) {
6722 ValueInfo AliasVI = ImportSummary->getValueInfo(*AliasGUID);
6723 assert(AliasVI && "Expected ValueInfo for imported alias GUID");
6724 return AliasVI;
6725 }
6726
6727 // FIXME: Ideally we would retain the original GUID in some fashion on the
6728 // function (e.g. as metadata), but for now do our best to locate the
6729 // summary without that information.
6730 ValueInfo TheFnVI = ImportSummary->getValueInfo(GV.getGUID());
6731 if (!TheFnVI)
6732 // See if GV was internalized, by checking index directly with
6733 // original name (this avoids the name adjustment done by getGUID() for
6734 // internal symbols).
6735 TheFnVI = ImportSummary->getValueInfo(
6737 if (TheFnVI)
6738 return TheFnVI;
6739 // Now query with the original name before any promotion was performed.
6740 StringRef OrigName =
6742 // When this pass is enabled, we always add thinlto_src_file provenance
6743 // metadata to imported function definitions, which allows us to recreate the
6744 // original internal symbol's GUID.
6745 const auto *GO = dyn_cast<GlobalObject>(&GV);
6746 MDNode *SrcFileMD = GO ? GO->getMetadata("thinlto_src_file") : nullptr;
6747 // If this is a call to an imported/promoted local for which we didn't import
6748 // the definition, the metadata will not exist on the declaration. However,
6749 // since we are doing this early, before any inlining in the LTO backend, we
6750 // can simply look at the metadata on the calling function which must have
6751 // been from the same module if GV was an internal symbol originally.
6752 if (!SrcFileMD && GV.isDeclaration()) {
6753 // We would only call this for a declaration for a direct callsite, in which
6754 // case the caller would have provided the calling function pointer.
6755 assert(CallingFunc);
6756 SrcFileMD = CallingFunc->getMetadata("thinlto_src_file");
6757 // If this is a promoted local (OrigName != GV.getName()), since this is a
6758 // declaration, it must be imported from a different module and therefore we
6759 // should always find the metadata on its calling function. Any call to a
6760 // promoted local that came from this module should still be a definition.
6761 assert(SrcFileMD || OrigName == GV.getName());
6762 }
6763 StringRef SrcFile = M.getSourceFileName();
6764 if (SrcFileMD)
6765 SrcFile = dyn_cast<MDString>(SrcFileMD->getOperand(0))->getString();
6766 std::string OrigId = GlobalValue::getGlobalIdentifier(
6767 OrigName, GlobalValue::InternalLinkage, SrcFile);
6768 TheFnVI = ImportSummary->getValueInfo(
6770 // Internal func in original module may have gotten a numbered suffix if we
6771 // imported an external function with the same name. This happens
6772 // automatically during IR linking for naming conflicts. It would have to
6773 // still be internal in that case (otherwise it would have been renamed on
6774 // promotion in which case we wouldn't have a naming conflict).
6775 if (!TheFnVI && OrigName == GV.getName() && GV.hasLocalLinkage() &&
6776 GV.getName().contains('.')) {
6777 OrigName = GV.getName().rsplit('.').first;
6779 OrigName, GlobalValue::InternalLinkage, SrcFile);
6780 TheFnVI = ImportSummary->getValueInfo(
6782 }
6783 // The only way we may not have a VI is if this is a declaration created for
6784 // an imported reference. For distributed ThinLTO we may not have a VI for
6785 // such declarations in the distributed summary.
6786 assert(TheFnVI || GV.isDeclaration());
6787 return TheFnVI;
6788}
6789
6790// Find the CallsiteInfo record synthesized by the thin link for profiled target
6791// CandidateGUID of an indirect tail call, in MapTailCallCalleeVIToCallsite
6792// (which maps each synthesized record's callee to the record). Returns null if
6793// there is none. OrigNameGUIDToTailCallCallsite caches a map from the original
6794// name GUID of each record's callee to the record, and is built on first use
6795// (along with AliasVIToGV, which caches alias ValueInfos in M).
6797 uint64_t CandidateGUID,
6798 const DenseMap<ValueInfo, CallsiteInfo> &MapTailCallCalleeVIToCallsite,
6800 &OrigNameGUIDToTailCallCallsite,
6801 std::optional<DenseMap<ValueInfo, const GlobalAlias *>> &AliasVIToGV,
6802 const Module &M, const ModuleSummaryIndex *ImportSummary,
6803 InstrProfSymtab &Symtab) {
6804 auto End = MapTailCallCalleeVIToCallsite.end();
6805 // The callee of the synthesized record is normally the VP metadata GUID, so
6806 // check that first.
6807 if (ValueInfo VI = ImportSummary->getValueInfo(CandidateGUID)) {
6808 auto It = MapTailCallCalleeVIToCallsite.find(VI);
6809 if (It != End)
6810 return &It->second;
6811 }
6812 // For local targets the VP metadata may contain the GUID of the original
6813 // name without the source file prefix, which the thin link translates to the
6814 // actual GUID of the local function (see updateValueInfoForIndirectCalls).
6815 if (auto LocalGUID = ImportSummary->getGUIDFromOriginalID(CandidateGUID)) {
6816 if (ValueInfo LocalVI = ImportSummary->getValueInfo(LocalGUID)) {
6817 auto It = MapTailCallCalleeVIToCallsite.find(LocalVI);
6818 if (It != End)
6819 return &It->second;
6820 }
6821 }
6822 // The index for a distributed ThinLTO backend does not record the original
6823 // names of local functions, in which case the above lookup via
6824 // getGUIDFromOriginalID fails. Instead, compute the original name GUID of
6825 // each record's callee from its function or alias in this module, using its
6826 // name before any promotion.
6827 if (!OrigNameGUIDToTailCallCallsite) {
6828 // Construct the (initially empty) map so that it is marked as built, even
6829 // if no entries are added below, to avoid rebuilding it on later calls.
6830 OrigNameGUIDToTailCallCallsite.emplace();
6831 for (const auto &[CalleeVI, Callsite] : MapTailCallCalleeVIToCallsite) {
6832 const GlobalValue *Callee = Symtab.getFunction(CalleeVI.getGUID());
6833 if (!Callee) {
6834 // InstrProfSymtab only indexes Functions, not GlobalAliases (imported
6835 // alias copies are materialized as Functions with thinlto_alias_guid
6836 // metadata and are found via Symtab above). Lazily build a module-wide
6837 // map for same-module function GlobalAliases once per module so we can
6838 // recover the alias's pre-promotion name.
6839 if (!AliasVIToGV) {
6840 AliasVIToGV.emplace();
6841 for (const GlobalAlias &A : M.aliases()) {
6842 if (isMemProfClone(A) ||
6843 !isa_and_nonnull<Function>(A.getAliaseeObject()))
6844 continue;
6845 if (ValueInfo VI = findValueInfoForGV(A, M, ImportSummary))
6846 AliasVIToGV->try_emplace(VI, &A);
6847 }
6848 }
6849 Callee = AliasVIToGV->lookup(CalleeVI);
6850 if (!Callee)
6851 continue;
6852 }
6853 StringRef OrigName =
6855 auto [It, Inserted] = OrigNameGUIDToTailCallCallsite->try_emplace(
6856 GlobalValue::getGUIDAssumingExternalLinkage(OrigName), &Callsite);
6857 // If multiple callees have the same original name, we can't tell which
6858 // corresponds to the profiled target.
6859 if (!Inserted && It->second != &Callsite)
6860 It->second = nullptr;
6861 }
6862 }
6863 return OrigNameGUIDToTailCallCallsite->lookup(CandidateGUID);
6864}
6865
6866bool MemProfContextDisambiguation::initializeIndirectCallPromotionInfo(
6867 Module &M) {
6868 ICallAnalysis = std::make_unique<ICallPromotionAnalysis>();
6869 Symtab = std::make_unique<InstrProfSymtab>();
6870 // Don't add canonical names, to avoid multiple functions to the symtab
6871 // when they both have the same root name with "." suffixes stripped.
6872 // If we pick the wrong one then this could lead to incorrect ICP and calling
6873 // a memprof clone that we don't actually create (resulting in linker unsats).
6874 // What this means is that the GUID of the function *must* match that in the
6875 // VP metadata to allow promotion. In practice this should not be a
6876 // limitation, since local functions have a GUID from before they were
6877 // promoted and global function names shouldn't need any special handling
6878 // (they should not get the ".llvm.*" suffix that the canonicalization
6879 // handling is attempting to strip).
6880 // Key imported copies of aliases by the alias's GUID rather than the
6881 // aliasee's GUID retained in their !guid metadata, since we rely on the
6882 // looked up function's name (to compute its original name GUID and the names
6883 // of its clones), and so that they don't shadow the aliasee's own function
6884 // when both are in the module. See AliaseeGUIDToImportedAlias for how
6885 // performICP handles profiled targets that are the aliasee of an imported
6886 // alias copy when the aliasee itself is not in the module.
6887 AliaseeGUIDToImportedAlias.reset();
6888 if (Error E = Symtab->create(M, /*InLTO=*/true, /*AddCanonical=*/false,
6889 /*KeyImportedAliasesByAliasGUID=*/true)) {
6890 std::string SymtabFailure = toString(std::move(E));
6891 M.getContext().emitError("Failed to create symtab: " + SymtabFailure);
6892 return false;
6893 }
6894 return true;
6895}
6896
6897#ifndef NDEBUG
6898// Sanity check that the MIB stack ids match between the summary and
6899// instruction metadata.
6901 const AllocInfo &AllocNode, const MDNode *MemProfMD,
6902 const CallStack<MDNode, MDNode::op_iterator> &CallsiteContext,
6903 const ModuleSummaryIndex *ImportSummary) {
6904 auto MIBIter = AllocNode.MIBs.begin();
6905 for (auto &MDOp : MemProfMD->operands()) {
6906 assert(MIBIter != AllocNode.MIBs.end());
6907 // The combined index may have been written without the MIB contexts (see
6908 // -combined-index-memprof-context, which defaults to false in NDEBUG
6909 // builds), e.g. if the thin link was performed by a release build while
6910 // this backend has assertions enabled. Since the MIB context in the summary
6911 // can never be empty after trimming the allocation's callsite context, an
6912 // empty list means the context was not serialized, and there is nothing to
6913 // check.
6914 if (MIBIter->StackIdIndices.empty()) {
6915 MIBIter++;
6916 continue;
6917 }
6918 auto StackIdIndexIter = MIBIter->StackIdIndices.begin();
6919 auto *MIBMD = cast<const MDNode>(MDOp);
6920 MDNode *StackMDNode = getMIBStackNode(MIBMD);
6921 assert(StackMDNode);
6922 CallStack<MDNode, MDNode::op_iterator> StackContext(StackMDNode);
6923 auto ContextIterBegin =
6924 StackContext.beginAfterSharedPrefix(CallsiteContext);
6925 // Skip the checking on the first iteration.
6926 uint64_t LastStackContextId =
6927 (ContextIterBegin != StackContext.end() && *ContextIterBegin == 0) ? 1
6928 : 0;
6929 for (auto ContextIter = ContextIterBegin; ContextIter != StackContext.end();
6930 ++ContextIter) {
6931 // If this is a direct recursion, simply skip the duplicate
6932 // entries, to be consistent with how the summary ids were
6933 // generated during ModuleSummaryAnalysis.
6934 if (LastStackContextId == *ContextIter)
6935 continue;
6936 LastStackContextId = *ContextIter;
6937 assert(StackIdIndexIter != MIBIter->StackIdIndices.end());
6938 assert(ImportSummary->getStackIdAtIndex(*StackIdIndexIter) ==
6939 *ContextIter);
6940 StackIdIndexIter++;
6941 }
6942 MIBIter++;
6943 }
6944}
6945#endif
6946
6947bool MemProfContextDisambiguation::applyImport(Module &M) {
6948 assert(ImportSummary);
6949 bool Changed = false;
6950
6951 // We also need to clone any aliases that reference cloned functions, because
6952 // the modified callsites may invoke via the alias. Keep track of the aliases
6953 // for each function.
6954 std::map<const Function *, SmallPtrSet<const GlobalAlias *, 1>>
6955 FuncToAliasMap;
6956 for (auto &A : M.aliases()) {
6957 auto *Aliasee = A.getAliaseeObject();
6958 if (auto *F = dyn_cast<Function>(Aliasee))
6959 FuncToAliasMap[F].insert(&A);
6960 }
6961
6962 if (!initializeIndirectCallPromotionInfo(M))
6963 return false;
6964
6965 // Lazily populated map from alias ValueInfo to the corresponding same-module
6966 // GlobalAlias, used by findIndirectTailCallCallsite when a local alias target
6967 // is not in Symtab.
6968 std::optional<DenseMap<ValueInfo, const GlobalAlias *>> AliasVIToGV;
6969
6970 for (auto &F : M) {
6971 if (F.isDeclaration() || isMemProfClone(F))
6972 continue;
6973
6974 OptimizationRemarkEmitter ORE(&F);
6975
6977 bool ClonesCreated = false;
6978 unsigned NumClonesCreated = 0;
6979 auto CloneFuncIfNeeded = [&](unsigned NumClones, FunctionSummary *FS) {
6980 // We should at least have version 0 which is the original copy.
6981 assert(NumClones > 0);
6982 // If only one copy needed use original.
6983 if (NumClones == 1)
6984 return;
6985 // If we already performed cloning of this function, confirm that the
6986 // requested number of clones matches (the thin link should ensure the
6987 // number of clones for each constituent callsite is consistent within
6988 // each function), before returning.
6989 if (ClonesCreated) {
6990 assert(NumClonesCreated == NumClones);
6991 return;
6992 }
6993 VMaps = createFunctionClones(F, NumClones, M, ORE, FuncToAliasMap, FS);
6994 // The first "clone" is the original copy, which doesn't have a VMap.
6995 assert(VMaps.size() == NumClones - 1);
6996 Changed = true;
6997 ClonesCreated = true;
6998 NumClonesCreated = NumClones;
6999 };
7000
7001 auto CloneCallsite = [&](const CallsiteInfo &StackNode, CallBase *CB,
7002 Function *CalledFunction, FunctionSummary *FS) {
7003 // Perform cloning if not yet done.
7004 CloneFuncIfNeeded(/*NumClones=*/StackNode.Clones.size(), FS);
7005
7006 assert(!isMemProfClone(*CalledFunction));
7007
7008 // Because we update the cloned calls by calling setCalledOperand (see
7009 // comment below), out of an abundance of caution make sure the called
7010 // function was actually the called operand (or its aliasee). We also
7011 // strip pointer casts when looking for calls (to match behavior during
7012 // summary generation), however, with opaque pointers in theory this
7013 // should not be an issue. Note we still clone the current function
7014 // (containing this call) above, as that could be needed for its callers.
7015 auto *GA = dyn_cast_or_null<GlobalAlias>(CB->getCalledOperand());
7016 if (CalledFunction != CB->getCalledOperand() &&
7017 (!GA || CalledFunction != GA->getAliaseeObject())) {
7018 SkippedCallsCloning++;
7019 return;
7020 }
7021 // Update the calls per the summary info.
7022 // Save orig name since it gets updated in the first iteration
7023 // below.
7024 auto CalleeOrigName = CalledFunction->getName();
7025 for (unsigned J = 0; J < StackNode.Clones.size(); J++) {
7026 // If the VMap is empty, this clone was a duplicate of another and was
7027 // created as an alias or a declaration.
7028 if (J > 0 && VMaps[J - 1]->empty())
7029 continue;
7030 // Do nothing if this version calls the original version of its
7031 // callee.
7032 if (!StackNode.Clones[J])
7033 continue;
7034 auto NewF = M.getOrInsertFunction(
7035 getMemProfFuncName(CalleeOrigName, StackNode.Clones[J]),
7036 CalledFunction->getFunctionType());
7037 CallBase *CBClone;
7038 // Copy 0 is the original function.
7039 if (!J)
7040 CBClone = CB;
7041 else
7042 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
7043 // Set the called operand directly instead of calling setCalledFunction,
7044 // as the latter mutates the function type on the call. In rare cases
7045 // we may have a slightly different type on a callee function
7046 // declaration due to it being imported from a different module with
7047 // incomplete types. We really just want to change the name of the
7048 // function to the clone, and not make any type changes.
7049 CBClone->setCalledOperand(NewF.getCallee());
7050 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofCall", CBClone)
7051 << ore::NV("Call", CBClone) << " in clone "
7052 << ore::NV("Caller", CBClone->getFunction())
7053 << " assigned to call function clone "
7054 << ore::NV("Callee", NewF.getCallee()));
7055 }
7056 };
7057
7058 // Locate the summary for F.
7059 ValueInfo TheFnVI = findValueInfoForGV(F, M, ImportSummary);
7060 // If not found, this could be an imported local (see comment in
7061 // findValueInfoForGV). Skip for now as it will be cloned in its original
7062 // module (where it would have been promoted to global scope so should
7063 // satisfy any reference in this module).
7064 if (!TheFnVI)
7065 continue;
7066
7067 auto *GVSummary =
7068 ImportSummary->findSummaryInModule(TheFnVI, M.getModuleIdentifier());
7069 if (!GVSummary) {
7070 // Must have been imported, use the summary which matches the definition。
7071 // (might be multiple if this was a linkonce_odr).
7072 auto SrcModuleMD = F.getMetadata("thinlto_src_module");
7073 assert(SrcModuleMD &&
7074 "enable-import-metadata is needed to emit thinlto_src_module");
7075 StringRef SrcModule =
7076 dyn_cast<MDString>(SrcModuleMD->getOperand(0))->getString();
7077 for (auto &GVS : TheFnVI.getSummaryList()) {
7078 if (GVS->modulePath() == SrcModule) {
7079 GVSummary = GVS.get();
7080 break;
7081 }
7082 }
7083 assert(GVSummary && GVSummary->modulePath() == SrcModule);
7084 }
7085
7086 // If this was an imported alias skip it as we won't have the function
7087 // summary, and it should be cloned in the original module.
7088 if (isa<AliasSummary>(GVSummary))
7089 continue;
7090
7091 auto *FS = cast<FunctionSummary>(GVSummary->getBaseObject());
7092
7093 if (FS->allocs().empty() && FS->callsites().empty())
7094 continue;
7095
7096 auto SI = FS->callsites().begin();
7097 auto AI = FS->allocs().begin();
7098
7099 // To handle callsite infos synthesized for tail calls which have missing
7100 // frames in the profiled context, map callee VI to the synthesized callsite
7101 // info.
7102 DenseMap<ValueInfo, CallsiteInfo> MapTailCallCalleeVIToCallsite;
7103 // Iterate the callsites for this function in reverse, since we place all
7104 // those synthesized for tail calls at the end.
7105 for (auto CallsiteIt = FS->callsites().rbegin();
7106 CallsiteIt != FS->callsites().rend(); CallsiteIt++) {
7107 auto &Callsite = *CallsiteIt;
7108 // Stop as soon as we see a non-synthesized callsite info (see comment
7109 // above loop). All the entries added for discovered tail calls have empty
7110 // stack ids.
7111 if (!Callsite.StackIdIndices.empty())
7112 break;
7113 MapTailCallCalleeVIToCallsite.insert({Callsite.Callee, Callsite});
7114 }
7115 // Maps the original name GUID of each synthesized callsite info's callee to
7116 // the callsite info, built on first use by findIndirectTailCallCallsite.
7117 std::optional<DenseMap<uint64_t, const CallsiteInfo *>>
7118 OrigNameGUIDToTailCallCallsite;
7119
7120 // Keeps track of needed ICP for the function.
7121 SmallVector<ICallAnalysisData> ICallAnalysisInfo;
7122
7123 // Assume for now that the instructions are in the exact same order
7124 // as when the summary was created, but confirm this is correct by
7125 // matching the stack ids.
7126 for (auto &BB : F) {
7127 for (auto &I : BB) {
7128 auto *CB = dyn_cast<CallBase>(&I);
7129 // Same handling as when creating module summary.
7130 if (!mayHaveMemprofSummary(CB))
7131 continue;
7132
7133 auto *CalledValue = CB->getCalledOperand();
7134 auto *CalledFunction = CB->getCalledFunction();
7135 if (CalledValue && !CalledFunction) {
7136 CalledValue = CalledValue->stripPointerCasts();
7137 // Stripping pointer casts can reveal a called function.
7138 CalledFunction = dyn_cast<Function>(CalledValue);
7139 }
7140 // Check if this is an alias to a function. If so, get the
7141 // called aliasee for the checks below.
7142 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
7143 assert(!CalledFunction &&
7144 "Expected null called function in callsite for alias");
7145 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
7146 }
7147
7148 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
7149 I.getMetadata(LLVMContext::MD_callsite));
7150 auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof);
7151
7152 // Include allocs that were already assigned a memprof function
7153 // attribute in the statistics. Only do this for those that do not have
7154 // memprof metadata, since we add an "ambiguous" memprof attribute by
7155 // default.
7156 if (CB->getAttributes().hasFnAttr("memprof") && !MemProfMD) {
7157 CB->getAttributes().getFnAttr("memprof").getValueAsString() == "cold"
7158 ? AllocTypeColdThinBackend++
7159 : AllocTypeNotColdThinBackend++;
7160 OrigAllocsThinBackend++;
7161 AllocVersionsThinBackend++;
7162 if (!MaxAllocVersionsThinBackend)
7163 MaxAllocVersionsThinBackend = 1;
7164 continue;
7165 }
7166
7167 if (MemProfMD) {
7168 // Consult the next alloc node.
7169 assert(AI != FS->allocs().end());
7170 auto &AllocNode = *(AI++);
7171
7172#ifndef NDEBUG
7173 checkAllocContextIds(AllocNode, MemProfMD, CallsiteContext,
7174 ImportSummary);
7175#endif
7176
7177 // Perform cloning if not yet done.
7178 CloneFuncIfNeeded(/*NumClones=*/AllocNode.Versions.size(), FS);
7179
7180 OrigAllocsThinBackend++;
7181 AllocVersionsThinBackend += AllocNode.Versions.size();
7182 if (MaxAllocVersionsThinBackend < AllocNode.Versions.size())
7183 MaxAllocVersionsThinBackend = AllocNode.Versions.size();
7184
7185 // If there is only one version that means we didn't end up
7186 // considering this function for cloning. Count that as unclonable
7187 // unless the single version is cold due to the
7188 // MinClonedColdBytePercent heuristic. The alloc may still be none
7189 // type (not reached during whole program analysis), in which case
7190 // there is nothing to apply; otherwise it got the type the whole
7191 // program analysis resolved it to (not cold, or both types when the
7192 // contexts could not be disambiguated), which is applied below like
7193 // for cloned functions so that the attribute matches the regular
7194 // LTO result.
7195 if (AllocNode.Versions.size() == 1 &&
7196 (AllocationType)AllocNode.Versions[0] != AllocationType::Cold)
7197 UnclonableAllocsThinBackend++;
7198
7199 // Update the allocation types per the summary info.
7200 for (unsigned J = 0; J < AllocNode.Versions.size(); J++) {
7201 // If the VMap is empty, this clone was a duplicate of another and
7202 // was created as an alias or a declaration.
7203 if (J > 0 && VMaps[J - 1]->empty())
7204 continue;
7205 // Ignore any that didn't get an assigned allocation type.
7206 if (AllocNode.Versions[J] == (uint8_t)AllocationType::None)
7207 continue;
7208 AllocationType AllocTy = (AllocationType)AllocNode.Versions[J];
7209 // The whole program analysis only records both types when
7210 // ambiguous attributes are enabled; if the backend runs without
7211 // them, fall back to the not cold default.
7212 if (isAmbiguousAllocType((uint8_t)AllocTy) &&
7214 AllocTy = AllocationType::NotCold;
7215 const bool IsAmbiguous = isAmbiguousAllocType((uint8_t)AllocTy);
7216 if (AllocTy == AllocationType::Cold)
7217 AllocTypeColdThinBackend++;
7218 else if (IsAmbiguous)
7219 AllocTypeAmbiguousThinBackend++;
7220 else
7221 AllocTypeNotColdThinBackend++;
7222 std::string AllocTypeString = getAllocTypeAttributeString(AllocTy);
7223 CallBase *CBClone;
7224 // Copy 0 is the original function.
7225 if (!J)
7226 CBClone = CB;
7227 else
7228 // Since VMaps are only created for new clones, we index with
7229 // clone J-1 (J==0 is the original clone and does not have a VMaps
7230 // entry).
7231 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
7232 if (IsAmbiguous) {
7233 // The contexts could not be disambiguated: keep (or add) the
7234 // ambiguous attribute from matching instead of a specific type.
7235 addAmbiguousAttribute(CBClone);
7236 } else {
7238 CBClone->addFnAttr(llvm::Attribute::get(F.getContext(), "memprof",
7239 AllocTypeString));
7240 }
7241 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", CBClone)
7242 << ore::NV("AllocationCall", CBClone) << " in clone "
7243 << ore::NV("Caller", CBClone->getFunction())
7244 << " marked with memprof allocation attribute "
7245 << ore::NV("Attribute", AllocTypeString));
7246 }
7247 } else if (!CallsiteContext.empty()) {
7248 if (!CalledFunction) {
7249#ifndef NDEBUG
7250 // We should have skipped inline assembly calls.
7251 auto *CI = dyn_cast<CallInst>(CB);
7252 assert(!CI || !CI->isInlineAsm());
7253#endif
7254 // We should have skipped direct calls via a Constant.
7255 assert(CalledValue && !isa<Constant>(CalledValue));
7256
7257 // This is an indirect call, see if we have profile information and
7258 // whether any clones were recorded for the profiled targets (that
7259 // we synthesized CallsiteInfo summary records for when building the
7260 // index). These records are the next ones in the function's
7261 // callsites, one per profiled target.
7262 auto NumClones = recordICPInfo(
7263 CB,
7264 [&](const InstrProfValueData &Candidate) {
7265 assert(SI != FS->callsites().end());
7266#ifndef NDEBUG
7267 auto CalleeValueInfo =
7268 ImportSummary->getValueInfo(Candidate.Value);
7269 auto LocalGUID =
7270 ImportSummary->getGUIDFromOriginalID(Candidate.Value);
7271#endif
7272 // We might not have a ValueInfo if this is a distributed
7273 // ThinLTO backend and decided not to import that function.
7274 // The thin link may also have updated the callee from the
7275 // original name GUID recorded in the VP metadata to the GUID
7276 // of the local target function (see
7277 // updateValueInfoForIndirectCalls).
7278 assert(!CalleeValueInfo || SI->Callee == CalleeValueInfo ||
7279 (SI->Callee && SI->Callee.getGUID() == LocalGUID));
7280 return &*(SI++);
7281 },
7282 ICallAnalysisInfo);
7283
7284 // Perform cloning if not yet done. This is done here in case
7285 // we don't need to do ICP, but might need to clone this
7286 // function as it is the target of other cloned calls.
7287 if (NumClones)
7288 CloneFuncIfNeeded(NumClones, FS);
7289 }
7290
7291 else {
7292 // Consult the next callsite node.
7293 assert(SI != FS->callsites().end());
7294 auto &StackNode = *(SI++);
7295
7296#ifndef NDEBUG
7297 // Sanity check that the stack ids match between the summary and
7298 // instruction metadata.
7299 auto StackIdIndexIter = StackNode.StackIdIndices.begin();
7300 for (auto StackId : CallsiteContext) {
7301 assert(StackIdIndexIter != StackNode.StackIdIndices.end());
7302 assert(ImportSummary->getStackIdAtIndex(*StackIdIndexIter) ==
7303 StackId);
7304 StackIdIndexIter++;
7305 }
7306#endif
7307
7308 CloneCallsite(StackNode, CB, CalledFunction, FS);
7309 }
7310 } else if (CB->isTailCall() && CalledFunction) {
7311 // Locate the synthesized callsite info for the callee VI, if any was
7312 // created, and use that for cloning.
7313 ValueInfo CalleeVI = findValueInfoForGV(
7314 *cast<GlobalValue>(CalledValue), M, ImportSummary, &F);
7315 if (CalleeVI && MapTailCallCalleeVIToCallsite.count(CalleeVI)) {
7316 auto Callsite = MapTailCallCalleeVIToCallsite.find(CalleeVI);
7317 assert(Callsite != MapTailCallCalleeVIToCallsite.end());
7318 CloneCallsite(Callsite->second, CB, CalledFunction, FS);
7319 }
7320 } else if (CB->isTailCall() && !CalledFunction &&
7321 !MapTailCallCalleeVIToCallsite.empty()) {
7322 // An indirect tail call, which the thin link may have identified as
7323 // being on profiled contexts with a missing frame, via the profiled
7324 // targets in its VP metadata. If so, the callsite infos synthesized
7325 // for those targets are used to perform ICP so that each clone of
7326 // this function calls the assigned clone of the target.
7327 auto PrevNumICallAnalysisInfo = ICallAnalysisInfo.size();
7328 auto NumClones = recordICPInfo(
7329 CB,
7330 [&](const InstrProfValueData &Candidate) {
7332 Candidate.Value, MapTailCallCalleeVIToCallsite,
7333 OrigNameGUIDToTailCallCallsite, AliasVIToGV, M,
7334 ImportSummary, *Symtab);
7335 },
7336 ICallAnalysisInfo);
7337 if (ICallAnalysisInfo.size() > PrevNumICallAnalysisInfo)
7338 IndirectTailCallsRecordedForICPThinBackend++;
7339 if (NumClones)
7340 CloneFuncIfNeeded(NumClones, FS);
7341 }
7342 }
7343 }
7344
7345 // Now do any promotion required for cloning.
7346 performICP(M, VMaps, ICallAnalysisInfo, ORE);
7347 }
7348
7349 // We skip some of the functions and instructions above, so remove all the
7350 // metadata in a single sweep here.
7351 for (auto &F : M) {
7352 // We can skip memprof clones because createFunctionClones already strips
7353 // the metadata from the newly created clones.
7354 if (F.isDeclaration() || isMemProfClone(F))
7355 continue;
7356 for (auto &BB : F) {
7357 for (auto &I : BB) {
7358 if (!isa<CallBase>(I))
7359 continue;
7360 I.setMetadata(LLVMContext::MD_memprof, nullptr);
7361 I.setMetadata(LLVMContext::MD_callsite, nullptr);
7362 }
7363 }
7364 }
7365
7366 return Changed;
7367}
7368
7369unsigned MemProfContextDisambiguation::recordICPInfo(
7370 CallBase *CB,
7371 function_ref<const CallsiteInfo *(const InstrProfValueData &)> GetCallsite,
7372 SmallVector<ICallAnalysisData> &ICallAnalysisInfo) {
7373 // First see if we have profile information for this indirect call.
7374 uint32_t NumCandidates;
7375 uint64_t TotalCount;
7376 auto CandidateProfileData =
7377 ICallAnalysis->getPromotionCandidatesForInstruction(
7378 CB, TotalCount, NumCandidates,
7380 if (CandidateProfileData.empty())
7381 return 0;
7382
7383 // Iterate through all of the candidate profiled targets along with the
7384 // CallsiteInfo summary records synthesized for them, and see if any are
7385 // cloned and/or refer to clones.
7386 bool ICPNeeded = false;
7387 unsigned NumClones = 0;
7389 for (const auto &Candidate : CandidateProfileData) {
7390 const CallsiteInfo *Callsite = GetCallsite(Candidate);
7391 Callsites.push_back(Callsite);
7392 if (!Callsite)
7393 continue;
7394 // See if any of the clones of the indirect callsite for this
7395 // profiled target should call a cloned version of the profiled
7396 // target. We only need to do the ICP here if so.
7397 ICPNeeded |= llvm::any_of(Callsite->Clones,
7398 [](unsigned CloneNo) { return CloneNo != 0; });
7399 // Every callsite in the same function should have been cloned the same
7400 // number of times.
7401 assert(!NumClones || NumClones == Callsite->Clones.size());
7402 NumClones = Callsite->Clones.size();
7403 }
7404 if (!ICPNeeded)
7405 return NumClones;
7406 // Save information for ICP, which is performed later to avoid messing up the
7407 // current function traversal.
7408 ICallAnalysisInfo.push_back({CB, CandidateProfileData.vec(), NumCandidates,
7409 TotalCount, NumClones, std::move(Callsites)});
7410 return NumClones;
7411}
7412
7413void MemProfContextDisambiguation::performICP(
7414 Module &M, ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
7415 ArrayRef<ICallAnalysisData> ICallAnalysisInfo,
7416 OptimizationRemarkEmitter &ORE) {
7417 // Now do any promotion required for cloning. Specifically, for each
7418 // recorded ICP candidate (which was only recorded because one clone of that
7419 // candidate should call a cloned target), we perform ICP (speculative
7420 // devirtualization) for each clone of the callsite, and update its callee
7421 // to the appropriate clone. Note that the ICP compares against the original
7422 // version of the target, which is what is in the vtable.
7423 for (auto &Info : ICallAnalysisInfo) {
7424 auto *CB = Info.CB;
7425 auto TotalCount = Info.TotalCount;
7426 unsigned NumClones = Info.NumClones;
7427 SmallVector<InstrProfValueData, 8> RemainingCandidates;
7428
7429 assert(Info.CandidateProfileData.size() == Info.Callsites.size());
7430 for (unsigned I = 0; I < Info.CandidateProfileData.size(); I++) {
7431 auto &Candidate = Info.CandidateProfileData[I];
7432 const CallsiteInfo *StackNode = Info.Callsites[I];
7433 // All calls in the same function must have the same number of clones.
7434 assert(!StackNode || NumClones == StackNode->Clones.size());
7435
7436 // See if the target is in the module. If it wasn't imported, it is
7437 // possible that this profile could have been collected on a different
7438 // target (or version of the code), and we need to be conservative
7439 // (similar to what is done in the ICP pass).
7440 Function *TargetFunction = Symtab->getFunction(Candidate.Value);
7441 // If not found, try the GUID of the callee recorded in the summary. For
7442 // local targets the VP metadata may contain the GUID of the original
7443 // name without the source file prefix (e.g. if it was synthesized from
7444 // the MemProf profile's callee GUIDs or from a SamplePGO profile), which
7445 // the thin link translates to the actual GUID of the local function
7446 // (see updateValueInfoForIndirectCalls). The latter is recorded in the
7447 // function's !guid metadata, which is preserved across promotion and
7448 // importing, and is added to the Symtab. If there is no summary record,
7449 // the target was not cloned, so we conservatively only promote it if
7450 // found directly via the VP metadata GUID.
7451 if (!TargetFunction && StackNode && StackNode->Callee &&
7452 StackNode->Callee.getGUID() != Candidate.Value)
7453 TargetFunction = Symtab->getFunction(StackNode->Callee.getGUID());
7454 // The target may be the aliasee of an alias imported as a copy of the
7455 // aliasee, without the aliasee itself being imported (e.g. an IRPGO value
7456 // profile records the aliasee for calls through the alias, as the alias
7457 // has no profile data of its own). The Symtab keys such a copy by the
7458 // alias GUID (see initializeIndirectCallPromotionInfo), so look for one
7459 // with the target's GUID as its aliasee GUID. Promoting to the copy is
7460 // correct as it has the same address, and its clones are aliases of the
7461 // aliasee's clones in the defining module.
7462 if (!TargetFunction) {
7463 if (!AliaseeGUIDToImportedAlias) {
7464 AliaseeGUIDToImportedAlias.emplace();
7465 for (Function &Fn : M) {
7466 if (isMemProfClone(Fn) || !getImportedAliasGUID(Fn))
7467 continue;
7468 if (auto AliaseeGUID = Fn.getGUIDIfAssigned())
7469 AliaseeGUIDToImportedAlias->try_emplace(*AliaseeGUID, &Fn);
7470 }
7471 }
7472 TargetFunction = AliaseeGUIDToImportedAlias->lookup(Candidate.Value);
7473 if (!TargetFunction && StackNode && StackNode->Callee &&
7474 StackNode->Callee.getGUID() != Candidate.Value)
7475 TargetFunction =
7476 AliaseeGUIDToImportedAlias->lookup(StackNode->Callee.getGUID());
7477 }
7478 if (TargetFunction == nullptr ||
7479 // Any ThinLTO global dead symbol removal should have already
7480 // occurred, so it should be safe to promote when the target is a
7481 // declaration.
7482 // TODO: Remove internal option once more fully tested.
7484 TargetFunction->isDeclaration())) {
7485 ORE.emit([&]() {
7486 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", CB)
7487 << "Memprof cannot promote indirect call: target with md5sum "
7488 << ore::NV("target md5sum", Candidate.Value) << " not found";
7489 });
7490 // FIXME: See if we can use the new declaration importing support to
7491 // at least get the declarations imported for this case. Hot indirect
7492 // targets should have been imported normally, however.
7493 RemainingCandidates.push_back(Candidate);
7494 continue;
7495 }
7496
7497 // Check if legal to promote
7498 const char *Reason = nullptr;
7499 if (!isLegalToPromote(*CB, TargetFunction, &Reason)) {
7500 ORE.emit([&]() {
7501 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", CB)
7502 << "Memprof cannot promote indirect call to "
7503 << ore::NV("TargetFunction", TargetFunction)
7504 << " with count of " << ore::NV("TotalCount", TotalCount)
7505 << ": " << Reason;
7506 });
7507 RemainingCandidates.push_back(Candidate);
7508 continue;
7509 }
7510
7511 assert(!isMemProfClone(*TargetFunction));
7512
7513 // Handle each call clone, applying ICP so that each clone directly
7514 // calls the specified callee clone, guarded by the appropriate ICP
7515 // check.
7516 CallBase *CBClone = CB;
7517 for (unsigned J = 0; J < NumClones; J++) {
7518 // If the VMap is empty, this clone was a duplicate of another and was
7519 // created as an alias or a declaration.
7520 if (J > 0 && VMaps[J - 1]->empty())
7521 continue;
7522 // Copy 0 is the original function.
7523 if (J > 0)
7524 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
7525 // We do the promotion using the original name, so that the comparison
7526 // is against the name in the vtable. Then just below, change the new
7527 // direct call to call the cloned function.
7528 auto &DirectCall =
7529 pgo::promoteIndirectCall(*CBClone, TargetFunction, Candidate.Count,
7530 TotalCount, isSamplePGO, &ORE);
7531 auto *TargetToUse = TargetFunction;
7532 // Call original if this version calls the original version of its
7533 // callee (always the case if there is no summary record).
7534 if (StackNode && StackNode->Clones[J]) {
7535 TargetToUse =
7536 cast<Function>(M.getOrInsertFunction(
7537 getMemProfFuncName(TargetFunction->getName(),
7538 StackNode->Clones[J]),
7539 TargetFunction->getFunctionType())
7540 .getCallee());
7541 }
7542 DirectCall.setCalledFunction(TargetToUse);
7543 // During matching we generate synthetic VP metadata for indirect calls
7544 // not already having any, from the memprof profile's callee GUIDs. If
7545 // we subsequently promote and inline those callees, we currently lose
7546 // the ability to generate this synthetic VP metadata. Optionally apply
7547 // a noinline attribute to promoted direct calls, where the threshold is
7548 // set to capture synthetic VP metadata targets which get a count of 1.
7550 Candidate.Count < MemProfICPNoInlineThreshold)
7551 DirectCall.setIsNoInline();
7552 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofCall", CBClone)
7553 << ore::NV("Call", CBClone) << " in clone "
7554 << ore::NV("Caller", CBClone->getFunction())
7555 << " promoted and assigned to call function clone "
7556 << ore::NV("Callee", TargetToUse));
7557 }
7558
7559 // Update TotalCount (all clones should get same count above)
7560 TotalCount -= Candidate.Count;
7561 }
7562 // Adjust the MD.prof metadata for all clones, now that we have the new
7563 // TotalCount and the remaining candidates.
7564 CallBase *CBClone = CB;
7565 for (unsigned J = 0; J < NumClones; J++) {
7566 // If the VMap is empty, this clone was a duplicate of another and was
7567 // created as an alias or a declaration.
7568 if (J > 0 && VMaps[J - 1]->empty())
7569 continue;
7570 // Copy 0 is the original function.
7571 if (J > 0)
7572 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
7573 // First delete the old one.
7574 CBClone->setMetadata(LLVMContext::MD_prof, nullptr);
7575 // If all promoted, we don't need the MD.prof metadata.
7576 // Otherwise we need update with the un-promoted records back.
7577 if (TotalCount != 0)
7578 annotateValueSite(M, *CBClone, RemainingCandidates, TotalCount,
7579 IPVK_IndirectCallTarget, Info.NumCandidates);
7580 }
7581 }
7582}
7583
7584template <typename DerivedCCG, typename FuncTy, typename CallTy>
7585bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::process(
7586 function_ref<void(StringRef, StringRef, const Twine &)> EmitRemark,
7587 bool AllowExtraAnalysis) {
7588 if (DumpCCG) {
7589 dbgs() << "CCG before cloning:\n";
7590 dbgs() << *this;
7591 }
7592 if (ExportToDot)
7593 exportToDot("postbuild");
7594
7595 if (VerifyCCG) {
7596 check();
7597 }
7598
7599 // The detail suffix needs the pre-cloning state of each context; only
7600 // capture it (extra memory and time) when it will be printed.
7602 capturePreCloningContextInfo();
7603
7604 identifyClones();
7605
7606 if (VerifyCCG) {
7607 check();
7608 }
7609
7610 if (DumpCCG) {
7611 dbgs() << "CCG after cloning:\n";
7612 dbgs() << *this;
7613 }
7614 if (ExportToDot)
7615 exportToDot("cloned");
7616
7617 bool Changed = assignFunctions();
7618
7619 if (DumpCCG) {
7620 dbgs() << "CCG after assigning function clones:\n";
7621 dbgs() << *this;
7622 }
7623 if (ExportToDot)
7624 exportToDot("clonefuncassign");
7625
7626 // AllowExtraAnalysis is set when the hinted size messages were enabled via
7627 // remarks (-pass-remarks=memprof-context-disambiguation).
7628 // TODO: Consider also supporting the detail suffix for the remark output.
7629 if (MemProfReportHintedSizes || AllowExtraAnalysis) {
7630 // The referenced-function set can be large; build it only now, when it is
7631 // used by the detail suffix, rather than keeping it across cloning.
7633 populateFunctionsWithCallers();
7634 printTotalSizes(errs(), EmitRemark);
7635 }
7636
7637 return Changed;
7638}
7639
7640bool MemProfContextDisambiguation::processModule(
7641 Module &M,
7642 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
7643
7644 // If we have an import summary, then the cloning decisions were made during
7645 // the thin link on the index. Apply them and return.
7646 if (ImportSummary)
7647 return applyImport(M);
7648
7649 // TODO: If/when other types of memprof cloning are enabled beyond just for
7650 // hot and cold, we will need to change this to individually control the
7651 // AllocationType passed to addStackNodesForMIB during CCG construction.
7652 // Note that we specifically check this after applying imports above, so that
7653 // the option isn't needed to be passed to distributed ThinLTO backend
7654 // clang processes, which won't necessarily have visibility into the linker
7655 // dependences. Instead the information is communicated from the LTO link to
7656 // the backends via the combined summary index.
7657 if (!SupportsHotColdNew)
7658 return false;
7659
7660 ModuleCallsiteContextGraph CCG(M, OREGetter);
7661 // TODO: Set up remarks for regular LTO. We need to decide what function to
7662 // use in the callback.
7663 return CCG.process();
7664}
7665
7667 const ModuleSummaryIndex *Summary, bool isSamplePGO)
7668 : ImportSummary(Summary), isSamplePGO(isSamplePGO) {
7669 // Check the dot graph printing options once here, to make sure we have valid
7670 // and expected combinations.
7671 if (DotGraphScope == DotScope::Alloc && !AllocIdForDot.getNumOccurrences())
7673 "-memprof-dot-scope=alloc requires -memprof-dot-alloc-id");
7675 !ContextIdForDot.getNumOccurrences())
7677 "-memprof-dot-scope=context requires -memprof-dot-context-id");
7678 if (DotGraphScope == DotScope::All && AllocIdForDot.getNumOccurrences() &&
7679 ContextIdForDot.getNumOccurrences())
7681 "-memprof-dot-scope=all can't have both -memprof-dot-alloc-id and "
7682 "-memprof-dot-context-id");
7683 if (ImportSummary) {
7684 // The MemProfImportSummary should only be used for testing ThinLTO
7685 // distributed backend handling via opt, in which case we don't have a
7686 // summary from the pass pipeline.
7688 return;
7689 }
7690 if (MemProfImportSummary.empty())
7691 return;
7692
7693 auto ReadSummaryFile =
7695 if (!ReadSummaryFile) {
7696 logAllUnhandledErrors(ReadSummaryFile.takeError(), errs(),
7697 "Error loading file '" + MemProfImportSummary +
7698 "': ");
7699 return;
7700 }
7701 auto ImportSummaryForTestingOrErr = getModuleSummaryIndex(**ReadSummaryFile);
7702 if (!ImportSummaryForTestingOrErr) {
7703 logAllUnhandledErrors(ImportSummaryForTestingOrErr.takeError(), errs(),
7704 "Error parsing file '" + MemProfImportSummary +
7705 "': ");
7706 return;
7707 }
7708 ImportSummaryForTesting = std::move(*ImportSummaryForTestingOrErr);
7709 ImportSummary = ImportSummaryForTesting.get();
7710}
7711
7714 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
7715 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
7716 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
7717 };
7718 if (!processModule(M, OREGetter))
7719 return PreservedAnalyses::all();
7720 return PreservedAnalyses::none();
7721}
7722
7723// After the thin link cloning decisions have been recorded in the summary
7724// callsite records, mark the summary indirect call edges to any callee that a
7725// callsite was assigned to call a (non-original) clone of as requiring a
7726// declaration import.
7727// See the comments for the MemProfImportClonedIndirectTargets option.
7729 ModuleSummaryIndex &Index,
7731 isPrevailing) {
7732 // Map from callee to the corresponding call edge in the current function
7733 // summary, so that we don't need to walk the function's call edges for each
7734 // callsite assigned to call a cloned callee. Note that there is a single call
7735 // edge per callee. The map is built lazily, the first time we encounter such
7736 // a callsite in a given function summary, since most functions have none
7737 // (the map is cleared before processing each function summary). The
7738 // pointers into the call edge vector remain valid since it isn't modified
7739 // while the map is in use.
7741 for (auto &I : Index) {
7742 auto VI = Index.getValueInfo(I);
7743 for (auto &S : VI.getSummaryList()) {
7744 // Only the prevailing copies were added to the CCG (see the
7745 // IndexCallsiteContextGraph constructor).
7746 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
7747 !isPrevailing(VI.getGUID(), S.get()))
7748 continue;
7749 auto *FS = dyn_cast<FunctionSummary>(S.get());
7750 if (!FS || FS->callsites().empty())
7751 continue;
7752 CalleeToEdge.clear();
7753 for (auto &CI : FS->callsites()) {
7754 if (!CI.Callee || llvm::all_of(CI.Clones, [](unsigned CloneNo) {
7755 return CloneNo == 0;
7756 }))
7757 continue;
7758 // Note that we mark the edge even if the callee is defined in the
7759 // same module as the caller, since the caller may be imported into
7760 // other modules. The function importer will skip importing the callee
7761 // into any module that already defines it.
7762 NumClonedCalleeCallsites++;
7763 // Lazily build the map on the first such callsite in this function.
7764 if (CalleeToEdge.empty())
7765 for (auto &[CalleeVI, Edge] : FS->mutableCalls())
7766 CalleeToEdge[CalleeVI] = &Edge;
7767 auto It = CalleeToEdge.find(CI.Callee);
7768 if (It == CalleeToEdge.end())
7769 continue;
7770 CalleeInfo *Edge = It->second;
7771 // Direct calls don't require importing the callee. Note that the
7772 // edge is marked indirect if any call to the callee in this function
7773 // is indirect, in which case we can't distinguish whether this
7774 // callsite is direct and conservatively treat it as indirect.
7775 if (!Edge->hasIndirectCall())
7776 continue;
7777 NumClonedCalleeIndirectCallsites++;
7778 if (!Edge->requiresDeclImport()) {
7779 Edge->setRequiresDeclImport(true);
7780 NumClonedCalleeEdgesMarkedRequiresDeclImport++;
7781 }
7782 }
7783 }
7784 }
7785}
7786
7788 ModuleSummaryIndex &Index,
7790 isPrevailing,
7791 LLVMContext &Ctx,
7792 function_ref<void(StringRef, StringRef, const Twine &)> EmitRemark) {
7793 // TODO: If/when other types of memprof cloning are enabled beyond just for
7794 // hot and cold, we will need to change this to individually control the
7795 // AllocationType passed to addStackNodesForMIB during CCG construction.
7796 // The index was set from the option, so these should be in sync.
7797 assert(Index.withSupportsHotColdNew() == SupportsHotColdNew);
7798 if (!SupportsHotColdNew)
7799 return;
7800
7801 bool AllowExtraAnalysis =
7803
7804 bool Changed = false;
7805 {
7806 IndexCallsiteContextGraph CCG(Index, isPrevailing);
7807 Changed = CCG.process(EmitRemark, AllowExtraAnalysis);
7808 }
7809 // Note this must be done after the CCG is destroyed, which is when the
7810 // callsite records synthesized for missing tail call frames are added to the
7811 // function summaries. Importing declarations is only useful if MemProf ICP
7812 // is allowed to promote to a declaration of the target.
7815 updateClonedCalleeEdgesForImport(Index, isPrevailing);
7816}
7817
7818// Strips MemProf attributes and metadata. Can be invoked by the pass pipeline
7819// when we don't have an index that has recorded that we are linking with
7820// allocation libraries containing the necessary APIs for downstream
7821// transformations.
7823 // The profile matcher applies hotness attributes directly for allocations,
7824 // and those will cause us to generate calls to the hot/cold interfaces
7825 // unconditionally. If supports-hot-cold-new was not enabled in the LTO
7826 // link then assume we don't want these calls (e.g. not linking with
7827 // the appropriate library, or otherwise trying to disable this behavior).
7828 bool Changed = false;
7829 for (auto &F : M) {
7830 for (auto &BB : F) {
7831 for (auto &I : BB) {
7832 auto *CI = dyn_cast<CallBase>(&I);
7833 if (!CI)
7834 continue;
7835 if (CI->hasFnAttr("memprof")) {
7836 CI->removeFnAttr("memprof");
7837 Changed = true;
7838 }
7839 if (!CI->hasMetadata(LLVMContext::MD_callsite)) {
7840 assert(!CI->hasMetadata(LLVMContext::MD_memprof));
7841 continue;
7842 }
7843 // Strip off all memprof metadata as it is no longer needed.
7844 // Importantly, this avoids the addition of new memprof attributes
7845 // after inlining propagation.
7846 CI->setMetadata(LLVMContext::MD_memprof, nullptr);
7847 CI->setMetadata(LLVMContext::MD_callsite, nullptr);
7848 Changed = true;
7849 }
7850 }
7851 }
7852 if (!Changed)
7853 return PreservedAnalyses::all();
7854 return PreservedAnalyses::none();
7855}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
Unify divergent function exit nodes
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static cl::opt< unsigned > TailCallSearchDepth("memprof-tail-call-search-depth", cl::init(5), cl::Hidden, cl::desc("Max depth to recursively search for missing " "frames through tail calls."))
uint64_t ComputeHash(const FunctionSummary *FS, unsigned I)
static cl::opt< DotScope > DotGraphScope("memprof-dot-scope", cl::desc("Scope of graph to export to dot"), cl::Hidden, cl::init(DotScope::All), cl::values(clEnumValN(DotScope::All, "all", "Export full callsite graph"), clEnumValN(DotScope::Alloc, "alloc", "Export only nodes with contexts feeding given " "-memprof-dot-alloc-id"), clEnumValN(DotScope::Context, "context", "Export only nodes with given -memprof-dot-context-id")))
static bool isMemProfClone(const GlobalValue &GV)
static cl::opt< bool > DoMergeIteration("memprof-merge-iteration", cl::init(true), cl::Hidden, cl::desc("Iteratively apply merging on a node to catch new callers"))
static cl::opt< unsigned > AllocIdForDot("memprof-dot-alloc-id", cl::init(0), cl::Hidden, cl::desc("Id of alloc to export if -memprof-dot-scope=alloc " "or to highlight if -memprof-dot-scope=all"))
static bool clonesHaveSameVersions(const FunctionSummary *FS, unsigned I, unsigned J)
static std::optional< GlobalValue::GUID > getImportedAliasGUID(const Function &F)
static void updateClonedCalleeEdgesForImport(ModuleSummaryIndex &Index, llvm::function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static cl::opt< unsigned > ContextIdForDot("memprof-dot-context-id", cl::init(0), cl::Hidden, cl::desc("Id of context to export if -memprof-dot-scope=context or to " "highlight otherwise"))
static cl::opt< bool > ExportToDot("memprof-export-to-dot", cl::init(false), cl::Hidden, cl::desc("Export graph to dot files."))
static ValueInfo findValueInfoForGV(const GlobalValue &GV, const Module &M, const ModuleSummaryIndex *ImportSummary, const Function *CallingFunc=nullptr)
static void checkEdge(const std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > &Edge)
static cl::opt< bool > AllowRecursiveCallsites("memprof-allow-recursive-callsites", cl::init(true), cl::Hidden, cl::desc("Allow cloning of callsites involved in recursive cycles"))
bool checkColdOrNotCold(uint8_t AllocType)
static cl::opt< bool > CloneRecursiveContexts("memprof-clone-recursive-contexts", cl::init(true), cl::Hidden, cl::desc("Allow cloning of contexts through recursive cycles"))
static std::string getAllocTypeString(uint8_t AllocTypes)
static cl::opt< bool > IndirectTailCallSearch("memprof-indirect-tail-call-search", cl::init(true), cl::Hidden, cl::desc("Search for missing frames through indirect tail calls to their " "profiled targets (ThinLTO)."))
bool DOTGraphTraits< constCallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * >::DoHighlight
static unsigned getMemProfCloneNum(const Function &F)
static cl::opt< unsigned > MemProfICPNoInlineThreshold("memprof-icp-noinline-threshold", cl::init(0), cl::Hidden, cl::desc("Minimum absolute count for promoted target to be inlinable"))
static SmallVector< std::unique_ptr< ValueToValueMapTy >, 4 > createFunctionClones(Function &F, unsigned NumClones, Module &M, OptimizationRemarkEmitter &ORE, std::map< const Function *, SmallPtrSet< const GlobalAlias *, 1 > > &FuncToAliasMap, FunctionSummary *FS)
static cl::opt< bool > VerifyCCG("memprof-verify-ccg", cl::init(false), cl::Hidden, cl::desc("Perform verification checks on CallingContextGraph."))
static void checkNode(const ContextNode< DerivedCCG, FuncTy, CallTy > *Node, bool CheckEdges=true)
static cl::opt< bool > MergeClones("memprof-merge-clones", cl::init(true), cl::Hidden, cl::desc("Merge clones before assigning functions"))
static std::string getMemProfFuncName(Twine Base, unsigned CloneNo)
static cl::opt< std::string > MemProfImportSummary("memprof-import-summary", cl::desc("Import summary to use for testing the ThinLTO backend via opt"), cl::Hidden)
static const CallsiteInfo * findIndirectTailCallCallsite(uint64_t CandidateGUID, const DenseMap< ValueInfo, CallsiteInfo > &MapTailCallCalleeVIToCallsite, std::optional< DenseMap< uint64_t, const CallsiteInfo * > > &OrigNameGUIDToTailCallCallsite, std::optional< DenseMap< ValueInfo, const GlobalAlias * > > &AliasVIToGV, const Module &M, const ModuleSummaryIndex *ImportSummary, InstrProfSymtab &Symtab)
static const std::string MemProfCloneSuffix
static void updateSubprogramLinkageName(Function *NewFunc, StringRef Name)
static cl::opt< bool > AllowRecursiveContexts("memprof-allow-recursive-contexts", cl::init(true), cl::Hidden, cl::desc("Allow cloning of contexts having recursive cycles"))
static cl::opt< std::string > DotFilePathPrefix("memprof-dot-file-path-prefix", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path prefix of the MemProf dot files."))
static cl::opt< bool > VerifyNodes("memprof-verify-nodes", cl::init(false), cl::Hidden, cl::desc("Perform frequent verification checks on nodes."))
static void checkAllocContextIds(const AllocInfo &AllocNode, const MDNode *MemProfMD, const CallStack< MDNode, MDNode::op_iterator > &CallsiteContext, const ModuleSummaryIndex *ImportSummary)
static cl::opt< bool > DumpCCG("memprof-dump-ccg", cl::init(false), cl::Hidden, cl::desc("Dump CallingContextGraph to stdout after each stage."))
AllocType
This is the interface to build a ModuleSummaryIndex for a module.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
const char * Msg
std::pair< BasicBlock *, BasicBlock * > Edge
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
ValueInfo getAliaseeVI() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
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.
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
void setCalledOperand(Value *V)
Subprogram description. Uses SubclassData1.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:811
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
bool erase(const KeyT &Val)
Definition DenseMap.h:930
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Function summary information to aid decisions and implementation of importing.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
DISubprogram * getSubprogram() const
Get the attached subprogram.
const Function & getFunction() const
Definition Function.h:167
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
Function and variable summary information to aid decisions and implementation of importing.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:158
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
Definition Globals.cpp:103
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
bool isWeakForLinker() const
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:500
Function * getFunction(uint64_t FuncMD5Hash) const
Return function from the name's md5 hash. Return nullptr if not found.
Definition InstrProf.h:800
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
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
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:668
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
Definition Metadata.h:1312
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
size_type count(const KeyT &Key) const
Definition MapVector.h:153
LLVM_ABI MemProfContextDisambiguation(const ModuleSummaryIndex *Summary=nullptr, bool isSamplePGO=false)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
uint64_t getStackIdAtIndex(unsigned Index) const
GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const
Return the GUID for OriginalId in the OidGuidMap.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
unsigned size() const
bool insert(SUnit *SU)
The optimization diagnostic interface.
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to produce fewer false positi...
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
A class that wrap the SHA1 algorithm.
Definition SHA1.h:27
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition SHA1.cpp:208
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
Definition SHA1.cpp:288
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
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
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
std::pair< StringRef, StringRef > rsplit(StringRef Separator) const
Split into two substrings around the last occurrence of a separator string.
Definition StringRef.h:769
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
bool erase(const ValueT &V)
Definition DenseSet.h:98
void insert_range(Range &&R)
Definition DenseSet.h:236
size_type size() const
Definition DenseSet.h:85
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:94
An efficient, type-erasing, non-owning reference to a callable.
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
CallStackIterator beginAfterSharedPrefix(const CallStack &Other)
CallStackIterator end() const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
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
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
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
LLVM_ABI CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
uint32_t NodeId
Definition RDFGraph.h:262
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
uint64_t read64le(const void *P)
Definition Endian.h:415
void write32le(void *P, uint32_t V)
Definition Endian.h:455
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"))
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
void stable_sort(R &&Range)
Definition STLExtras.h:2132
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
cl::opt< bool > MemProfUseAmbiguousAttributes
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool mayHaveMemprofSummary(const CallBase *CB)
Returns true if the instruction could have memprof metadata, used to ensure consistency between summa...
constexpr from_range_t from_range
static cl::opt< bool > MemProfRequireDefinitionForPromotion("memprof-require-definition-for-promotion", cl::init(false), cl::Hidden, cl::desc("Require target function definition when promoting indirect calls"))
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
cl::opt< unsigned > MemProfTopNImportant("memprof-top-n-important", cl::init(10), cl::Hidden, cl::desc("Number of largest cold contexts to consider important"))
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
static cl::opt< bool > MemProfImportClonedIndirectTargets("memprof-import-cloned-indirect-targets", cl::init(true), cl::Hidden, cl::desc("Import at least a declaration of the indirect call targets of " "callsites assigned to call a cloned callee (needed for MemProf " "ICP in the ThinLTO backend)"))
void set_subtract(S1Ty &S1, const S2Ty &S2)
set_subtract(A, B) - Compute A := A - B
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
bool set_intersects(const S1Ty &S1, const S2Ty &S2)
set_intersects(A, B) - Return true iff A ^ B is non empty
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
static cl::opt< bool > MemProfReportHintedSizesDetail("memprof-report-hinted-sizes-detail", cl::init(false), cl::Hidden, cl::desc("Append post-cloning call path and matching details to each " "-memprof-report-hinted-sizes line"))
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
cl::opt< bool > SupportsHotColdNew
Indicate we are linking with an allocator that supports hot/cold operator new interfaces.
static cl::opt< unsigned > MemProfReportHintedSizesDetailMaxPathLen("memprof-report-hinted-sizes-detail-max-path-len", cl::init(7), cl::Hidden, cl::desc("Maximum number of functions printed in full for a post-cloning " "call path in the -memprof-report-hinted-sizes-detail suffix; " "longer paths are elided in the middle"))
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
S1Ty set_intersection(const S1Ty &S1, const S2Ty &S2)
set_intersection(A, B) - Return A ^ B
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getMaxSummaryIndirectEdges(const LLVMContext &C)
Return -module-summary-max-indirect-edges.
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
S1Ty set_difference(const S1Ty &S1, const S2Ty &S2)
set_difference(A, B) - Return A - B
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition Error.h:1261
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
cl::opt< bool > MemProfFixupImportant("memprof-fixup-important", cl::init(true), cl::Hidden, cl::desc("Enables edge fixup for important contexts"))
#define N
static std::string getEdgeAttributes(NodeRef, ChildIteratorType ChildIter, GraphType G)
static const ContextNode< DerivedCCG, FuncTy, CallTy > * GetCallee(const EdgePtrTy &P)
std::unique_ptr< ContextNode< DerivedCCG, FuncTy, CallTy > > NodePtrTy
mapped_iterator< typename std::vector< std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > >::const_iterator, decltype(&GetCallee)> ChildIteratorType
mapped_iterator< typename std::vector< NodePtrTy >::const_iterator, decltype(&getNode)> nodes_iterator
std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > EdgePtrTy
Summary of memprof metadata on allocations.
std::vector< MIBInfo > MIBs
Class to accumulate and hold information about a callee.
Summary of memprof callsite metadata.
SmallVector< unsigned > StackIdIndices
SmallVector< unsigned > Clones
DefaultDOTGraphTraits(bool simple=false)
An information struct used to provide DenseMap with the various necessary components for a given valu...
typename GraphType::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:94
Struct that holds a reference to a particular GUID in a global value summary.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
GlobalValue::GUID getGUID() const
PointerUnion< CallsiteInfo *, AllocInfo * > SimpleType
static SimpleType getSimplifiedValue(IndexCall &Val)
const PointerUnion< CallsiteInfo *, AllocInfo * > SimpleType
static SimpleType getSimplifiedValue(const IndexCall &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34