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