55#define DEBUG_TYPE "memprof-context-disambiguation"
58 "Number of function clones created during whole program analysis");
60 "Number of function clones created during ThinLTO backend");
62 "Number of functions that had clones created during ThinLTO backend");
64 FunctionCloneDuplicatesThinBackend,
65 "Number of function clone duplicates detected during ThinLTO backend");
66STATISTIC(AllocTypeNotCold,
"Number of not cold static allocations (possibly "
67 "cloned) during whole program analysis");
68STATISTIC(AllocTypeCold,
"Number of cold static allocations (possibly cloned) "
69 "during whole program analysis");
71 "Number of ambiguous static allocations (possibly cloned) during "
72 "whole program analysis");
74 "Number of not cold static allocations (possibly cloned) during "
76STATISTIC(AllocTypeColdThinBackend,
"Number of cold static allocations "
77 "(possibly cloned) during ThinLTO backend");
79 "Number of ambiguous static allocations (possibly cloned) during "
82 "Number of original (not cloned) allocations with memprof profiles "
83 "during ThinLTO backend");
85 AllocVersionsThinBackend,
86 "Number of allocation versions (including clones) during ThinLTO backend");
88 "Maximum number of allocation versions created for an original "
89 "allocation during ThinLTO backend");
91 "Number of unclonable ambigous allocations during ThinLTO backend");
93 "Number of edges removed due to mismatched callees (profiled vs IR)");
95 "Number of profiled callees found via tail calls");
97 "Aggregate depth of profiled callees found via tail calls");
99 "Maximum depth of profiled callees found via tail calls");
101 "Number of profiled callees found via multiple tail call chains");
103 "Number of tail calls in chains to profiled callees that are "
104 "indirect (thin link)");
106 "Number of indirect tail calls recorded for ICP for cloning during "
108STATISTIC(DeferredBackedges,
"Number of backedges with deferred cloning");
109STATISTIC(NewMergedNodes,
"Number of new nodes created during merging");
110STATISTIC(NonNewMergedNodes,
"Number of non new nodes used during merging");
112 "Number of missing alloc nodes for context ids");
114 "Number of calls skipped during cloning due to unexpected operand");
116 "Number of callsites assigned to call multiple non-matching clones");
117STATISTIC(TotalMergeInvokes,
"Number of merge invocations for nodes");
118STATISTIC(TotalMergeIters,
"Number of merge iterations for nodes");
119STATISTIC(MaxMergeIters,
"Max merge iterations for nodes");
120STATISTIC(NumImportantContextIds,
"Number of important context ids");
121STATISTIC(NumFixupEdgeIdsInserted,
"Number of fixup edge ids inserted");
122STATISTIC(NumFixupEdgesAdded,
"Number of fixup edges added");
123STATISTIC(NumFixedContexts,
"Number of contexts with fixed edges");
125 "Number of callsite clones without an edge to a callee's clones "
126 "assigned the callee function clone of their original node");
128 "Number of calls in function clones whose callee was taken from a "
129 "callsite clone an implicit caller requires");
131 "Number of context ids with call stacks trimmed at a callsite");
133 "Number of callsite clones without an edge to a callee's clones "
134 "left in a function clone calling a conflicting callee clone");
136 "Number of aliasees prevailing in a different module than its alias");
138 "Number of summary callsites assigned to call a cloned callee (thin "
141 "Number of summary callsites assigned to call a cloned callee with "
142 "an indirect call edge (thin link)");
144 "Number of summary indirect call edges to cloned callees marked as "
145 "requiring a declaration import (thin link)");
147 "Number of calls assigned contexts trimmed within their inlined "
148 "stack id sequence");
150 "Number of (duplicated) context ids for contexts trimmed within a "
151 "call's inlined stack id sequence");
156 cl::desc(
"Specify the path prefix of the MemProf dot files."));
160 cl::desc(
"Export graph to dot files."));
165 cl::desc(
"Iteratively apply merging on a node to catch new callers"));
175 "memprof-dot-scope",
cl::desc(
"Scope of graph to export to dot"),
180 "Export only nodes with contexts feeding given "
181 "-memprof-dot-alloc-id"),
183 "Export only nodes with given -memprof-dot-context-id")));
187 cl::desc(
"Id of alloc to export if -memprof-dot-scope=alloc "
188 "or to highlight if -memprof-dot-scope=all"));
192 cl::desc(
"Id of context to export if -memprof-dot-scope=context or to "
193 "highlight otherwise"));
197 cl::desc(
"Dump CallingContextGraph to stdout after each stage."));
201 cl::desc(
"Perform verification checks on CallingContextGraph."));
205 cl::desc(
"Perform frequent verification checks on nodes."));
208 "memprof-import-summary",
209 cl::desc(
"Import summary to use for testing the ThinLTO backend via opt"),
215 cl::desc(
"Max depth to recursively search for missing "
216 "frames through tail calls."));
223 cl::desc(
"Search for missing frames through indirect tail calls to their "
224 "profiled targets (ThinLTO)."));
229 cl::desc(
"Allow cloning of callsites involved in recursive cycles"));
233 cl::desc(
"Allow cloning of contexts through recursive cycles"));
240 cl::desc(
"Merge clones before assigning functions"));
249 cl::desc(
"Allow cloning of contexts having recursive cycles"));
263 cl::desc(
"Assign contexts trimmed within a call's inlined stack id "
264 "sequence to that call"));
270 cl::desc(
"Minimum absolute count for promoted target to be inlinable"));
274 "enable-memprof-context-disambiguation",
cl::Hidden,
275 cl::desc(
"Enable MemProf context disambiguation"));
281 cl::desc(
"Linking with hot/cold operator new interfaces"));
286 "Require target function definition when promoting indirect calls"));
309 cl::desc(
"Import at least a declaration of the indirect call targets of "
310 "callsites assigned to call a cloned callee (needed for MemProf "
311 "ICP in the ThinLTO backend)"));
324 cl::desc(
"Append post-cloning call path and matching details to each "
325 "-memprof-report-hinted-sizes line"));
332 cl::desc(
"Maximum number of functions printed in full for a post-cloning "
333 "call path in the -memprof-report-hinted-sizes-detail suffix; "
334 "longer paths are elided in the middle"));
338 cl::desc(
"Number of largest cold contexts to consider important"));
342 cl::desc(
"Enables edge fixup for important contexts"));
362template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
363class CallsiteContextGraph {
365 CallsiteContextGraph() =
default;
366 CallsiteContextGraph(
const CallsiteContextGraph &) =
default;
367 CallsiteContextGraph(CallsiteContextGraph &&) =
default;
371 EmitRemark =
nullptr,
372 bool AllowExtraAnalysis =
false);
376 void identifyClones();
383 bool assignFunctions();
389 EmitRemark =
nullptr)
const;
392 const CallsiteContextGraph &CCG) {
397 friend struct GraphTraits<
398 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
399 friend struct DOTGraphTraits<
400 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
402 void exportToDot(std::string Label)
const;
405 struct FuncInfo final
406 :
public std::pair<FuncTy *, unsigned > {
407 using Base = std::pair<FuncTy *, unsigned>;
408 FuncInfo(
const Base &
B) : Base(
B) {}
409 FuncInfo(FuncTy *
F =
nullptr,
unsigned CloneNo = 0) : Base(
F, CloneNo) {}
410 explicit operator bool()
const {
return this->first !=
nullptr; }
411 FuncTy *func()
const {
return this->first; }
412 unsigned cloneNo()
const {
return this->second; }
416 struct CallInfo final :
public std::pair<CallTy, unsigned > {
417 using Base = std::pair<CallTy, unsigned>;
418 CallInfo(
const Base &
B) : Base(
B) {}
419 CallInfo(CallTy
Call =
nullptr,
unsigned CloneNo = 0)
420 : Base(
Call, CloneNo) {}
421 explicit operator bool()
const {
return (
bool)this->first; }
422 CallTy call()
const {
return this->first; }
423 unsigned cloneNo()
const {
return this->second; }
424 void setCloneNo(
unsigned N) { this->second =
N; }
425 void print(raw_ostream &OS)
const {
426 if (!
operator bool()) {
432 OS <<
"\t(clone " << cloneNo() <<
")";
438 friend raw_ostream &
operator<<(raw_ostream &OS,
const CallInfo &
Call) {
458 bool Recursive =
false;
462 uint8_t AllocTypes = 0;
485 std::vector<std::shared_ptr<ContextEdge>> CalleeEdges;
489 std::vector<std::shared_ptr<ContextEdge>> CallerEdges;
493 bool useCallerEdgesForContextInfo()
const {
498 assert(!CalleeEdges.empty() || CallerEdges.empty() || IsAllocation ||
510 DenseSet<uint32_t> getContextIds()
const {
516 for (
auto &
Edge : CalleeEdges.empty() ? CallerEdges : CalleeEdges)
518 DenseSet<uint32_t> ContextIds;
521 CalleeEdges, useCallerEdgesForContextInfo()
523 : std::vector<std::shared_ptr<ContextEdge>>());
524 for (
const auto &
Edge : Edges)
531 uint8_t computeAllocType()
const {
533 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
534 uint8_t
AllocType = (uint8_t)AllocationType::None;
536 CalleeEdges, useCallerEdgesForContextInfo()
538 : std::vector<std::shared_ptr<ContextEdge>>());
539 for (
const auto &
Edge : Edges) {
550 bool emptyContextIds()
const {
552 CalleeEdges, useCallerEdgesForContextInfo()
554 : std::vector<std::shared_ptr<ContextEdge>>());
555 for (
const auto &
Edge : Edges) {
556 if (!
Edge->getContextIds().empty())
563 bool hasContextId(uint32_t Id)
const {
565 CalleeEdges, useCallerEdgesForContextInfo()
567 : std::vector<std::shared_ptr<ContextEdge>>());
568 for (
const auto &
Edge : Edges) {
569 if (
Edge->getContextIds().contains(Id))
578 void removeContextIdsNotPresent(DenseSet<uint32_t> &Ids)
const {
579 DenseSet<uint32_t> NotFound = Ids;
581 CalleeEdges, useCallerEdgesForContextInfo()
583 : std::vector<std::shared_ptr<ContextEdge>>());
584 for (
const auto &
Edge : Edges) {
585 const auto &EdgeIds =
Edge->getContextIds();
587 if (EdgeIds.size() < NotFound.size()) {
588 for (
auto Id : EdgeIds)
592 [&EdgeIds](uint32_t Id) {
return EdgeIds.contains(Id); });
594 if (NotFound.empty())
601 std::vector<ContextNode *> Clones;
604 ContextNode *CloneOf =
nullptr;
606 ContextNode(
bool IsAllocation) : IsAllocation(IsAllocation), Call() {}
608 ContextNode(
bool IsAllocation, CallInfo
C)
609 : IsAllocation(IsAllocation), Call(
C) {}
611 void addClone(ContextNode *Clone) {
613 CloneOf->Clones.push_back(Clone);
614 Clone->CloneOf = CloneOf;
616 Clones.push_back(Clone);
618 Clone->CloneOf =
this;
622 ContextNode *getOrigNode() {
628 const ContextNode *getOrigNode()
const {
635 unsigned int ContextId);
637 ContextEdge *findEdgeFromCallee(
const ContextNode *Callee);
638 ContextEdge *findEdgeFromCaller(
const ContextNode *Caller);
639 void eraseCalleeEdge(
const ContextEdge *
Edge);
640 void eraseCallerEdge(
const ContextEdge *
Edge);
642 void setCall(CallInfo
C) { Call = std::move(
C); }
644 bool hasCall()
const {
return (
bool)Call.call(); }
646 void printCall(raw_ostream &OS)
const { Call.print(OS); }
650 bool isRemoved()
const {
656 (AllocTypes == (uint8_t)AllocationType::None) ==
658 return AllocTypes == (uint8_t)AllocationType::None;
662 void print(raw_ostream &OS)
const;
664 friend raw_ostream &
operator<<(raw_ostream &OS,
const ContextNode &Node) {
678 uint8_t AllocTypes = 0;
686 bool IsBackedge =
false;
689 DenseSet<uint32_t> ContextIds;
691 ContextEdge(ContextNode *Callee, ContextNode *Caller, uint8_t
AllocType,
692 DenseSet<uint32_t> ContextIds)
693 : Callee(Callee), Caller(Caller), AllocTypes(
AllocType),
694 ContextIds(std::
move(ContextIds)) {}
696 DenseSet<uint32_t> &getContextIds() {
return ContextIds; }
700 inline void clear() {
702 AllocTypes = (uint8_t)AllocationType::None;
710 inline bool isRemoved()
const {
711 if (Callee || Caller)
716 assert(AllocTypes == (uint8_t)AllocationType::None);
717 assert(ContextIds.empty());
722 void print(raw_ostream &OS)
const;
724 friend raw_ostream &
operator<<(raw_ostream &OS,
const ContextEdge &
Edge) {
732 void removeNoneTypeCalleeEdges(ContextNode *Node);
733 void removeNoneTypeCallerEdges(ContextNode *Node);
735 recursivelyRemoveNoneTypeCalleeEdges(ContextNode *Node,
736 DenseSet<const ContextNode *> &Visited);
741 template <
class NodeT,
class IteratorT>
742 std::vector<ContextNode *>
743 getStackNodesForCallsite(CallStack<NodeT, IteratorT> &CallsiteContext);
747 ContextNode *addAllocNode(CallInfo
Call,
const FuncTy *
F);
750 template <
class NodeT,
class IteratorT>
751 void addStackNodesForMIB(
752 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
755 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold);
760 void updateStackNodes();
769 void fixupImportantContexts();
773 void handleCallsitesWithMultipleTargets();
776 void markBackedges();
786 bool partitionCallsByCallee(
788 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode);
792 MapVector<FuncTy *, std::vector<CallInfo>> FuncToCallsWithMetadata;
795 std::map<const ContextNode *, const FuncTy *> NodeToCallingFunc;
797 const FuncTy *getCallingFunc(
const ContextNode *
N)
const {
798 auto It = NodeToCallingFunc.find(
N);
799 return It != NodeToCallingFunc.end() ? It->second :
nullptr;
807 DenseSet<const FuncTy *> FunctionsWithCallers;
811 DenseSet<uint32_t> DotAllocContextIds;
814 using EdgeIter =
typename std::vector<std::shared_ptr<ContextEdge>>::iterator;
819 struct CallContextInfo {
827 std::vector<ContextNode *> StackNodes;
832 DenseSet<uint32_t> ContextIds;
837 DenseSet<uint32_t> TrimmedInlinedDupIds;
846 void removeEdgeFromGraph(ContextEdge *
Edge, EdgeIter *EI =
nullptr,
847 bool CalleeIter =
true);
855 void assignStackNodesPostOrder(
856 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
857 DenseMap<
uint64_t, std::vector<CallContextInfo>> &StackIdToMatchingCalls,
858 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
859 const DenseSet<uint32_t> &ImportantContextIds);
865 DenseSet<uint32_t> duplicateContextIds(
866 const DenseSet<uint32_t> &StackSequenceContextIds,
867 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds,
868 function_ref<
void(uint32_t OldId, uint32_t NewId)> OnDuplicate =
nullptr);
871 void propagateDuplicateContextIds(
872 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds);
878 struct TrimmedAtNodeCache {
879 DenseMap<const ContextNode *, unsigned> NodeToIndex;
880 std::vector<DenseSet<uint32_t>> TrimmedAtNodeIds;
888 TrimmedAtNodeCache &Cache);
893 void connectNewNode(ContextNode *NewNode, ContextNode *OrigNode,
894 bool TowardsCallee,
const DenseSet<uint32_t> &ContextIds);
900 return static_cast<const DerivedCCG *
>(
this)->getStackId(IdOrIndex);
910 calleesMatch(CallTy
Call, EdgeIter &EI,
911 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap);
915 const FuncTy *getCalleeFunc(CallTy
Call) {
916 return static_cast<DerivedCCG *
>(
this)->getCalleeFunc(
Call);
922 bool calleeMatchesFunc(
923 CallTy
Call,
const FuncTy *Func,
const FuncTy *CallerFunc,
924 std::vector<std::pair<CallTy, FuncTy *>> &FoundCalleeChain) {
925 return static_cast<DerivedCCG *
>(
this)->calleeMatchesFunc(
926 Call, Func, CallerFunc, FoundCalleeChain);
930 bool sameCallee(CallTy Call1, CallTy Call2) {
931 return static_cast<DerivedCCG *
>(
this)->sameCallee(Call1, Call2);
936 std::vector<ContextNode *> getStackNodesForCall(CallTy
Call) {
937 return static_cast<DerivedCCG *
>(
this)->getStackNodesForCall(
Call);
942 return static_cast<DerivedCCG *
>(
this)->getLastStackId(
Call);
950 AllocTypeAmbiguous++;
953 static_cast<DerivedCCG *
>(
this)->updateAllocationCall(
Call,
AllocType);
958 return static_cast<const DerivedCCG *
>(
this)->getAllocationCallType(
Call);
963 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc) {
964 static_cast<DerivedCCG *
>(
this)->updateCall(CallerCall, CalleeFunc);
970 FuncInfo cloneFunctionForCallsite(
971 FuncInfo &Func, CallInfo &
Call, DenseMap<CallInfo, CallInfo> &CallMap,
972 std::vector<CallInfo> &CallsWithMetadataInFunc,
unsigned CloneNo) {
973 return static_cast<DerivedCCG *
>(
this)->cloneFunctionForCallsite(
974 Func,
Call, CallMap, CallsWithMetadataInFunc, CloneNo);
979 std::string getLabel(
const FuncTy *Func,
const CallTy
Call,
980 unsigned CloneNo)
const {
981 return static_cast<const DerivedCCG *
>(
this)->getLabel(Func,
Call, CloneNo);
985 std::string getFuncName(
const FuncTy *Func,
unsigned CloneNo = 0)
const {
986 return static_cast<const DerivedCCG *
>(
this)->getFuncName(Func, CloneNo);
991 bool isFuncDead(
const FuncTy *Func)
const {
992 return static_cast<const DerivedCCG *
>(
this)->isFuncDead(Func);
996 void populateFunctionsWithCallers() {
997 static_cast<DerivedCCG *
>(
this)->populateFunctionsWithCallers();
1002 void capturePreCloningContextInfo();
1007 std::string formatContextReportSuffix(
const ContextNode *Node,
1011 ContextNode *createNewNode(
bool IsAllocation,
const FuncTy *
F =
nullptr,
1012 CallInfo
C = CallInfo()) {
1013 NodeOwner.push_back(std::make_unique<ContextNode>(IsAllocation,
C));
1014 auto *NewNode = NodeOwner.back().get();
1016 NodeToCallingFunc[NewNode] =
F;
1017 NewNode->NodeId = NodeOwner.size();
1022 ContextNode *getNodeForInst(
const CallInfo &
C);
1023 ContextNode *getNodeForAlloc(
const CallInfo &
C);
1024 ContextNode *getNodeForStackId(
uint64_t StackId);
1028 uint8_t computeAllocType(DenseSet<uint32_t> &ContextIds)
const;
1033 uint8_t intersectAllocTypesImpl(
const DenseSet<uint32_t> &Node1Ids,
1034 const DenseSet<uint32_t> &Node2Ids)
const;
1038 uint8_t intersectAllocTypes(
const DenseSet<uint32_t> &Node1Ids,
1039 const DenseSet<uint32_t> &Node2Ids)
const;
1046 moveEdgeToNewCalleeClone(
const std::shared_ptr<ContextEdge> &
Edge,
1047 DenseSet<uint32_t> ContextIdsToMove = {});
1053 void moveEdgeToExistingCalleeClone(
const std::shared_ptr<ContextEdge> &
Edge,
1054 ContextNode *NewCallee,
1055 bool NewClone =
false,
1056 DenseSet<uint32_t> ContextIdsToMove = {});
1063 void moveCalleeEdgeToNewCaller(
const std::shared_ptr<ContextEdge> &
Edge,
1064 ContextNode *NewCaller);
1067 void markBackedges(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1068 DenseSet<const ContextNode *> &CurrentStack);
1072 mergeClones(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1073 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode);
1075 void mergeNodeCalleeClones(
1076 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1077 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode);
1080 void findOtherCallersToShareMerge(
1081 ContextNode *Node, std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
1082 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
1083 DenseSet<ContextNode *> &OtherCallersToShareMerge);
1089 void identifyClones(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
1090 const DenseSet<uint32_t> &AllocContextIds);
1095 struct ImplicitSource {
1097 const ContextNode *Source;
1105 using ImplicitSourceMap =
1106 DenseMap<std::pair<const ContextNode *, unsigned>, ImplicitSource>;
1113 void assignImplicitCallers(
1114 ContextNode *Node,
const DenseSet<uint32_t> &TrimmedContextIds,
1115 DenseMap<ContextNode *, FuncInfo> &CallsiteToCalleeFuncCloneMap,
1116 const std::map<FuncInfo, ContextNode *> &FuncCloneToCurNodeCloneMap,
1117 ImplicitSourceMap &ImplicitSources);
1123 static const ContextNode *resolveImplicitSource(
const ContextNode *Node,
1124 const ImplicitSource &Src);
1127 DenseMap<uint32_t, AllocationType> ContextIdToAllocationType;
1133 DenseMap<uint32_t, std::vector<ContextTotalSize>> ContextIdToContextSizeInfos;
1139 DenseMap<uint64_t, ContextNode *> StackEntryIdToContextNodeMap;
1143 struct ImportantContextInfo {
1145 std::vector<uint64_t> StackIds;
1148 unsigned MaxLength = 0;
1152 std::map<std::vector<uint64_t>, ContextNode *> StackIdsToNode;
1156 DenseMap<uint32_t, ImportantContextInfo> ImportantContextIdInfo;
1165 const DenseSet<uint32_t> &NodeContextIds,
1166 const DenseSet<uint32_t> &ImportantContextIds) {
1171 DenseSet<uint32_t> Ids =
1175 std::vector<uint64_t> StackIds;
1176 StackIds.reserve(StackNodes.
size());
1177 for (
const ContextNode *
N : StackNodes)
1178 StackIds.push_back(
N->OrigStackOrAllocId);
1179 auto Size = StackIds.size();
1180 for (
auto Id : Ids) {
1181 auto &
Entry = ImportantContextIdInfo[
Id];
1190 MapVector<CallInfo, ContextNode *> AllocationCallToContextNodeMap;
1191 MapVector<CallInfo, ContextNode *> NonAllocationCallToContextNodeMap;
1194 std::vector<std::unique_ptr<ContextNode>> NodeOwner;
1200 unsigned int LastContextId = 0;
1208 struct PreCloningContextInfo {
1212 std::vector<const ContextNode *> Chain;
1222 unsigned MaxMatchedFrame = 0;
1225 bool OutermostMatchedNodeHasOtherCallers =
false;
1230 bool StoppedAtRecursive =
false;
1231 bool StoppedAtMismatchedCallee =
false;
1234 const FuncTy *UnmatchedCallingFunc =
nullptr;
1237 DenseMap<uint32_t, PreCloningContextInfo> PreCloningContextInfoMap;
1240 DenseSet<const ContextNode *> PreCloningAllocHasMatchedCaller;
1243 DenseMap<const FuncTy *, unsigned> FuncToNumClones;
1248 DenseMap<std::pair<const ContextNode *, unsigned>,
unsigned>
1249 OrigNodeAndCloneToCalleeClone;
1253 DenseMap<std::pair<const ContextNode *, unsigned>,
const ContextNode *>
1254 OrigAllocAndCloneToNode;
1257template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1259 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode;
1260template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1262 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge;
1263template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1265 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::FuncInfo;
1266template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1268 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::CallInfo;
1271class ModuleCallsiteContextGraph
1272 :
public CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
1275 ModuleCallsiteContextGraph(
1277 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter);
1280 friend CallsiteContextGraph<ModuleCallsiteContextGraph,
Function,
1285 bool calleeMatchesFunc(
1287 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain);
1288 bool sameCallee(Instruction *Call1, Instruction *Call2);
1289 bool findProfiledCalleeThroughTailCalls(
1291 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
1292 bool &FoundMultipleCalleeChains);
1294 std::vector<ContextNode *> getStackNodesForCall(Instruction *
Call);
1297 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1298 CallsiteContextGraph<ModuleCallsiteContextGraph,
Function,
1300 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &
Call,
1301 DenseMap<CallInfo, CallInfo> &CallMap,
1302 std::vector<CallInfo> &CallsWithMetadataInFunc,
1304 std::string getLabel(
const Function *Func,
const Instruction *
Call,
1305 unsigned CloneNo)
const;
1306 std::string getFuncName(
const Function *Func,
unsigned CloneNo = 0)
const;
1307 bool isFuncDead(
const Function *Func)
const {
return false; }
1308 void populateFunctionsWithCallers();
1311 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter;
1317struct IndexCall :
public PointerUnion<CallsiteInfo *, AllocInfo *> {
1318 IndexCall() : PointerUnion() {}
1319 IndexCall(std::nullptr_t) : IndexCall() {}
1320 IndexCall(CallsiteInfo *StackNode) : PointerUnion(StackNode) {}
1321 IndexCall(AllocInfo *AllocNode) : PointerUnion(AllocNode) {}
1322 IndexCall(PointerUnion PT) : PointerUnion(PT) {}
1324 IndexCall *operator->() {
return this; }
1326 void print(raw_ostream &OS)
const {
1327 PointerUnion<CallsiteInfo *, AllocInfo *>
Base = *
this;
1352class IndexCallsiteContextGraph
1353 :
public CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1356 IndexCallsiteContextGraph(
1357 ModuleSummaryIndex &Index,
1361 ~IndexCallsiteContextGraph() {
1366 for (
auto &
I : FunctionCalleesToSynthesizedCallsiteInfos) {
1368 for (
auto &Callsite :
I.second)
1369 FS->addCallsite(std::move(*Callsite.second));
1374 friend CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1378 const FunctionSummary *getCalleeFunc(IndexCall &
Call);
1379 bool calleeMatchesFunc(
1380 IndexCall &
Call,
const FunctionSummary *Func,
1381 const FunctionSummary *CallerFunc,
1382 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain);
1383 bool sameCallee(IndexCall &Call1, IndexCall &Call2);
1384 bool findProfiledCalleeThroughTailCalls(
1385 ValueInfo ProfiledCallee, ValueInfo CurCallee,
unsigned Depth,
1386 std::vector<std::pair<ValueInfo, FunctionSummary *>> &FoundCalleeChain,
1387 bool &FoundMultipleCalleeChains);
1389 std::vector<ContextNode *> getStackNodesForCall(IndexCall &
Call);
1392 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1393 CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1394 IndexCall>::FuncInfo
1395 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &
Call,
1396 DenseMap<CallInfo, CallInfo> &CallMap,
1397 std::vector<CallInfo> &CallsWithMetadataInFunc,
1399 std::string getLabel(
const FunctionSummary *Func,
const IndexCall &
Call,
1400 unsigned CloneNo)
const;
1401 std::string getFuncName(
const FunctionSummary *Func,
1402 unsigned CloneNo = 0)
const;
1403 bool isFuncDead(
const FunctionSummary *Func)
const;
1404 void populateFunctionsWithCallers();
1405 DenseSet<GlobalValue::GUID> findAliaseeGUIDsPrevailingInDifferentModule();
1409 std::map<const FunctionSummary *, ValueInfo> FSToVIMap;
1411 const ModuleSummaryIndex &Index;
1419 DenseMap<FunctionSummary *,
1420 std::map<ValueInfo, std::unique_ptr<CallsiteInfo>>>
1421 FunctionCalleesToSynthesizedCallsiteInfos;
1432 :
public DenseMapInfo<std::pair<IndexCall, unsigned>> {};
1435 :
public DenseMapInfo<PointerUnion<CallsiteInfo *, AllocInfo *>> {};
1456template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1457bool allocTypesMatch(
1458 const std::vector<uint8_t> &InAllocTypes,
1459 const std::vector<std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>>
1463 assert(InAllocTypes.size() == Edges.size());
1465 InAllocTypes.begin(), InAllocTypes.end(), Edges.begin(), Edges.end(),
1467 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &r) {
1471 if (l == (uint8_t)AllocationType::None ||
1472 r->AllocTypes == (uint8_t)AllocationType::None)
1474 return allocTypeToUse(l) == allocTypeToUse(r->AllocTypes);
1483template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1484bool allocTypesMatchClone(
1485 const std::vector<uint8_t> &InAllocTypes,
1486 const ContextNode<DerivedCCG, FuncTy, CallTy> *Clone) {
1487 const ContextNode<DerivedCCG, FuncTy, CallTy> *
Node = Clone->CloneOf;
1491 assert(InAllocTypes.size() ==
Node->CalleeEdges.size());
1495 for (
const auto &
E : Clone->CalleeEdges) {
1497 EdgeCalleeMap[
E->Callee] =
E->AllocTypes;
1501 for (
unsigned I = 0;
I <
Node->CalleeEdges.size();
I++) {
1502 auto Iter = EdgeCalleeMap.
find(
Node->CalleeEdges[
I]->Callee);
1504 if (Iter == EdgeCalleeMap.
end())
1512 if (allocTypeToUse(Iter->second) != allocTypeToUse(InAllocTypes[
I]))
1520template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1521typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1522CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForInst(
1523 const CallInfo &
C) {
1524 ContextNode *
Node = getNodeForAlloc(
C);
1528 return NonAllocationCallToContextNodeMap.lookup(
C);
1531template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1532typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1533CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForAlloc(
1534 const CallInfo &
C) {
1535 return AllocationCallToContextNodeMap.lookup(
C);
1538template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1539typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1540CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForStackId(
1542 auto StackEntryNode = StackEntryIdToContextNodeMap.
find(StackId);
1543 if (StackEntryNode != StackEntryIdToContextNodeMap.
end())
1544 return StackEntryNode->second;
1548template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1549void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1551 unsigned int ContextId) {
1552 for (
auto &
Edge : CallerEdges) {
1553 if (
Edge->Caller == Caller) {
1555 Edge->getContextIds().insert(ContextId);
1559 std::shared_ptr<ContextEdge>
Edge = std::make_shared<ContextEdge>(
1560 this, Caller, (uint8_t)
AllocType, DenseSet<uint32_t>({ContextId}));
1561 CallerEdges.push_back(
Edge);
1565template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1566void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::removeEdgeFromGraph(
1567 ContextEdge *
Edge, EdgeIter *EI,
bool CalleeIter) {
1583 auto CalleeCallerCount =
Callee->CallerEdges.size();
1584 auto CallerCalleeCount =
Caller->CalleeEdges.size();
1589 }
else if (CalleeIter) {
1591 *EI =
Caller->CalleeEdges.erase(*EI);
1594 *EI =
Callee->CallerEdges.erase(*EI);
1596 assert(
Callee->CallerEdges.size() < CalleeCallerCount);
1597 assert(
Caller->CalleeEdges.size() < CallerCalleeCount);
1600template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1601void CallsiteContextGraph<
1602 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCalleeEdges(ContextNode *Node) {
1603 for (
auto EI =
Node->CalleeEdges.begin(); EI !=
Node->CalleeEdges.end();) {
1605 if (
Edge->AllocTypes == (uint8_t)AllocationType::None) {
1607 removeEdgeFromGraph(
Edge.get(), &EI,
true);
1613template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1614void CallsiteContextGraph<
1615 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCallerEdges(ContextNode *Node) {
1616 for (
auto EI =
Node->CallerEdges.begin(); EI !=
Node->CallerEdges.end();) {
1618 if (
Edge->AllocTypes == (uint8_t)AllocationType::None) {
1620 Edge->Caller->eraseCalleeEdge(
Edge.get());
1621 EI =
Node->CallerEdges.erase(EI);
1627template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1628typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1629CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1630 findEdgeFromCallee(
const ContextNode *Callee) {
1631 for (
const auto &
Edge : CalleeEdges)
1632 if (
Edge->Callee == Callee)
1637template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1638typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1639CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1640 findEdgeFromCaller(
const ContextNode *Caller) {
1641 for (
const auto &
Edge : CallerEdges)
1642 if (
Edge->Caller == Caller)
1647template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1648void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1649 eraseCalleeEdge(
const ContextEdge *
Edge) {
1651 CalleeEdges, [
Edge](
const std::shared_ptr<ContextEdge> &CalleeEdge) {
1652 return CalleeEdge.get() ==
Edge;
1654 assert(EI != CalleeEdges.end());
1655 CalleeEdges.erase(EI);
1658template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1659void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1660 eraseCallerEdge(
const ContextEdge *
Edge) {
1662 CallerEdges, [
Edge](
const std::shared_ptr<ContextEdge> &CallerEdge) {
1663 return CallerEdge.get() ==
Edge;
1665 assert(EI != CallerEdges.end());
1666 CallerEdges.erase(EI);
1669template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1670uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::computeAllocType(
1671 DenseSet<uint32_t> &ContextIds)
const {
1673 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1674 uint8_t
AllocType = (uint8_t)AllocationType::None;
1675 for (
auto Id : ContextIds) {
1676 AllocType |= (uint8_t)ContextIdToAllocationType.
at(Id);
1684template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1686CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypesImpl(
1687 const DenseSet<uint32_t> &Node1Ids,
1688 const DenseSet<uint32_t> &Node2Ids)
const {
1690 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1691 uint8_t
AllocType = (uint8_t)AllocationType::None;
1692 for (
auto Id : Node1Ids) {
1693 if (!Node2Ids.
count(Id))
1695 AllocType |= (uint8_t)ContextIdToAllocationType.
at(Id);
1703template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1704uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypes(
1705 const DenseSet<uint32_t> &Node1Ids,
1706 const DenseSet<uint32_t> &Node2Ids)
const {
1707 if (Node1Ids.
size() < Node2Ids.
size())
1708 return intersectAllocTypesImpl(Node1Ids, Node2Ids);
1710 return intersectAllocTypesImpl(Node2Ids, Node1Ids);
1713template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1714typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1715CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addAllocNode(
1716 CallInfo
Call,
const FuncTy *
F) {
1718 ContextNode *AllocNode = createNewNode(
true,
F,
Call);
1719 AllocationCallToContextNodeMap[
Call] = AllocNode;
1721 AllocNode->OrigStackOrAllocId = LastContextId;
1724 AllocNode->AllocTypes = (uint8_t)AllocationType::None;
1740template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1741template <
class NodeT,
class IteratorT>
1742void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addStackNodesForMIB(
1743 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
1746 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold) {
1752 ContextIdToAllocationType[++LastContextId] =
AllocType;
1754 bool IsImportant =
false;
1755 if (!ContextSizeInfo.
empty()) {
1756 auto &
Entry = ContextIdToContextSizeInfos[LastContextId];
1761 for (
auto &CSI : ContextSizeInfo)
1762 TotalCold += CSI.TotalSize;
1768 TotalCold > TotalSizeToContextIdTopNCold.begin()->first) {
1771 auto IdToRemove = TotalSizeToContextIdTopNCold.begin()->second;
1772 TotalSizeToContextIdTopNCold.erase(
1773 TotalSizeToContextIdTopNCold.begin());
1775 ImportantContextIdInfo.
erase(IdToRemove);
1777 TotalSizeToContextIdTopNCold[TotalCold] = LastContextId;
1781 Entry.insert(
Entry.begin(), ContextSizeInfo.begin(), ContextSizeInfo.end());
1785 AllocNode->AllocTypes |= (uint8_t)
AllocType;
1790 ContextNode *PrevNode = AllocNode;
1794 SmallSet<uint64_t, 8> StackIdSet;
1797 ContextIter != StackContext.
end(); ++ContextIter) {
1798 auto StackId = getStackId(*ContextIter);
1800 ImportantContextIdInfo[LastContextId].StackIds.push_back(StackId);
1801 ContextNode *StackNode = getNodeForStackId(StackId);
1803 StackNode = createNewNode(
false);
1804 StackEntryIdToContextNodeMap[StackId] = StackNode;
1805 StackNode->OrigStackOrAllocId = StackId;
1810 auto Ins = StackIdSet.
insert(StackId);
1812 StackNode->Recursive =
true;
1814 StackNode->AllocTypes |= (uint8_t)
AllocType;
1815 PrevNode->addOrUpdateCallerEdge(StackNode,
AllocType, LastContextId);
1816 PrevNode = StackNode;
1820template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1822CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::duplicateContextIds(
1823 const DenseSet<uint32_t> &StackSequenceContextIds,
1824 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds,
1825 function_ref<
void(uint32_t OldId, uint32_t NewId)> OnDuplicate) {
1826 DenseSet<uint32_t> NewContextIds;
1827 NewContextIds.
reserve(StackSequenceContextIds.
size());
1828 for (
auto OldId : StackSequenceContextIds) {
1829 NewContextIds.
insert(++LastContextId);
1830 OldToNewContextIds[OldId].insert(LastContextId);
1832 OnDuplicate(OldId, LastContextId);
1835 ContextIdToAllocationType[LastContextId] = ContextIdToAllocationType[OldId];
1836 auto CSI = ContextIdToContextSizeInfos.
find(OldId);
1837 if (CSI != ContextIdToContextSizeInfos.
end())
1838 ContextIdToContextSizeInfos[LastContextId] = CSI->second;
1839 if (DotAllocContextIds.
contains(OldId))
1840 DotAllocContextIds.
insert(LastContextId);
1842 return NewContextIds;
1845template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1846void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1847 propagateDuplicateContextIds(
1848 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds) {
1850 auto GetNewIds = [&OldToNewContextIds](
const DenseSet<uint32_t> &ContextIds) {
1851 DenseSet<uint32_t> NewIds;
1852 for (
auto Id : ContextIds)
1853 if (
auto NewId = OldToNewContextIds.find(Id);
1854 NewId != OldToNewContextIds.end())
1860 auto UpdateCallers = [&](ContextNode *
Node,
1861 DenseSet<const ContextEdge *> &Visited,
1862 auto &&UpdateCallers) ->
void {
1863 for (
const auto &
Edge :
Node->CallerEdges) {
1867 ContextNode *NextNode =
Edge->Caller;
1868 DenseSet<uint32_t> NewIdsToAdd = GetNewIds(
Edge->getContextIds());
1871 if (!NewIdsToAdd.
empty()) {
1872 Edge->getContextIds().insert_range(NewIdsToAdd);
1873 UpdateCallers(NextNode, Visited, UpdateCallers);
1878 DenseSet<const ContextEdge *> Visited;
1879 for (
auto &Entry : AllocationCallToContextNodeMap) {
1881 UpdateCallers(Node, Visited, UpdateCallers);
1885template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1886void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::connectNewNode(
1887 ContextNode *NewNode, ContextNode *OrigNode,
bool TowardsCallee,
1888 const DenseSet<uint32_t> &ContextIds) {
1890 TowardsCallee ? OrigNode->CalleeEdges : OrigNode->CallerEdges;
1892 for (
auto EI = OrigEdges.begin(); EI != OrigEdges.end();) {
1894 DenseSet<uint32_t> NewEdgeContextIds;
1899 if (NewEdgeContextIds.
empty()) {
1903 if (TowardsCallee) {
1904 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1905 auto NewEdge = std::make_shared<ContextEdge>(
1906 Edge->Callee, NewNode, NewAllocType, std::move(NewEdgeContextIds));
1907 NewNode->CalleeEdges.push_back(NewEdge);
1908 NewEdge->Callee->CallerEdges.push_back(NewEdge);
1910 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1911 auto NewEdge = std::make_shared<ContextEdge>(
1912 NewNode,
Edge->Caller, NewAllocType, std::move(NewEdgeContextIds));
1913 NewNode->CallerEdges.push_back(NewEdge);
1914 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
1918 if (
Edge->getContextIds().empty()) {
1919 removeEdgeFromGraph(
Edge.get(), &EI, TowardsCallee);
1922 Edge->AllocTypes = computeAllocType(
Edge->getContextIds());
1927template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1929 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &Edge) {
1933 assert(!Edge->ContextIds.empty());
1936template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1938 bool CheckEdges =
true) {
1939 if (
Node->isRemoved())
1943 auto NodeContextIds =
Node->getContextIds();
1947 if (
Node->CallerEdges.size()) {
1949 Node->CallerEdges.front()->ContextIds);
1953 set_union(CallerEdgeContextIds, Edge->ContextIds);
1960 NodeContextIds == CallerEdgeContextIds ||
1963 if (
Node->CalleeEdges.size()) {
1965 Node->CalleeEdges.front()->ContextIds);
1969 set_union(CalleeEdgeContextIds, Edge->getContextIds());
1975 NodeContextIds == CalleeEdgeContextIds);
1984 for (
const auto &
E :
Node->CalleeEdges)
1990template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1991void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1992 assignStackNodesPostOrder(ContextNode *Node,
1993 DenseSet<const ContextNode *> &Visited,
1994 DenseMap<
uint64_t, std::vector<CallContextInfo>>
1995 &StackIdToMatchingCalls,
1996 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
1997 const DenseSet<uint32_t> &ImportantContextIds) {
2005 auto CallerEdges =
Node->CallerEdges;
2006 for (
auto &
Edge : CallerEdges) {
2008 if (
Edge->isRemoved()) {
2012 assignStackNodesPostOrder(
Edge->Caller, Visited, StackIdToMatchingCalls,
2013 CallToMatchingCall, ImportantContextIds);
2022 if (
Node->IsAllocation ||
2023 !StackIdToMatchingCalls.count(
Node->OrigStackOrAllocId))
2026 auto &Calls = StackIdToMatchingCalls[
Node->OrigStackOrAllocId];
2030 if (Calls.size() == 1) {
2031 auto &[
Call, StackNodes,
Func, SavedContextIds, TrimmedInlinedDupIds] =
2033 if (StackNodes.size() == 1) {
2034 assert(SavedContextIds.empty());
2036 assert(TrimmedInlinedDupIds.empty());
2038 assert(Node == StackNodes[0]);
2039 if (
Node->Recursive)
2042 NonAllocationCallToContextNodeMap[
Call] =
Node;
2044 recordStackNode(StackNodes, Node,
Node->getContextIds(),
2045 ImportantContextIds);
2054 ContextNode *LastNode = getNodeForStackId(LastId);
2057 assert(LastNode == Node);
2059 ContextNode *LastNode =
Node;
2064 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
2066 [[maybe_unused]]
bool PrevIterCreatedNode =
false;
2067 bool CreatedNode =
false;
2068 for (
unsigned I = 0;
I < Calls.size();
2069 I++, PrevIterCreatedNode = CreatedNode) {
2070 CreatedNode =
false;
2071 auto &[
Call, StackNodes,
Func, SavedContextIds, TrimmedInlinedDupIds] =
2075 if (SavedContextIds.empty() && TrimmedInlinedDupIds.empty()) {
2082 auto MatchingCall = CallToMatchingCall[
Call];
2083 if (!NonAllocationCallToContextNodeMap.contains(MatchingCall)) {
2087 assert(
I > 0 && !PrevIterCreatedNode);
2090 NonAllocationCallToContextNodeMap[MatchingCall]->MatchingCalls.push_back(
2095 assert(LastNode == StackNodes.back());
2104 ContextNode *PrevNode = LastNode;
2105 bool Skip = SavedContextIds.empty();
2108 for (
auto NodeIter = StackNodes.rbegin() + 1;
2109 !Skip && NodeIter != StackNodes.rend(); NodeIter++) {
2110 ContextNode *CurNode = *NodeIter;
2114 assert(!CurNode->Recursive);
2116 auto *
Edge = CurNode->findEdgeFromCaller(PrevNode);
2128 if (SavedContextIds.empty()) {
2134 SavedContextIds.clear();
2141 if (!TrimmedInlinedDupIds.empty()) {
2142 StackNodes[0]->removeContextIdsNotPresent(TrimmedInlinedDupIds);
2143 SavedContextIds.insert_range(TrimmedInlinedDupIds);
2145 if (SavedContextIds.empty())
2149 ContextNode *NewNode = createNewNode(
false, Func,
Call);
2150 NonAllocationCallToContextNodeMap[
Call] = NewNode;
2152 NewNode->AllocTypes = computeAllocType(SavedContextIds);
2154 ContextNode *FirstNode = StackNodes[0];
2160 connectNewNode(NewNode, FirstNode,
true, SavedContextIds);
2165 connectNewNode(NewNode, LastNode,
false, SavedContextIds);
2170 for (ContextNode *CurNode : StackNodes) {
2177 auto *PrevEdge = CurNode->findEdgeFromCallee(PrevNode);
2184 set_subtract(PrevEdge->getContextIds(), SavedContextIds);
2185 if (PrevEdge->getContextIds().empty())
2186 removeEdgeFromGraph(PrevEdge);
2188 PrevEdge->AllocTypes = computeAllocType(PrevEdge->getContextIds());
2193 CurNode->AllocTypes = CurNode->CalleeEdges.empty()
2194 ? (uint8_t)AllocationType::None
2195 : CurNode->computeAllocType();
2199 recordStackNode(StackNodes, NewNode, SavedContextIds, ImportantContextIds);
2203 for (ContextNode *CurNode : StackNodes) {
2212template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2213void CallsiteContextGraph<DerivedCCG, FuncTy,
2214 CallTy>::fixupImportantContexts() {
2215 if (ImportantContextIdInfo.
empty())
2219 NumImportantContextIds = ImportantContextIdInfo.
size();
2225 exportToDot(
"beforestackfixup");
2250 for (
auto &[CurContextId, Info] : ImportantContextIdInfo) {
2251 if (
Info.StackIdsToNode.empty())
2254 ContextNode *PrevNode =
nullptr;
2255 ContextNode *CurNode =
nullptr;
2256 DenseSet<const ContextEdge *> VisitedEdges;
2257 ArrayRef<uint64_t> AllStackIds(
Info.StackIds);
2260 for (
unsigned I = 0;
I < AllStackIds.size();
I++, PrevNode = CurNode) {
2264 auto LenToEnd = AllStackIds.size() -
I;
2272 auto CheckStackIds = AllStackIds.slice(
I, Len);
2273 auto EntryIt =
Info.StackIdsToNode.find(CheckStackIds);
2274 if (EntryIt ==
Info.StackIdsToNode.end())
2276 CurNode = EntryIt->second;
2293 auto *CurEdge = PrevNode->findEdgeFromCaller(CurNode);
2296 if (CurEdge->getContextIds().insert(CurContextId).second) {
2297 NumFixupEdgeIdsInserted++;
2302 NumFixupEdgesAdded++;
2303 DenseSet<uint32_t> ContextIds({CurContextId});
2304 auto AllocType = computeAllocType(ContextIds);
2305 auto NewEdge = std::make_shared<ContextEdge>(
2306 PrevNode, CurNode,
AllocType, std::move(ContextIds));
2307 PrevNode->CallerEdges.push_back(NewEdge);
2308 CurNode->CalleeEdges.push_back(NewEdge);
2310 CurEdge = NewEdge.get();
2313 VisitedEdges.
insert(CurEdge);
2316 for (
auto &
Edge : PrevNode->CallerEdges) {
2320 Edge->getContextIds().erase(CurContextId);
2338template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2339DenseSet<uint32_t> CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
2341 TrimmedAtNodeCache &Cache) {
2343 DenseSet<uint32_t>
Result;
2348 auto GetTrimmedAtNodeIndex = [&Cache](
const ContextNode *
Node) {
2350 Cache.NodeToIndex.try_emplace(Node, Cache.TrimmedAtNodeIds.size());
2351 unsigned Index = It->second;
2356 DenseSet<uint32_t> &Trimmed = Cache.TrimmedAtNodeIds.emplace_back();
2357 for (
const auto &CalleeEdge :
Node->CalleeEdges)
2359 for (
const auto &CallerEdge :
Node->CallerEdges) {
2361 if (Trimmed.
empty())
2369 SmallVector<unsigned, 8> TrimmedAtNodeIdsIndices;
2370 bool AnyTrimmed =
false;
2371 for (ContextNode *Node : StackNodes.
drop_back()) {
2373 if (
Node->Recursive)
2375 unsigned Index = GetTrimmedAtNodeIndex(Node);
2376 AnyTrimmed |= !Cache.TrimmedAtNodeIds[
Index].empty();
2377 TrimmedAtNodeIdsIndices.
push_back(Index);
2396 Result = Cache.TrimmedAtNodeIds[TrimmedAtNodeIdsIndices[0]];
2397 DenseSet<uint32_t> PrefixContextIds;
2398 for (
unsigned I = 1;
I < TrimmedAtNodeIdsIndices.
size();
I++) {
2399 auto *
Edge = StackNodes[
I]->findEdgeFromCallee(StackNodes[
I - 1]);
2403 PrefixContextIds =
Edge->getContextIds();
2406 if (PrefixContextIds.
empty())
2409 PrefixContextIds, Cache.TrimmedAtNodeIds[TrimmedAtNodeIdsIndices[
I]]));
2414template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2415void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::updateStackNodes() {
2423 DenseMap<uint64_t, std::vector<CallContextInfo>> StackIdToMatchingCalls;
2424 for (
auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
2425 for (
auto &
Call : CallsWithMetadata) {
2427 if (AllocationCallToContextNodeMap.count(
Call))
2429 std::vector<ContextNode *> StackNodes = getStackNodesForCall(
Call.call());
2432 if (StackNodes.empty())
2436 uint64_t LastId = StackNodes.back()->OrigStackOrAllocId;
2437 StackIdToMatchingCalls[LastId].push_back(
2438 {
Call.call(), std::move(StackNodes),
Func, {}, {}});
2454 return std::lexicographical_compare(
2455 A.begin(),
A.end(),
B.begin(),
B.end(),
2456 [](
const ContextNode *
X,
const ContextNode *
Y) {
2457 return X->OrigStackOrAllocId < Y->OrigStackOrAllocId;
2463 DenseMap<CallInfo, CallInfo> CallToMatchingCall;
2464 for (
auto &Entry : StackIdToMatchingCalls) {
2465 auto &Calls =
Entry.second;
2466 if (Calls.size() == 1)
2468 DenseMap<const FuncTy *, unsigned> FuncToIndex;
2469 for (
const auto &[Idx, CallCtxInfo] :
enumerate(Calls))
2470 FuncToIndex.
insert({CallCtxInfo.Func,
Idx});
2471 auto CallLess = [&FuncToIndex, &StackIdsLess](
const CallContextInfo &
A,
2472 const CallContextInfo &
B) {
2473 return A.StackNodes.size() >
B.StackNodes.size() ||
2474 (
A.StackNodes.size() ==
B.StackNodes.size() &&
2475 (StackIdsLess(
A.StackNodes,
B.StackNodes) ||
2476 (
A.StackNodes ==
B.StackNodes &&
2477 FuncToIndex[
A.Func] < FuncToIndex[
B.Func])));
2484 unsigned FirstInRun = 0;
2485 for (
unsigned I = 1;
I < Calls.size();
I++) {
2486 if (Calls[
I].Func != Calls[FirstInRun].Func ||
2487 Calls[
I].StackNodes != Calls[FirstInRun].StackNodes) {
2491 CallToMatchingCall[Calls[
I].Call] = Calls[FirstInRun].Call;
2501 DenseMap<uint32_t, DenseSet<uint32_t>> OldToNewContextIds;
2517 std::vector<ArrayRef<ContextNode *>> TrimmedInlinedDupCreatorNodes;
2520 DenseMap<uint32_t, SmallVector<std::pair<uint32_t, unsigned>, 1>>
2521 OrigToTrimmedInlinedDups;
2523 TrimmedAtNodeCache Cache;
2524 for (
auto &Entry : StackIdToMatchingCalls) {
2525 auto &Calls =
Entry.second;
2528 if (Calls[0].StackNodes.back()->Recursive)
2530 for (
unsigned I = 0;
I < Calls.size();
I++) {
2531 auto &CallCtxInfo = Calls[
I];
2532 auto &StackNodes = CallCtxInfo.StackNodes;
2535 if (StackNodes.size() < 2)
2539 if (CallToMatchingCall.
contains(CallCtxInfo.Call))
2541 auto Trimmed = computeTrimmedInlinedContextIds(StackNodes, Cache);
2542 if (Trimmed.
empty())
2544 unsigned CreatorIdx = TrimmedInlinedDupCreatorNodes.size();
2545 TrimmedInlinedDupCreatorNodes.push_back(StackNodes);
2546 CallCtxInfo.TrimmedInlinedDupIds = duplicateContextIds(
2547 Trimmed, OldToNewContextIds, [&](uint32_t OldId, uint32_t NewId) {
2548 OrigToTrimmedInlinedDups[OldId].push_back({NewId, CreatorIdx});
2550 NumCallsAssignedTrimmedInlinedContexts++;
2551 NumTrimmedInlinedContextIds += Trimmed.
size();
2570 auto AddTrimmedInlinedDups = [&](DenseSet<uint32_t> &SavedContextIds,
2571 const ContextNode *LastNode) {
2572 SmallVector<uint32_t> DupIdsToAdd;
2575 for (
auto [DupId, CreatorIdx] : Dups) {
2577 TrimmedInlinedDupCreatorNodes[CreatorIdx];
2592 if (OrigToTrimmedInlinedDups.
size() < SavedContextIds.
size()) {
2593 for (
auto &[OrigId, Dups] : OrigToTrimmedInlinedDups)
2594 if (SavedContextIds.
contains(OrigId))
2597 for (
auto Id : SavedContextIds) {
2598 auto It = OrigToTrimmedInlinedDups.find(Id);
2599 if (It != OrigToTrimmedInlinedDups.end())
2600 AddDups(It->second);
2603 SavedContextIds.insert_range(DupIdsToAdd);
2605 for (
auto &It : StackIdToMatchingCalls) {
2606 auto &Calls = It.getSecond();
2608 if (Calls.size() == 1) {
2609 auto &StackNodes = Calls[0].StackNodes;
2610 if (StackNodes.size() == 1)
2619 ContextNode *LastNode = Calls[0].StackNodes.back();
2622 assert(LastNode == getNodeForStackId(LastId));
2624 if (LastNode->Recursive)
2629 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
2637 DenseSet<const FuncTy *> MatchingIdsFuncSet;
2640 for (
unsigned I = 0;
I < Calls.size();
I++) {
2641 auto &[
Call, StackNodes,
Func, SavedContextIds, TrimmedInlinedDupIds] =
2643 assert(SavedContextIds.empty());
2644 assert(LastNode == StackNodes.back());
2649 if (
I > 0 && StackNodes != Calls[
I - 1].StackNodes)
2650 MatchingIdsFuncSet.
clear();
2657 bool DuplicateContextIds =
false;
2658 for (
unsigned J =
I + 1; J < Calls.size(); J++) {
2659 auto &CallCtxInfo = Calls[J];
2660 if (CallCtxInfo.StackNodes != StackNodes)
2662 auto *NextFunc = CallCtxInfo.Func;
2663 if (NextFunc != Func) {
2666 DuplicateContextIds =
true;
2678 DenseSet<uint32_t> StackSequenceContextIds = LastNodeContextIds;
2680 ContextNode *PrevNode = LastNode;
2681 ContextNode *CurNode = LastNode;
2686 for (
auto NodeIter = StackNodes.rbegin() + 1;
2687 NodeIter != StackNodes.rend(); NodeIter++) {
2688 CurNode = *NodeIter;
2692 if (CurNode->Recursive) {
2697 auto *
Edge = CurNode->findEdgeFromCaller(PrevNode);
2718 if (StackSequenceContextIds.
empty()) {
2731 if (LastId != getLastStackId(
Call)) {
2732 for (
const auto &PE : LastNode->CallerEdges) {
2733 set_subtract(StackSequenceContextIds, PE->getContextIds());
2734 if (StackSequenceContextIds.
empty())
2738 if (StackSequenceContextIds.
empty())
2750 MatchingIdsFuncSet.
insert(Func);
2759 OldToNewContextIds.
reserve(OldToNewContextIds.
size() +
2760 StackSequenceContextIds.
size());
2763 ? duplicateContextIds(StackSequenceContextIds, OldToNewContextIds)
2764 : StackSequenceContextIds;
2765 assert(!SavedContextIds.empty());
2766 if (!OrigToTrimmedInlinedDups.empty())
2767 AddTrimmedInlinedDups(SavedContextIds, LastNode);
2769 if (!DuplicateContextIds) {
2773 set_subtract(LastNodeContextIds, StackSequenceContextIds);
2774 if (LastNodeContextIds.
empty())
2781 propagateDuplicateContextIds(OldToNewContextIds);
2791 DenseSet<const ContextNode *> Visited;
2793 ImportantContextIdInfo.keys());
2794 for (
auto &Entry : AllocationCallToContextNodeMap)
2795 assignStackNodesPostOrder(
Entry.second, Visited, StackIdToMatchingCalls,
2796 CallToMatchingCall, ImportantContextIds);
2798 fixupImportantContexts();
2804uint64_t ModuleCallsiteContextGraph::getLastStackId(Instruction *
Call) {
2805 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2807 return CallsiteContext.
back();
2810uint64_t IndexCallsiteContextGraph::getLastStackId(IndexCall &
Call) {
2812 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2815 return Index.getStackIdAtIndex(CallsiteContext.
back());
2831 auto Pos =
F.getName().find_last_of(
'.');
2834 bool Err =
F.getName().drop_front(Pos + 1).getAsInteger(10, CloneNo);
2840std::string ModuleCallsiteContextGraph::getLabel(
const Function *Func,
2841 const Instruction *
Call,
2842 unsigned CloneNo)
const {
2848std::string IndexCallsiteContextGraph::getLabel(
const FunctionSummary *Func,
2849 const IndexCall &
Call,
2850 unsigned CloneNo)
const {
2851 auto VI = FSToVIMap.find(Func);
2852 assert(VI != FSToVIMap.end());
2855 return CallerName +
" -> alloc";
2858 return CallerName +
" -> " +
2860 Callsite->Clones[CloneNo]);
2864std::string ModuleCallsiteContextGraph::getFuncName(
const Function *Func,
2865 unsigned CloneNo)
const {
2871void ModuleCallsiteContextGraph::populateFunctionsWithCallers() {
2874 for (
const auto &
F :
Mod)
2876 FunctionsWithCallers.
insert(&
F);
2879std::string IndexCallsiteContextGraph::getFuncName(
const FunctionSummary *Func,
2880 unsigned CloneNo)
const {
2883 auto VI = FSToVIMap.find(Func);
2884 if (VI != FSToVIMap.end()) {
2885 if (!
VI->second.name().empty())
2893bool IndexCallsiteContextGraph::isFuncDead(
const FunctionSummary *Func)
const {
2894 return Index.withGlobalValueDeadStripping() &&
Func && !
Func->isLive();
2897void IndexCallsiteContextGraph::populateFunctionsWithCallers() {
2898 for (
const auto &
I : Index) {
2900 for (
const auto &S :
VI.getSummaryList()) {
2902 !isPrevailing(
VI.getGUID(), S.get()))
2904 if (
Index.withGlobalValueDeadStripping() && !S->isLive())
2906 auto AddReferenced = [&](ValueInfo RefVI) {
2907 for (
const auto &RefS : RefVI.getSummaryList()) {
2908 const GlobalValueSummary *
Base = RefS->getBaseObject();
2910 FunctionsWithCallers.
insert(RefFS);
2914 for (
const auto &RefVI : S->refs())
2915 AddReferenced(RefVI);
2918 for (
const auto &CallEdge :
FS->calls())
2919 AddReferenced(CallEdge.first);
2924std::vector<ModuleCallsiteContextGraph::ContextNode *>
2925ModuleCallsiteContextGraph::getStackNodesForCall(Instruction *
Call) {
2926 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2928 return getStackNodesForCallsite<MDNode, MDNode::op_iterator>(CallsiteContext);
2931std::vector<IndexCallsiteContextGraph::ContextNode *>
2932IndexCallsiteContextGraph::getStackNodesForCall(IndexCall &
Call) {
2934 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2936 return getStackNodesForCallsite<CallsiteInfo,
2937 SmallVector<unsigned>::const_iterator>(
2941template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2942template <
class NodeT,
class IteratorT>
2944 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *>
2945CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getStackNodesForCallsite(
2946 CallStack<NodeT, IteratorT> &CallsiteContext) {
2947 std::vector<ContextNode *> StackNodes;
2948 for (
auto IdOrIndex : CallsiteContext) {
2949 auto StackId = getStackId(IdOrIndex);
2950 ContextNode *
Node = getNodeForStackId(StackId);
2953 StackNodes.push_back(Node);
2958ModuleCallsiteContextGraph::ModuleCallsiteContextGraph(
2960 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter)
2961 :
Mod(
M), OREGetter(OREGetter) {
2965 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2967 std::vector<CallInfo> CallsWithMetadata;
2968 for (
auto &BB :
F) {
2969 for (
auto &
I : BB) {
2972 if (
auto *MemProfMD =
I.getMetadata(LLVMContext::MD_memprof)) {
2973 CallsWithMetadata.push_back(&
I);
2974 auto *AllocNode = addAllocNode(&
I, &
F);
2975 auto *CallsiteMD =
I.getMetadata(LLVMContext::MD_callsite);
2979 for (
auto &MDOp : MemProfMD->operands()) {
2981 std::vector<ContextTotalSize> ContextSizeInfo;
2983 if (MIBMD->getNumOperands() > 2) {
2984 for (
unsigned I = 2;
I < MIBMD->getNumOperands();
I++) {
2985 MDNode *ContextSizePair =
2994 ContextSizeInfo.push_back({FullStackId, TotalSize});
3000 addStackNodesForMIB<MDNode, MDNode::op_iterator>(
3001 AllocNode, StackContext, CallsiteContext,
3003 TotalSizeToContextIdTopNCold);
3008 DotAllocContextIds = AllocNode->getContextIds();
3012 I.setMetadata(LLVMContext::MD_memprof,
nullptr);
3013 I.setMetadata(LLVMContext::MD_callsite,
nullptr);
3016 else if (
I.getMetadata(LLVMContext::MD_callsite)) {
3017 CallsWithMetadata.push_back(&
I);
3021 if (!CallsWithMetadata.empty())
3022 FuncToCallsWithMetadata[&
F] = CallsWithMetadata;
3026 dbgs() <<
"CCG before updating call stack chains:\n";
3031 exportToDot(
"prestackupdate");
3036 exportToDot(
"poststackupdate");
3038 handleCallsitesWithMultipleTargets();
3043 for (
auto &FuncEntry : FuncToCallsWithMetadata)
3044 for (
auto &
Call : FuncEntry.second)
3045 Call.call()->setMetadata(LLVMContext::MD_callsite,
nullptr);
3051IndexCallsiteContextGraph::findAliaseeGUIDsPrevailingInDifferentModule() {
3052 DenseSet<GlobalValue::GUID> AliaseeGUIDs;
3053 for (
auto &
I : Index) {
3055 for (
auto &S :
VI.getSummaryList()) {
3060 auto *AliaseeSummary = &AS->getAliasee();
3068 !isPrevailing(
VI.getGUID(), S.get()))
3073 auto AliaseeGUID = AS->getAliaseeGUID();
3075 if (!isPrevailing(AliaseeGUID, AliaseeSummary))
3076 AliaseeGUIDs.
insert(AliaseeGUID);
3079 AliaseesPrevailingInDiffModuleFromAlias += AliaseeGUIDs.
size();
3080 return AliaseeGUIDs;
3083IndexCallsiteContextGraph::IndexCallsiteContextGraph(
3084 ModuleSummaryIndex &Index,
3094 findAliaseeGUIDsPrevailingInDifferentModule();
3098 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
3103 for (
const auto &
I : Index.sortedGlobalValueSummariesRange()) {
3104 auto VI = Index.getValueInfo(
I);
3105 if (GUIDsToSkip.
contains(VI.getGUID()))
3107 for (
auto &S : VI.getSummaryList()) {
3116 !isPrevailing(VI.getGUID(), S.get()))
3121 std::vector<CallInfo> CallsWithMetadata;
3122 if (!
FS->allocs().empty()) {
3123 for (
auto &AN :
FS->mutableAllocs()) {
3128 if (AN.MIBs.empty())
3130 IndexCall AllocCall(&AN);
3131 CallsWithMetadata.push_back(AllocCall);
3132 auto *AllocNode = addAllocNode(AllocCall, FS);
3140 AN.ContextSizeInfos.size() == AN.MIBs.size());
3142 for (
auto &MIB : AN.MIBs) {
3145 std::vector<ContextTotalSize> ContextSizeInfo;
3146 if (!AN.ContextSizeInfos.empty()) {
3147 for (
auto [FullStackId, TotalSize] : AN.ContextSizeInfos[
I])
3148 ContextSizeInfo.push_back({FullStackId, TotalSize});
3150 addStackNodesForMIB<MIBInfo, SmallVector<unsigned>::const_iterator>(
3151 AllocNode, StackContext, EmptyContext, MIB.AllocType,
3152 ContextSizeInfo, TotalSizeToContextIdTopNCold);
3158 DotAllocContextIds = AllocNode->getContextIds();
3164 AN.Versions[0] = (
uint8_t)allocTypeToUse(AllocNode->AllocTypes);
3168 if (!
FS->callsites().empty())
3169 for (
auto &SN :
FS->mutableCallsites()) {
3170 IndexCall StackNodeCall(&SN);
3171 CallsWithMetadata.push_back(StackNodeCall);
3174 if (!CallsWithMetadata.empty())
3175 FuncToCallsWithMetadata[
FS] = CallsWithMetadata;
3177 if (!
FS->allocs().empty() || !
FS->callsites().empty())
3183 dbgs() <<
"CCG before updating call stack chains:\n";
3188 exportToDot(
"prestackupdate");
3193 exportToDot(
"poststackupdate");
3195 handleCallsitesWithMultipleTargets();
3200template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3201void CallsiteContextGraph<DerivedCCG, FuncTy,
3202 CallTy>::handleCallsitesWithMultipleTargets() {
3217 std::vector<std::pair<CallInfo, ContextNode *>> NewCallToNode;
3218 for (
auto &Entry : NonAllocationCallToContextNodeMap) {
3219 auto *
Node = Entry.second;
3228 std::vector<CallInfo> AllCalls;
3229 AllCalls.reserve(
Node->MatchingCalls.size() + 1);
3230 AllCalls.push_back(
Node->Call);
3244 if (partitionCallsByCallee(
Node, AllCalls, NewCallToNode))
3247 auto It = AllCalls.begin();
3249 for (; It != AllCalls.end(); ++It) {
3252 for (
auto EI =
Node->CalleeEdges.begin(); EI !=
Node->CalleeEdges.end();
3255 if (!Edge->Callee->hasCall())
3257 assert(NodeToCallingFunc.count(Edge->Callee));
3259 if (!calleesMatch(
ThisCall.call(), EI, TailCallToContextNodeMap)) {
3268 if (
Node->Call != ThisCall) {
3269 Node->setCall(ThisCall);
3280 Node->MatchingCalls.clear();
3283 if (It == AllCalls.end()) {
3284 RemovedEdgesWithMismatchedCallees++;
3288 Node->setCall(CallInfo());
3293 for (++It; It != AllCalls.end(); ++It) {
3297 Node->MatchingCalls.push_back(ThisCall);
3306 NonAllocationCallToContextNodeMap.remove_if([](
const auto &it) {
3307 return !it.second->hasCall() || it.second->Call != it.first;
3311 for (
auto &[
Call,
Node] : NewCallToNode)
3312 NonAllocationCallToContextNodeMap[
Call] =
Node;
3316 for (
auto &[
Call,
Node] : TailCallToContextNodeMap)
3317 NonAllocationCallToContextNodeMap[
Call] =
Node;
3320template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3321bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::partitionCallsByCallee(
3323 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode) {
3327 struct CallsWithSameCallee {
3328 std::vector<CallInfo> Calls;
3329 ContextNode *
Node =
nullptr;
3335 for (
auto ThisCall : AllCalls) {
3336 auto *
F = getCalleeFunc(
ThisCall.call());
3338 CalleeFuncToCallInfo[
F].Calls.push_back(ThisCall);
3347 for (
const auto &Edge :
Node->CalleeEdges) {
3348 if (!Edge->Callee->hasCall())
3350 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[Edge->Callee];
3351 if (CalleeFuncToCallInfo.
contains(ProfiledCalleeFunc))
3352 CalleeNodeToCallInfo[Edge->Callee] =
3353 &CalleeFuncToCallInfo[ProfiledCalleeFunc];
3359 if (CalleeNodeToCallInfo.
empty())
3371 ContextNode *UnmatchedCalleesNode =
nullptr;
3373 bool UsedOrigNode =
false;
3378 auto CalleeEdges =
Node->CalleeEdges;
3379 for (
auto &Edge : CalleeEdges) {
3380 if (!Edge->Callee->hasCall())
3385 ContextNode *CallerNodeToUse =
nullptr;
3389 if (!CalleeNodeToCallInfo.
contains(Edge->Callee)) {
3390 if (!UnmatchedCalleesNode)
3391 UnmatchedCalleesNode =
3392 createNewNode(
false, NodeToCallingFunc[
Node]);
3393 CallerNodeToUse = UnmatchedCalleesNode;
3397 auto *Info = CalleeNodeToCallInfo[Edge->Callee];
3400 if (!UsedOrigNode) {
3403 Node->MatchingCalls.clear();
3404 UsedOrigNode =
true;
3407 createNewNode(
false, NodeToCallingFunc[
Node]);
3408 assert(!Info->Calls.empty());
3411 Info->Node->setCall(Info->Calls.front());
3417 NewCallToNode.push_back({Info->Node->Call, Info->Node});
3419 CallerNodeToUse = Info->Node;
3423 if (CallerNodeToUse ==
Node)
3426 moveCalleeEdgeToNewCaller(Edge, CallerNodeToUse);
3433 for (
auto &
I : CalleeNodeToCallInfo)
3434 removeNoneTypeCallerEdges(
I.second->Node);
3435 if (UnmatchedCalleesNode)
3436 removeNoneTypeCallerEdges(UnmatchedCalleesNode);
3437 removeNoneTypeCallerEdges(
Node);
3450 return Index.getStackIdAtIndex(IdOrIndex);
3453template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3454bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::calleesMatch(
3455 CallTy
Call, EdgeIter &EI,
3456 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap) {
3458 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[
Edge->Callee];
3459 const FuncTy *CallerFunc = NodeToCallingFunc[
Edge->Caller];
3462 std::vector<std::pair<CallTy, FuncTy *>> FoundCalleeChain;
3463 if (!calleeMatchesFunc(
Call, ProfiledCalleeFunc, CallerFunc,
3468 if (FoundCalleeChain.empty())
3472 auto *CurEdge =
Callee->findEdgeFromCaller(Caller);
3476 CurEdge->ContextIds.insert_range(
Edge->ContextIds);
3477 CurEdge->AllocTypes |=
Edge->AllocTypes;
3482 auto NewEdge = std::make_shared<ContextEdge>(
3483 Callee, Caller,
Edge->AllocTypes,
Edge->ContextIds);
3484 Callee->CallerEdges.push_back(NewEdge);
3485 if (Caller ==
Edge->Caller) {
3489 EI =
Caller->CalleeEdges.insert(EI, NewEdge);
3492 "Iterator position not restored after insert and increment");
3494 Caller->CalleeEdges.push_back(NewEdge);
3499 auto *CurCalleeNode =
Edge->Callee;
3500 for (
auto &[NewCall, Func] : FoundCalleeChain) {
3501 ContextNode *NewNode =
nullptr;
3503 if (TailCallToContextNodeMap.
count(NewCall)) {
3504 NewNode = TailCallToContextNodeMap[NewCall];
3505 NewNode->AllocTypes |=
Edge->AllocTypes;
3507 FuncToCallsWithMetadata[
Func].push_back({NewCall});
3509 NewNode = createNewNode(
false, Func, NewCall);
3510 TailCallToContextNodeMap[NewCall] = NewNode;
3511 NewNode->AllocTypes =
Edge->AllocTypes;
3515 AddEdge(NewNode, CurCalleeNode);
3517 CurCalleeNode = NewNode;
3521 AddEdge(
Edge->Caller, CurCalleeNode);
3529 removeEdgeFromGraph(
Edge.get(), &EI,
true);
3541bool ModuleCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3543 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
3544 bool &FoundMultipleCalleeChains) {
3551 FoundCalleeChain.push_back({Callsite,
F});
3566 bool FoundSingleCalleeChain =
false;
3567 for (
auto &BB : *CalleeFunc) {
3568 for (
auto &
I : BB) {
3570 if (!CB || !CB->isTailCall())
3572 auto *CalledValue = CB->getCalledOperand();
3573 auto *CalledFunction = CB->getCalledFunction();
3574 if (CalledValue && !CalledFunction) {
3575 CalledValue = CalledValue->stripPointerCasts();
3582 assert(!CalledFunction &&
3583 "Expected null called function in callsite for alias");
3586 if (!CalledFunction)
3588 if (CalledFunction == ProfiledCallee) {
3589 if (FoundSingleCalleeChain) {
3590 FoundMultipleCalleeChains =
true;
3593 FoundSingleCalleeChain =
true;
3594 FoundProfiledCalleeCount++;
3595 FoundProfiledCalleeDepth +=
Depth;
3596 if (
Depth > FoundProfiledCalleeMaxDepth)
3597 FoundProfiledCalleeMaxDepth =
Depth;
3598 SaveCallsiteInfo(&
I, CalleeFunc);
3599 }
else if (findProfiledCalleeThroughTailCalls(
3600 ProfiledCallee, CalledFunction,
Depth + 1,
3601 FoundCalleeChain, FoundMultipleCalleeChains)) {
3604 assert(!FoundMultipleCalleeChains);
3605 if (FoundSingleCalleeChain) {
3606 FoundMultipleCalleeChains =
true;
3609 FoundSingleCalleeChain =
true;
3610 SaveCallsiteInfo(&
I, CalleeFunc);
3611 }
else if (FoundMultipleCalleeChains)
3616 return FoundSingleCalleeChain;
3619const Function *ModuleCallsiteContextGraph::getCalleeFunc(Instruction *
Call) {
3621 if (!CB->getCalledOperand() || CB->isIndirectCall())
3623 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3630bool ModuleCallsiteContextGraph::calleeMatchesFunc(
3632 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain) {
3634 if (!CB->getCalledOperand() || CB->isIndirectCall())
3636 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3638 if (CalleeFunc == Func)
3641 if (Alias && Alias->getAliasee() == Func)
3652 bool FoundMultipleCalleeChains =
false;
3653 if (!findProfiledCalleeThroughTailCalls(Func, CalleeVal,
Depth,
3655 FoundMultipleCalleeChains)) {
3656 LLVM_DEBUG(
dbgs() <<
"Not found through unique tail call chain: "
3657 <<
Func->getName() <<
" from " << CallerFunc->
getName()
3658 <<
" that actually called " << CalleeVal->getName()
3659 << (FoundMultipleCalleeChains
3660 ?
" (found multiple possible chains)"
3663 if (FoundMultipleCalleeChains)
3664 FoundProfiledCalleeNonUniquelyCount++;
3671bool ModuleCallsiteContextGraph::sameCallee(Instruction *Call1,
3672 Instruction *Call2) {
3674 if (!CB1->getCalledOperand() || CB1->isIndirectCall())
3676 auto *CalleeVal1 = CB1->getCalledOperand()->stripPointerCasts();
3679 if (!CB2->getCalledOperand() || CB2->isIndirectCall())
3681 auto *CalleeVal2 = CB2->getCalledOperand()->stripPointerCasts();
3683 return CalleeFunc1 == CalleeFunc2;
3686bool IndexCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3687 ValueInfo ProfiledCallee, ValueInfo CurCallee,
unsigned Depth,
3688 std::vector<std::pair<ValueInfo, FunctionSummary *>> &FoundCalleeChain,
3689 bool &FoundMultipleCalleeChains) {
3699 auto SaveTailCall = [&](ValueInfo
Callee, FunctionSummary *
FS) {
3700 FoundCalleeChain.push_back({
Callee,
FS});
3707 bool FoundSingleCalleeChain =
false;
3710 !isPrevailing(CurCallee.
getGUID(), S.get()))
3715 auto FSVI = CurCallee;
3718 FSVI = AS->getAliaseeVI();
3719 for (
auto &CallEdge :
FS->calls()) {
3720 if (!CallEdge.second.hasTailCall())
3727 if (CallEdge.first == ProfiledCallee) {
3728 if (FoundSingleCalleeChain) {
3729 FoundMultipleCalleeChains =
true;
3732 FoundSingleCalleeChain =
true;
3733 FoundProfiledCalleeCount++;
3734 FoundProfiledCalleeDepth +=
Depth;
3735 if (
Depth > FoundProfiledCalleeMaxDepth)
3736 FoundProfiledCalleeMaxDepth =
Depth;
3737 if (CallEdge.second.hasIndirectCall())
3738 FoundProfiledCalleeIndirectTailCallCount++;
3739 SaveTailCall(CallEdge.first, FS);
3741 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3742 FSToVIMap[
FS] = FSVI;
3743 }
else if (findProfiledCalleeThroughTailCalls(
3744 ProfiledCallee, CallEdge.first,
Depth + 1,
3745 FoundCalleeChain, FoundMultipleCalleeChains)) {
3748 assert(!FoundMultipleCalleeChains);
3749 if (FoundSingleCalleeChain) {
3750 FoundMultipleCalleeChains =
true;
3753 FoundSingleCalleeChain =
true;
3754 if (CallEdge.second.hasIndirectCall())
3755 FoundProfiledCalleeIndirectTailCallCount++;
3756 SaveTailCall(CallEdge.first, FS);
3758 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3759 FSToVIMap[
FS] = FSVI;
3760 }
else if (FoundMultipleCalleeChains)
3765 return FoundSingleCalleeChain;
3768const FunctionSummary *
3769IndexCallsiteContextGraph::getCalleeFunc(IndexCall &
Call) {
3771 if (
Callee.getSummaryList().empty())
3776bool IndexCallsiteContextGraph::calleeMatchesFunc(
3777 IndexCall &
Call,
const FunctionSummary *Func,
3778 const FunctionSummary *CallerFunc,
3779 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain) {
3783 AliasSummary *Alias =
3784 Callee.getSummaryList().empty()
3787 assert(FSToVIMap.count(Func));
3788 auto FuncVI = FSToVIMap[
Func];
3789 if (Callee == FuncVI ||
3804 bool FoundMultipleCalleeChains =
false;
3805 std::vector<std::pair<ValueInfo, FunctionSummary *>> FoundCalleeVIChain;
3806 if (!findProfiledCalleeThroughTailCalls(FuncVI, Callee,
Depth,
3808 FoundMultipleCalleeChains)) {
3809 LLVM_DEBUG(
dbgs() <<
"Not found through unique tail call chain: " << FuncVI
3810 <<
" from " << FSToVIMap[CallerFunc]
3811 <<
" that actually called " << Callee
3812 << (FoundMultipleCalleeChains
3813 ?
" (found multiple possible chains)"
3816 if (FoundMultipleCalleeChains)
3817 FoundProfiledCalleeNonUniquelyCount++;
3826 for (
auto &[CalleeVI, FS] : FoundCalleeVIChain) {
3827 auto &CallsiteInfoPtr =
3828 FunctionCalleesToSynthesizedCallsiteInfos[
FS][CalleeVI];
3829 if (!CallsiteInfoPtr)
3833 std::make_unique<CallsiteInfo>(CalleeVI, SmallVector<unsigned>());
3834 FoundCalleeChain.push_back({CallsiteInfoPtr.get(),
FS});
3840bool IndexCallsiteContextGraph::sameCallee(IndexCall &Call1, IndexCall &Call2) {
3843 return Callee1 == Callee2;
3846template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3847void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::dump()
3853template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3854void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::print(
3855 raw_ostream &OS)
const {
3856 OS <<
"Node " <<
this <<
"\n";
3860 OS <<
" (recursive)";
3862 if (!MatchingCalls.
empty()) {
3863 OS <<
"\tMatchingCalls:\n";
3864 for (
auto &MatchingCall : MatchingCalls) {
3866 MatchingCall.print(OS);
3870 OS <<
"\tNodeId: " <<
NodeId <<
"\n";
3872 OS <<
"\tContextIds:";
3874 auto ContextIds = getContextIds();
3875 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
3876 std::sort(SortedIds.begin(), SortedIds.end());
3877 for (
auto Id : SortedIds)
3880 OS <<
"\tCalleeEdges:\n";
3881 for (
auto &
Edge : CalleeEdges)
3882 OS <<
"\t\t" << *
Edge <<
" (Callee NodeId: " <<
Edge->Callee->NodeId
3884 OS <<
"\tCallerEdges:\n";
3885 for (
auto &
Edge : CallerEdges)
3886 OS <<
"\t\t" << *
Edge <<
" (Caller NodeId: " <<
Edge->Caller->NodeId
3888 if (!Clones.empty()) {
3891 for (
auto *
C : Clones)
3892 OS <<
LS <<
C <<
" NodeId: " <<
C->NodeId;
3894 }
else if (CloneOf) {
3895 OS <<
"\tClone of " << CloneOf <<
" NodeId: " << CloneOf->NodeId <<
"\n";
3899template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3900void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::dump()
3906template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3907void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::print(
3908 raw_ostream &OS)
const {
3909 OS <<
"Edge from Callee " <<
Callee <<
" to Caller: " <<
Caller
3910 << (IsBackedge ?
" (BE)" :
"")
3912 OS <<
" ContextIds:";
3913 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
3914 std::sort(SortedIds.begin(), SortedIds.end());
3915 for (
auto Id : SortedIds)
3919template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3920void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::dump()
const {
3924template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3925void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::print(
3926 raw_ostream &OS)
const {
3927 OS <<
"Callsite Context Graph:\n";
3928 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3930 if (
Node->isRemoved())
3937template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3938void CallsiteContextGraph<DerivedCCG, FuncTy,
3939 CallTy>::capturePreCloningContextInfo() {
3940 for (
const auto &Entry : AllocationCallToContextNodeMap) {
3941 const ContextNode *AllocNode =
Entry.second;
3945 for (
const auto &
Edge : AllocNode->CallerEdges) {
3946 if (!
Edge->isRemoved() &&
Edge->Caller->hasCall()) {
3947 PreCloningAllocHasMatchedCaller.insert(AllocNode);
3951 DenseSet<uint32_t> ContextIds = AllocNode->getContextIds();
3952 for (uint32_t Id : ContextIds) {
3953 PreCloningContextInfo
Info;
3959 Info.Chain.push_back(AllocNode);
3960 SmallPtrSet<const ContextNode *, 16> Visited;
3961 Visited.
insert(AllocNode);
3962 const ContextNode *Cur = AllocNode;
3964 const ContextNode *
Next =
nullptr;
3965 for (
const auto &
Edge : Cur->CallerEdges) {
3966 if (
Edge->isRemoved() ||
Edge->IsBackedge)
3968 if (
Edge->getContextIds().contains(Id) &&
3975 for (
const auto &
Edge : Cur->CallerEdges) {
3976 if (
Edge->isRemoved())
3978 if (
Edge->getContextIds().contains(Id) &&
3995 Info.MaxMatchedFrame = 0;
3996 for (
unsigned I = 1;
I <
Info.Chain.size(); ++
I) {
3997 if (
Info.Chain[
I]->hasCall()) {
3998 Info.MaxMatchedFrame =
I;
4000 const ContextNode *Unmatched =
Info.Chain[
I];
4001 Info.UnmatchedStackId = Unmatched->OrigStackOrAllocId;
4002 Info.StoppedAtRecursive = Unmatched->Recursive;
4006 if (
auto It = NodeToCallingFunc.find(Unmatched);
4007 It != NodeToCallingFunc.end()) {
4008 Info.StoppedAtMismatchedCallee =
true;
4009 Info.UnmatchedCallingFunc = It->second;
4019 if (
Info.MaxMatchedFrame > 0 &&
4020 Info.MaxMatchedFrame + 1 ==
Info.Chain.size()) {
4021 const ContextNode *OutermostMatchedNode =
4023 for (
const auto &
Edge : OutermostMatchedNode->CallerEdges) {
4024 if (!
Edge->isRemoved() &&
Edge->Caller->hasCall()) {
4025 Info.OutermostMatchedNodeHasOtherCallers =
true;
4031 PreCloningContextInfoMap[
Id] = std::move(Info);
4036template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4038CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::formatContextReportSuffix(
4039 const ContextNode *Node, uint32_t Id)
const {
4040 auto InfoIt = PreCloningContextInfoMap.find(Id);
4041 if (InfoIt == PreCloningContextInfoMap.end())
4043 const PreCloningContextInfo &
Info = InfoIt->second;
4050 const ContextNode *OrigAlloc =
Node->getOrigNode();
4051 const FuncTy *AllocFunc = getCallingFunc(OrigAlloc);
4052 unsigned AllocCloneNo =
Node->Call.cloneNo();
4053 std::string AllocFuncStr = getFuncName(AllocFunc, AllocCloneNo);
4054 if (isFuncDead(AllocFunc)) {
4055 AllocFuncStr +=
" (dead)";
4056 }
else if (!PreCloningAllocHasMatchedCaller.contains(OrigAlloc) &&
4057 Info.Chain.size() > 1) {
4061 AllocFuncStr += AllocFunc && !FunctionsWithCallers.
contains(AllocFunc)
4062 ?
" (no references in IR/summary)"
4063 :
" (no matched callers)";
4069 unsigned TotalFrames =
Info.Chain.size() > 0 ?
Info.Chain.size() - 1 : 0;
4070 unsigned Matched =
Info.MaxMatchedFrame;
4071 std::string StatusStr;
4072 if (TotalFrames == 0) {
4073 StatusStr =
"inlined into leaf";
4074 }
else if (Matched < TotalFrames) {
4079 if (
Info.StoppedAtRecursive)
4080 StatusStr =
"unmatched recursive callsite";
4081 else if (
Info.StoppedAtMismatchedCallee)
4082 StatusStr =
"unmatched callsite (mismatched callee in " +
4083 getFuncName(
Info.UnmatchedCallingFunc, 0) +
")";
4085 StatusStr =
"unmatched callsite";
4086 StatusStr +=
" at frame " + std::to_string(Matched + 1) +
"/" +
4087 std::to_string(TotalFrames) +
" (stack id " +
4088 std::to_string(
Info.UnmatchedStackId) +
")";
4090 const ContextNode *OutermostMatchedNode =
Info.Chain[Matched];
4091 const FuncTy *OutermostMatchedFunc = getCallingFunc(OutermostMatchedNode);
4092 unsigned NumOutermostMatchedFuncClones =
4093 std::max<unsigned>(1, FuncToNumClones.lookup(OutermostMatchedFunc));
4094 bool HasCallersAbove =
4095 NumOutermostMatchedFuncClones > 1 ||
4096 Info.OutermostMatchedNodeHasOtherCallers ||
4097 (OutermostMatchedFunc &&
4098 FunctionsWithCallers.
contains(OutermostMatchedFunc));
4099 if (HasCallersAbove) {
4100 StatusStr =
"trimmed at frame " + std::to_string(Matched) +
" in " +
4101 getFuncName(OutermostMatchedFunc, 0);
4103 StatusStr =
"matched " + std::to_string(Matched) +
" frames to " +
4104 getFuncName(OutermostMatchedFunc, 0);
4113 std::string ReachesStr;
4115 const ContextNode *OutermostMatchedNode =
Info.Chain[Matched];
4116 const FuncTy *OutermostMatchedFunc = getCallingFunc(OutermostMatchedNode);
4117 unsigned NumOutermostMatchedFuncClones =
4118 std::max<unsigned>(1, FuncToNumClones.lookup(OutermostMatchedFunc));
4119 ReachesStr =
"; reaches ";
4124 SmallSet<unsigned, 4> ReportedAllocClones;
4125 bool FirstPath =
true;
4126 for (
unsigned OutermostMatchedFuncClone = 0;
4127 OutermostMatchedFuncClone < NumOutermostMatchedFuncClones;
4128 ++OutermostMatchedFuncClone) {
4132 std::vector<const FuncTy *> PathFuncs(Matched + 1);
4133 std::vector<unsigned> PathClones(Matched + 1);
4134 PathFuncs[0] = OutermostMatchedFunc;
4135 PathClones[0] = OutermostMatchedFuncClone;
4136 unsigned CurClone = OutermostMatchedFuncClone;
4137 for (
unsigned Step = 0; Step < Matched; ++Step) {
4138 unsigned FrameIdx = Matched - Step;
4139 const ContextNode *CallNode =
Info.Chain[FrameIdx];
4140 unsigned NextClone =
4141 OrigNodeAndCloneToCalleeClone.lookup({CallNode, CurClone});
4142 const FuncTy *CalleeFunc = getCallingFunc(
Info.Chain[FrameIdx - 1]);
4143 PathFuncs[Step + 1] = CalleeFunc;
4144 PathClones[Step + 1] = NextClone;
4145 CurClone = NextClone;
4148 if (!ReportedAllocClones.
insert(CurClone).second)
4154 const ContextNode *ReachedAlloc =
4155 OrigAllocAndCloneToNode.lookup({OrigAlloc, CurClone});
4159 std::string ReachedTypeStr;
4162 (uint8_t)getAllocationCallType(ReachedAlloc->Call));
4163 else if (CurClone == 0)
4167 ReachedTypeStr =
"None";
4173 std::string PathStr;
4174 bool SkippedPrev =
false;
4175 bool PrintFullPath =
4177 for (
unsigned S = 0; S <= Matched; ++S) {
4178 bool IsCloned = PathClones[S] > 0;
4179 bool PrevCloned = S > 0 ? (PathClones[S - 1] > 0) : IsCloned;
4180 bool NextCloned = S + 1 <= Matched ? (PathClones[S + 1] > 0) : IsCloned;
4181 bool Include = PrintFullPath || (S <= 1) || (S + 1 >= Matched) ||
4182 (IsCloned != PrevCloned) || (IsCloned != NextCloned);
4185 PathStr +=
" -> ...";
4190 SkippedPrev =
false;
4191 if (!PathStr.empty())
4193 PathStr += getFuncName(PathFuncs[S], PathClones[S]);
4195 ReachesStr += ReachedTypeStr +
" via " + PathStr;
4199 return " [alloc in " + AllocFuncStr +
"; " + StatusStr + ReachesStr +
"]";
4202template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4203void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::printTotalSizes(
4205 function_ref<
void(StringRef, StringRef,
const Twine &)> EmitRemark)
const {
4206 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4208 if (
Node->isRemoved())
4210 if (!
Node->IsAllocation)
4212 DenseSet<uint32_t> ContextIds =
Node->getContextIds();
4213 auto AllocTypeFromCall = getAllocationCallType(
Node->Call);
4214 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
4215 std::sort(SortedIds.begin(), SortedIds.end());
4216 for (
auto Id : SortedIds) {
4217 auto TypeI = ContextIdToAllocationType.
find(Id);
4218 assert(TypeI != ContextIdToAllocationType.
end());
4220 bool ComputedSuffix =
false;
4221 auto GetSuffix = [&]() ->
const std::string & {
4222 if (!ComputedSuffix) {
4224 ? formatContextReportSuffix(Node, Id)
4226 ComputedSuffix =
true;
4230 auto CSI = ContextIdToContextSizeInfos.
find(Id);
4231 if (CSI != ContextIdToContextSizeInfos.
end()) {
4232 for (
auto &Info : CSI->second) {
4235 " full allocation context " + std::to_string(
Info.FullStackId) +
4236 " with total size " + std::to_string(
Info.TotalSize) +
" is " +
4238 if (allocTypeToUse(
Node->AllocTypes) !=
4239 allocTypeToUse((uint8_t)AllocTypeFromCall))
4241 " due to cold byte percent";
4243 Msg +=
" (internal context id " + std::to_string(Id) +
")";
4245 OS <<
Msg << GetSuffix() <<
"\n";
4255 if (allocTypeToUse(
Node->AllocTypes) !=
4256 allocTypeToUse((uint8_t)AllocTypeFromCall))
4258 " due to cold byte percent";
4260 Msg +=
" (internal context id " + std::to_string(Id) +
")";
4262 OS <<
Msg << GetSuffix() <<
"\n";
4270template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4271void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::check()
const {
4272 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4275 for (
auto &
Edge :
Node->CallerEdges)
4280template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4282 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4283 using NodeRef =
const ContextNode<DerivedCCG, FuncTy, CallTy> *;
4285 using NodePtrTy = std::unique_ptr<ContextNode<DerivedCCG, FuncTy, CallTy>>;
4301 return G->NodeOwner.begin()->get();
4304 using EdgePtrTy = std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>;
4305 static const ContextNode<DerivedCCG, FuncTy, CallTy> *
4324template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4338 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4344 std::string LabelString =
4345 (
Twine(
"OrigId: ") + (
Node->IsAllocation ?
"Alloc" :
"") +
4348 LabelString +=
"\n";
4349 if (
Node->hasCall()) {
4350 auto Func =
G->NodeToCallingFunc.find(
Node);
4351 assert(Func !=
G->NodeToCallingFunc.end());
4353 G->getLabel(Func->second,
Node->Call.call(),
Node->Call.cloneNo());
4354 for (
auto &MatchingCall :
Node->MatchingCalls) {
4355 LabelString +=
"\n";
4356 LabelString +=
G->getLabel(Func->second, MatchingCall.call(),
4357 MatchingCall.cloneNo());
4360 LabelString +=
"null call";
4361 if (
Node->Recursive)
4362 LabelString +=
" (recursive)";
4364 LabelString +=
" (external)";
4370 auto ContextIds =
Node->getContextIds();
4374 bool Highlight =
false;
4383 std::string AttributeString = (
Twine(
"tooltip=\"") + getNodeId(
Node) +
" " +
4384 getContextIds(ContextIds) +
"\"")
4388 AttributeString +=
",fontsize=\"30\"";
4390 (
Twine(
",fillcolor=\"") + getColor(
Node->AllocTypes, Highlight) +
"\"")
4392 if (
Node->CloneOf) {
4393 AttributeString +=
",color=\"blue\"";
4394 AttributeString +=
",style=\"filled,bold,dashed\"";
4396 AttributeString +=
",style=\"filled\"";
4397 return AttributeString;
4402 auto &Edge = *(ChildIter.getCurrent());
4407 bool Highlight =
false;
4416 auto Color = getColor(Edge->AllocTypes, Highlight);
4417 std::string AttributeString =
4418 (
Twine(
"tooltip=\"") + getContextIds(Edge->ContextIds) +
"\"" +
4420 Twine(
",fillcolor=\"") + Color +
"\"" +
Twine(
",color=\"") + Color +
4423 if (Edge->IsBackedge)
4424 AttributeString +=
",style=\"dotted\"";
4427 AttributeString +=
",penwidth=\"2.0\",weight=\"2\"";
4428 return AttributeString;
4434 if (
Node->isRemoved())
4447 std::string IdString =
"ContextIds:";
4448 if (ContextIds.
size() < 100) {
4449 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
4450 std::sort(SortedIds.begin(), SortedIds.end());
4451 for (
auto Id : SortedIds)
4452 IdString += (
" " +
Twine(Id)).str();
4454 IdString += (
" (" + Twine(ContextIds.
size()) +
" ids)").str();
4459 static std::string getColor(uint8_t AllocTypes,
bool Highlight) {
4465 if (AllocTypes == (uint8_t)AllocationType::NotCold)
4467 return !
DoHighlight || Highlight ?
"brown1" :
"lightpink";
4468 if (AllocTypes == (uint8_t)AllocationType::Cold)
4469 return !
DoHighlight || Highlight ?
"cyan" :
"lightskyblue";
4471 ((uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold))
4472 return Highlight ?
"magenta" :
"mediumorchid1";
4476 static std::string getNodeId(NodeRef Node) {
4477 std::stringstream SStream;
4478 SStream << std::hex <<
"N0x" << (
unsigned long long)Node;
4479 std::string
Result = SStream.str();
4488template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4493template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4494void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::exportToDot(
4495 std::string Label)
const {
4500template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4501typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
4502CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::moveEdgeToNewCalleeClone(
4503 const std::shared_ptr<ContextEdge> &
Edge,
4504 DenseSet<uint32_t> ContextIdsToMove) {
4506 assert(NodeToCallingFunc.count(Node));
4507 ContextNode *Clone =
4508 createNewNode(
Node->IsAllocation, NodeToCallingFunc[Node],
Node->Call);
4509 Node->addClone(Clone);
4510 Clone->MatchingCalls =
Node->MatchingCalls;
4511 moveEdgeToExistingCalleeClone(
Edge, Clone,
true,
4516template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4517void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4518 moveEdgeToExistingCalleeClone(
const std::shared_ptr<ContextEdge> &
Edge,
4519 ContextNode *NewCallee,
bool NewClone,
4520 DenseSet<uint32_t> ContextIdsToMove) {
4523 assert(NewCallee->getOrigNode() ==
Edge->Callee->getOrigNode());
4525 bool EdgeIsRecursive =
Edge->Callee ==
Edge->Caller;
4527 ContextNode *OldCallee =
Edge->Callee;
4531 auto ExistingEdgeToNewCallee = NewCallee->findEdgeFromCaller(
Edge->Caller);
4535 if (ContextIdsToMove.
empty())
4536 ContextIdsToMove =
Edge->getContextIds();
4540 if (
Edge->getContextIds().size() == ContextIdsToMove.
size()) {
4543 NewCallee->AllocTypes |=
Edge->AllocTypes;
4545 if (ExistingEdgeToNewCallee) {
4548 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
4549 ExistingEdgeToNewCallee->AllocTypes |=
Edge->AllocTypes;
4550 assert(
Edge->ContextIds == ContextIdsToMove);
4551 removeEdgeFromGraph(
Edge.get());
4554 Edge->Callee = NewCallee;
4555 NewCallee->CallerEdges.push_back(
Edge);
4557 OldCallee->eraseCallerEdge(
Edge.get());
4564 auto CallerEdgeAllocType = computeAllocType(ContextIdsToMove);
4565 if (ExistingEdgeToNewCallee) {
4568 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
4569 ExistingEdgeToNewCallee->AllocTypes |= CallerEdgeAllocType;
4572 auto NewEdge = std::make_shared<ContextEdge>(
4573 NewCallee,
Edge->Caller, CallerEdgeAllocType, ContextIdsToMove);
4574 Edge->Caller->CalleeEdges.push_back(NewEdge);
4575 NewCallee->CallerEdges.push_back(NewEdge);
4579 NewCallee->AllocTypes |= CallerEdgeAllocType;
4581 Edge->AllocTypes = computeAllocType(
Edge->ContextIds);
4586 for (
auto &OldCalleeEdge : OldCallee->CalleeEdges) {
4587 ContextNode *CalleeToUse = OldCalleeEdge->Callee;
4591 if (CalleeToUse == OldCallee) {
4595 if (EdgeIsRecursive) {
4599 CalleeToUse = NewCallee;
4603 DenseSet<uint32_t> EdgeContextIdsToMove =
4605 set_subtract(OldCalleeEdge->getContextIds(), EdgeContextIdsToMove);
4606 OldCalleeEdge->AllocTypes =
4607 computeAllocType(OldCalleeEdge->getContextIds());
4614 if (
auto *NewCalleeEdge = NewCallee->findEdgeFromCallee(CalleeToUse)) {
4615 NewCalleeEdge->getContextIds().insert_range(EdgeContextIdsToMove);
4616 NewCalleeEdge->AllocTypes |= computeAllocType(EdgeContextIdsToMove);
4620 auto NewEdge = std::make_shared<ContextEdge>(
4621 CalleeToUse, NewCallee, computeAllocType(EdgeContextIdsToMove),
4622 EdgeContextIdsToMove);
4623 NewCallee->CalleeEdges.push_back(NewEdge);
4624 NewEdge->Callee->CallerEdges.push_back(NewEdge);
4628 OldCallee->AllocTypes = OldCallee->computeAllocType();
4630 assert((OldCallee->AllocTypes == (uint8_t)AllocationType::None) ==
4631 OldCallee->emptyContextIds());
4635 for (
const auto &OldCalleeEdge : OldCallee->CalleeEdges)
4638 for (
const auto &NewCalleeEdge : NewCallee->CalleeEdges)
4644template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4645void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4646 moveCalleeEdgeToNewCaller(
const std::shared_ptr<ContextEdge> &
Edge,
4647 ContextNode *NewCaller) {
4648 auto *OldCallee =
Edge->Callee;
4649 auto *NewCallee = OldCallee;
4652 bool Recursive =
Edge->Caller ==
Edge->Callee;
4654 NewCallee = NewCaller;
4656 ContextNode *OldCaller =
Edge->Caller;
4657 OldCaller->eraseCalleeEdge(
Edge.get());
4661 auto ExistingEdgeToNewCaller = NewCaller->findEdgeFromCallee(NewCallee);
4663 if (ExistingEdgeToNewCaller) {
4666 ExistingEdgeToNewCaller->getContextIds().insert_range(
4667 Edge->getContextIds());
4668 ExistingEdgeToNewCaller->AllocTypes |=
Edge->AllocTypes;
4669 Edge->ContextIds.clear();
4670 Edge->AllocTypes = (uint8_t)AllocationType::None;
4671 OldCallee->eraseCallerEdge(
Edge.get());
4674 Edge->Caller = NewCaller;
4675 NewCaller->CalleeEdges.push_back(
Edge);
4677 assert(NewCallee == NewCaller);
4680 Edge->Callee = NewCallee;
4681 NewCallee->CallerEdges.push_back(
Edge);
4682 OldCallee->eraseCallerEdge(
Edge.get());
4688 NewCaller->AllocTypes |=
Edge->AllocTypes;
4695 bool IsNewNode = NewCaller->CallerEdges.empty();
4704 for (
auto &OldCallerEdge : OldCaller->CallerEdges) {
4705 auto OldCallerCaller = OldCallerEdge->Caller;
4709 OldCallerEdge->getContextIds(),
Edge->getContextIds());
4710 if (OldCaller == OldCallerCaller) {
4711 OldCallerCaller = NewCaller;
4717 set_subtract(OldCallerEdge->getContextIds(), EdgeContextIdsToMove);
4718 OldCallerEdge->AllocTypes =
4719 computeAllocType(OldCallerEdge->getContextIds());
4724 auto *ExistingCallerEdge = NewCaller->findEdgeFromCaller(OldCallerCaller);
4728 if (ExistingCallerEdge) {
4729 ExistingCallerEdge->getContextIds().insert_range(EdgeContextIdsToMove);
4730 ExistingCallerEdge->AllocTypes |=
4731 computeAllocType(EdgeContextIdsToMove);
4734 auto NewEdge = std::make_shared<ContextEdge>(
4735 NewCaller, OldCallerCaller, computeAllocType(EdgeContextIdsToMove),
4736 EdgeContextIdsToMove);
4737 NewCaller->CallerEdges.push_back(NewEdge);
4738 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
4743 OldCaller->AllocTypes = OldCaller->computeAllocType();
4745 assert((OldCaller->AllocTypes == (uint8_t)AllocationType::None) ==
4746 OldCaller->emptyContextIds());
4750 for (
const auto &OldCallerEdge : OldCaller->CallerEdges)
4753 for (
const auto &NewCallerEdge : NewCaller->CallerEdges)
4759template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4760void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4761 recursivelyRemoveNoneTypeCalleeEdges(
4762 ContextNode *Node, DenseSet<const ContextNode *> &Visited) {
4767 removeNoneTypeCalleeEdges(Node);
4769 for (
auto *Clone :
Node->Clones)
4770 recursivelyRemoveNoneTypeCalleeEdges(Clone, Visited);
4774 auto CallerEdges =
Node->CallerEdges;
4775 for (
auto &
Edge : CallerEdges) {
4777 if (
Edge->isRemoved()) {
4781 recursivelyRemoveNoneTypeCalleeEdges(
Edge->Caller, Visited);
4786template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4787void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges() {
4792 DenseSet<const ContextNode *> Visited;
4793 DenseSet<const ContextNode *> CurrentStack;
4794 for (
auto &Entry : NonAllocationCallToContextNodeMap) {
4796 if (
Node->isRemoved())
4799 if (!
Node->CallerEdges.empty())
4801 markBackedges(Node, Visited, CurrentStack);
4807template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4808void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges(
4809 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4810 DenseSet<const ContextNode *> &CurrentStack) {
4811 auto I = Visited.
insert(Node);
4815 for (
auto &CalleeEdge :
Node->CalleeEdges) {
4816 auto *
Callee = CalleeEdge->Callee;
4817 if (Visited.
count(Callee)) {
4820 if (CurrentStack.
count(Callee))
4821 CalleeEdge->IsBackedge =
true;
4824 CurrentStack.
insert(Callee);
4825 markBackedges(Callee, Visited, CurrentStack);
4826 CurrentStack.
erase(Callee);
4830template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4831void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones() {
4832 DenseSet<const ContextNode *> Visited;
4833 for (
auto &Entry : AllocationCallToContextNodeMap) {
4835 identifyClones(
Entry.second, Visited,
Entry.second->getContextIds());
4838 for (
auto &Entry : AllocationCallToContextNodeMap)
4839 recursivelyRemoveNoneTypeCalleeEdges(
Entry.second, Visited);
4852template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4853void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones(
4854 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4855 const DenseSet<uint32_t> &AllocContextIds) {
4865 if (!
Node->hasCall())
4884 auto CallerEdges =
Node->CallerEdges;
4885 for (
auto &
Edge : CallerEdges) {
4887 if (
Edge->isRemoved()) {
4893 if (
Edge->IsBackedge) {
4900 if (!Visited.
count(
Edge->Caller) && !
Edge->Caller->CloneOf) {
4901 identifyClones(
Edge->Caller, Visited, AllocContextIds);
4924 const unsigned AllocTypeCloningPriority[] = { 3, 4,
4928 [&](
const std::shared_ptr<ContextEdge> &
A,
4929 const std::shared_ptr<ContextEdge> &
B) {
4932 if (A->ContextIds.empty())
4938 if (B->ContextIds.empty())
4941 if (A->AllocTypes == B->AllocTypes)
4944 return A->Caller->NodeId < B->Caller->NodeId;
4945 return AllocTypeCloningPriority[A->AllocTypes] <
4946 AllocTypeCloningPriority[B->AllocTypes];
4949 assert(
Node->AllocTypes != (uint8_t)AllocationType::None);
4951 DenseSet<uint32_t> RecursiveContextIds;
4956 DenseSet<uint32_t> AllCallerContextIds;
4957 for (
auto &CE :
Node->CallerEdges) {
4960 AllCallerContextIds.
reserve(
CE->getContextIds().size());
4961 for (
auto Id :
CE->getContextIds())
4962 if (!AllCallerContextIds.
insert(Id).second)
4963 RecursiveContextIds.
insert(Id);
4973 auto CallerEdges =
Node->CallerEdges;
4974 for (
auto &CallerEdge : CallerEdges) {
4976 if (CallerEdge->isRemoved()) {
4980 assert(CallerEdge->Callee == Node);
4989 if (!CallerEdge->Caller->hasCall())
4994 auto CallerEdgeContextsForAlloc =
4996 if (!RecursiveContextIds.
empty())
4997 CallerEdgeContextsForAlloc =
4999 if (CallerEdgeContextsForAlloc.empty())
5002 auto CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
5006 std::vector<uint8_t> CalleeEdgeAllocTypesForCallerEdge;
5007 CalleeEdgeAllocTypesForCallerEdge.reserve(
Node->CalleeEdges.size());
5008 for (
auto &CalleeEdge :
Node->CalleeEdges)
5009 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
5010 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
5026 assert(CallerEdge->AllocTypes != (uint8_t)AllocationType::None);
5027 assert(
Node->AllocTypes != (uint8_t)AllocationType::None);
5028 if (!CallerEdge->IsBackedge &&
5029 allocTypeToUse(CallerAllocTypeForAlloc) ==
5030 allocTypeToUse(
Node->AllocTypes) &&
5031 allocTypesMatch<DerivedCCG, FuncTy, CallTy>(
5032 CalleeEdgeAllocTypesForCallerEdge,
Node->CalleeEdges)) {
5036 if (CallerEdge->IsBackedge) {
5040 DeferredBackedges++;
5053 if (CallerEdge->IsBackedge && !CallerEdge->Caller->CloneOf &&
5054 !Visited.
count(CallerEdge->Caller)) {
5055 const auto OrigIdCount = CallerEdge->getContextIds().size();
5058 identifyClones(CallerEdge->Caller, Visited, CallerEdgeContextsForAlloc);
5059 removeNoneTypeCalleeEdges(CallerEdge->Caller);
5063 bool UpdatedEdge =
false;
5064 if (OrigIdCount > CallerEdge->getContextIds().size()) {
5065 for (
auto E :
Node->CallerEdges) {
5067 if (
E->Caller->CloneOf != CallerEdge->Caller)
5071 auto CallerEdgeContextsForAllocNew =
5073 if (CallerEdgeContextsForAllocNew.empty())
5083 CallerEdgeContextsForAlloc.swap(CallerEdgeContextsForAllocNew);
5093 if (CallerEdge->isRemoved())
5103 CallerEdgeContextsForAlloc, CallerEdge->getContextIds());
5104 if (CallerEdgeContextsForAlloc.empty())
5109 CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
5110 CalleeEdgeAllocTypesForCallerEdge.clear();
5111 for (
auto &CalleeEdge :
Node->CalleeEdges) {
5112 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
5113 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
5119 ContextNode *Clone =
nullptr;
5120 for (
auto *CurClone :
Node->Clones) {
5121 if (allocTypeToUse(CurClone->AllocTypes) !=
5122 allocTypeToUse(CallerAllocTypeForAlloc))
5129 assert(!BothSingleAlloc ||
5130 CurClone->AllocTypes == CallerAllocTypeForAlloc);
5136 if (BothSingleAlloc || allocTypesMatchClone<DerivedCCG, FuncTy, CallTy>(
5137 CalleeEdgeAllocTypesForCallerEdge, CurClone)) {
5145 moveEdgeToExistingCalleeClone(CallerEdge, Clone,
false,
5146 CallerEdgeContextsForAlloc);
5148 Clone = moveEdgeToNewCalleeClone(CallerEdge, CallerEdgeContextsForAlloc);
5151 assert(Clone->AllocTypes != (uint8_t)AllocationType::None);
5158 assert(
Node->AllocTypes != (uint8_t)AllocationType::None);
5164void ModuleCallsiteContextGraph::updateAllocationCall(
5180 .emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofAttribute",
Call.call())
5181 <<
ore::NV(
"AllocationCall",
Call.call()) <<
" in clone "
5183 <<
" marked with memprof allocation attribute "
5184 <<
ore::NV(
"Attribute", AllocTypeString));
5187void IndexCallsiteContextGraph::updateAllocationCall(CallInfo &
Call,
5191 assert(AI->Versions.size() >
Call.cloneNo());
5196ModuleCallsiteContextGraph::getAllocationCallType(
const CallInfo &
Call)
const {
5198 if (!CB->getAttributes().hasFnAttr(
"memprof"))
5199 return AllocationType::None;
5200 StringRef AllocTypeString =
5201 CB->getAttributes().getFnAttr(
"memprof").getValueAsString();
5202 if (AllocTypeString ==
"cold")
5203 return AllocationType::Cold;
5204 if (AllocTypeString ==
"ambiguous")
5206 (uint8_t)AllocationType::Cold);
5207 return AllocationType::NotCold;
5211IndexCallsiteContextGraph::getAllocationCallType(
const CallInfo &
Call)
const {
5213 assert(AI->Versions.size() >
Call.cloneNo());
5217void ModuleCallsiteContextGraph::updateCall(CallInfo &CallerCall,
5218 FuncInfo CalleeFunc) {
5219 auto *CurF = getCalleeFunc(CallerCall.call());
5220 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
5227 if (CurCalleeCloneNo != NewCalleeCloneNo) {
5229 << CurCalleeCloneNo <<
" now " << NewCalleeCloneNo
5231 MismatchedCloneAssignments++;
5234 if (NewCalleeCloneNo > 0)
5235 cast<CallBase>(CallerCall.call())->setCalledFunction(CalleeFunc.func());
5236 OREGetter(CallerCall.call()->getFunction())
5237 .emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofCall", CallerCall.call())
5238 <<
ore::NV(
"Call", CallerCall.call()) <<
" in clone "
5239 <<
ore::NV(
"Caller", CallerCall.call()->getFunction())
5240 <<
" assigned to call function clone "
5241 <<
ore::NV(
"Callee", CalleeFunc.func()));
5244void IndexCallsiteContextGraph::updateCall(CallInfo &CallerCall,
5245 FuncInfo CalleeFunc) {
5248 "Caller cannot be an allocation which should not have profiled calls");
5249 assert(CI->Clones.size() > CallerCall.cloneNo());
5250 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
5251 auto &CurCalleeCloneNo = CI->Clones[CallerCall.cloneNo()];
5256 if (CurCalleeCloneNo != 0 && CurCalleeCloneNo != NewCalleeCloneNo) {
5258 << CurCalleeCloneNo <<
" now " << NewCalleeCloneNo
5260 MismatchedCloneAssignments++;
5262 CurCalleeCloneNo = NewCalleeCloneNo;
5274 SP->replaceLinkageName(MDName);
5278 TempDISubprogram NewDecl = Decl->
clone();
5279 NewDecl->replaceLinkageName(MDName);
5283CallsiteContextGraph<ModuleCallsiteContextGraph,
Function,
5285ModuleCallsiteContextGraph::cloneFunctionForCallsite(
5286 FuncInfo &Func, CallInfo &
Call, DenseMap<CallInfo, CallInfo> &CallMap,
5287 std::vector<CallInfo> &CallsWithMetadataInFunc,
unsigned CloneNo) {
5294 NewFunc->setMetadata(LLVMContext::MD_kcfi_type,
nullptr);
5296 assert(!
Func.func()->getParent()->getFunction(Name));
5297 NewFunc->setName(Name);
5299 for (
auto &Inst : CallsWithMetadataInFunc) {
5301 assert(Inst.cloneNo() == 0);
5304 OREGetter(
Func.func())
5305 .emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofClone",
Func.func())
5306 <<
"created clone " <<
ore::NV(
"NewFunction", NewFunc));
5307 return {NewFunc, CloneNo};
5310CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
5311 IndexCall>::FuncInfo
5312IndexCallsiteContextGraph::cloneFunctionForCallsite(
5313 FuncInfo &Func, CallInfo &
Call, DenseMap<CallInfo, CallInfo> &CallMap,
5314 std::vector<CallInfo> &CallsWithMetadataInFunc,
unsigned CloneNo) {
5328 for (
auto &Inst : CallsWithMetadataInFunc) {
5330 assert(Inst.cloneNo() == 0);
5332 assert(AI->Versions.size() == CloneNo);
5335 AI->Versions.push_back(0);
5338 assert(CI && CI->Clones.size() == CloneNo);
5341 CI->Clones.push_back(0);
5343 CallMap[Inst] = {Inst.call(), CloneNo};
5345 return {
Func.func(), CloneNo};
5362template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5363void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones() {
5369 DenseMap<uint32_t, ContextNode *> ContextIdToAllocationNode;
5370 for (
auto &Entry : AllocationCallToContextNodeMap) {
5372 for (
auto Id :
Node->getContextIds())
5373 ContextIdToAllocationNode[
Id] =
Node->getOrigNode();
5374 for (
auto *Clone :
Node->Clones) {
5375 for (
auto Id : Clone->getContextIds())
5376 ContextIdToAllocationNode[
Id] = Clone->getOrigNode();
5383 DenseSet<const ContextNode *> Visited;
5384 for (
auto &Entry : AllocationCallToContextNodeMap) {
5387 mergeClones(Node, Visited, ContextIdToAllocationNode);
5393 auto Clones =
Node->Clones;
5394 for (
auto *Clone : Clones)
5395 mergeClones(Clone, Visited, ContextIdToAllocationNode);
5399 dbgs() <<
"CCG after merging:\n";
5403 exportToDot(
"aftermerge");
5411template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5412void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones(
5413 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
5414 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
5424 bool FoundUnvisited =
true;
5426 while (FoundUnvisited) {
5428 FoundUnvisited =
false;
5431 auto CallerEdges =
Node->CallerEdges;
5432 for (
auto CallerEdge : CallerEdges) {
5434 if (CallerEdge->Callee != Node)
5439 FoundUnvisited =
true;
5440 mergeClones(CallerEdge->Caller, Visited, ContextIdToAllocationNode);
5444 TotalMergeInvokes++;
5445 TotalMergeIters += Iters;
5446 if (Iters > MaxMergeIters)
5447 MaxMergeIters = Iters;
5450 mergeNodeCalleeClones(Node, Visited, ContextIdToAllocationNode);
5453template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5454void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeNodeCalleeClones(
5455 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
5456 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
5458 if (
Node->emptyContextIds())
5463 MapVector<ContextNode *, std::vector<std::shared_ptr<ContextEdge>>>
5464 OrigNodeToCloneEdges;
5465 for (
const auto &
E :
Node->CalleeEdges) {
5470 OrigNodeToCloneEdges[
Base].push_back(
E);
5476 auto CalleeCallerEdgeLessThan = [](
const std::shared_ptr<ContextEdge> &
A,
5477 const std::shared_ptr<ContextEdge> &
B) {
5478 if (
A->Callee->CallerEdges.size() !=
B->Callee->CallerEdges.size())
5479 return A->Callee->CallerEdges.size() <
B->Callee->CallerEdges.size();
5480 if (
A->Callee->CloneOf && !
B->Callee->CloneOf)
5482 else if (!
A->Callee->CloneOf &&
B->Callee->CloneOf)
5485 return A->Callee->NodeId <
B->Callee->NodeId;
5490 for (
auto Entry : OrigNodeToCloneEdges) {
5493 auto &CalleeEdges =
Entry.second;
5494 auto NumCalleeClones = CalleeEdges.size();
5496 if (NumCalleeClones == 1)
5507 DenseSet<ContextNode *> OtherCallersToShareMerge;
5508 findOtherCallersToShareMerge(Node, CalleeEdges, ContextIdToAllocationNode,
5509 OtherCallersToShareMerge);
5514 ContextNode *MergeNode =
nullptr;
5515 DenseMap<ContextNode *, unsigned> CallerToMoveCount;
5516 for (
auto CalleeEdge : CalleeEdges) {
5517 auto *OrigCallee = CalleeEdge->Callee;
5523 if (CalleeEdge->Callee->CallerEdges.size() == 1) {
5524 MergeNode = OrigCallee;
5525 NonNewMergedNodes++;
5532 if (!OtherCallersToShareMerge.
empty()) {
5533 bool MoveAllCallerEdges =
true;
5534 for (
auto CalleeCallerE : OrigCallee->CallerEdges) {
5535 if (CalleeCallerE == CalleeEdge)
5537 if (!OtherCallersToShareMerge.
contains(CalleeCallerE->Caller)) {
5538 MoveAllCallerEdges =
false;
5544 if (MoveAllCallerEdges) {
5545 MergeNode = OrigCallee;
5546 NonNewMergedNodes++;
5553 assert(MergeNode != OrigCallee);
5554 moveEdgeToExistingCalleeClone(CalleeEdge, MergeNode,
5557 MergeNode = moveEdgeToNewCalleeClone(CalleeEdge);
5562 if (!OtherCallersToShareMerge.
empty()) {
5566 auto OrigCalleeCallerEdges = OrigCallee->CallerEdges;
5567 for (
auto &CalleeCallerE : OrigCalleeCallerEdges) {
5568 if (CalleeCallerE == CalleeEdge)
5570 if (!OtherCallersToShareMerge.
contains(CalleeCallerE->Caller))
5572 CallerToMoveCount[CalleeCallerE->Caller]++;
5573 moveEdgeToExistingCalleeClone(CalleeCallerE, MergeNode,
5577 removeNoneTypeCalleeEdges(OrigCallee);
5578 removeNoneTypeCalleeEdges(MergeNode);
5596template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5597void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
5598 findOtherCallersToShareMerge(
5600 std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
5601 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
5602 DenseSet<ContextNode *> &OtherCallersToShareMerge) {
5603 auto NumCalleeClones = CalleeEdges.size();
5606 DenseMap<ContextNode *, unsigned> OtherCallersToSharedCalleeEdgeCount;
5609 unsigned PossibleOtherCallerNodes = 0;
5613 if (CalleeEdges[0]->
Callee->CallerEdges.size() < 2)
5619 DenseMap<ContextEdge *, DenseSet<ContextNode *>> CalleeEdgeToAllocNodes;
5620 for (
auto CalleeEdge : CalleeEdges) {
5621 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
5624 for (
auto CalleeCallerEdges : CalleeEdge->Callee->CallerEdges) {
5625 if (CalleeCallerEdges->Caller == Node) {
5626 assert(CalleeCallerEdges == CalleeEdge);
5629 OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller]++;
5632 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller] ==
5634 PossibleOtherCallerNodes++;
5638 for (
auto Id : CalleeEdge->getContextIds()) {
5639 auto *
Alloc = ContextIdToAllocationNode.
lookup(Id);
5643 MissingAllocForContextId++;
5646 CalleeEdgeToAllocNodes[CalleeEdge.get()].
insert(
Alloc);
5653 for (
auto CalleeEdge : CalleeEdges) {
5654 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
5656 if (!PossibleOtherCallerNodes)
5658 auto &CurCalleeAllocNodes = CalleeEdgeToAllocNodes[CalleeEdge.get()];
5660 for (
auto &CalleeCallerE : CalleeEdge->Callee->CallerEdges) {
5662 if (CalleeCallerE == CalleeEdge)
5666 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] !=
5671 for (
auto Id : CalleeCallerE->getContextIds()) {
5672 auto *
Alloc = ContextIdToAllocationNode.
lookup(Id);
5677 if (!CurCalleeAllocNodes.contains(
Alloc)) {
5678 OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] = 0;
5679 PossibleOtherCallerNodes--;
5686 if (!PossibleOtherCallerNodes)
5691 for (
auto &[OtherCaller,
Count] : OtherCallersToSharedCalleeEdgeCount) {
5692 if (
Count != NumCalleeClones)
5694 OtherCallersToShareMerge.
insert(OtherCaller);
5698template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5699const typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
5700CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::resolveImplicitSource(
5701 const ContextNode *Node,
const ImplicitSource &Src) {
5702 if (!Src.Source->emptyContextIds())
5708 if (
Node->hasContextId(Src.ContextId))
5710 for (
const ContextNode *
C :
Node->Clones)
5711 if (
C->hasContextId(Src.ContextId))
5716 assert(
false &&
"trimmed context id on no clone of its callsite node");
5758template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5759void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignImplicitCallers(
5760 ContextNode *Node,
const DenseSet<uint32_t> &TrimmedContextIds,
5761 DenseMap<ContextNode *, FuncInfo> &CallsiteToCalleeFuncCloneMap,
5762 const std::map<FuncInfo, ContextNode *> &FuncCloneToCurNodeCloneMap,
5763 ImplicitSourceMap &ImplicitSources) {
5764 auto HasEdgeToNodeFamily = [&](
const ContextNode *
N) {
5766 [&](
const std::shared_ptr<ContextEdge> &
E) {
5767 return E->Callee->getOrigNode() == Node;
5801 auto ImpliesContextIds =
5802 [&](ContextNode *
K, ContextNode *
Y,
const DenseSet<uint32_t> &Ids,
5803 DenseMap<std::pair<ContextNode *, ContextNode *>, DenseSet<uint32_t>>
5805 auto &&ImpliesContextIds) ->
bool {
5806 assert(
K->getOrigNode() ==
Y->getOrigNode());
5807 DenseSet<uint32_t> &VisitedIds = Visited[{
K,
Y}];
5808 DenseSet<uint32_t> NewIds;
5810 if (VisitedIds.
insert(Id).second)
5818 DenseSet<uint32_t> IdsOnCallerEdges;
5819 for (
auto &YEdge :
Y->CallerEdges) {
5820 DenseSet<uint32_t> IdsFromZ =
5822 if (IdsFromZ.
empty())
5825 IdsFromCallers.
push_back({YEdge->Caller, std::move(IdsFromZ)});
5829 if (IdsOnCallerEdges.
size() < NewIds.
size())
5833 for (
auto &[Z, IdsFromZ] : IdsFromCallers) {
5834 for (
auto &KEdge :
K->CallerEdges) {
5835 ContextNode *
C = KEdge->Caller;
5836 if (
C == Z ||
C->getOrigNode() !=
Z->getOrigNode())
5840 DenseSet<uint32_t> IdsNotOnC;
5841 for (
auto Id : IdsFromZ)
5842 if (!
C->hasContextId(Id))
5844 if (!IdsNotOnC.
empty() &&
5845 ImpliesContextIds(
C, Z, IdsNotOnC, Visited, ImpliesContextIds))
5854 auto SameVersion = [&](
const ContextNode *
A,
const ContextNode *
B) {
5857 if (
Node->IsAllocation)
5858 return allocTypeToUse(
A->AllocTypes) == allocTypeToUse(
B->AllocTypes);
5859 auto AIt = CallsiteToCalleeFuncCloneMap.
find(
A);
5860 auto BIt = CallsiteToCalleeFuncCloneMap.
find(
B);
5861 return AIt != CallsiteToCalleeFuncCloneMap.
end() &&
5862 BIt != CallsiteToCalleeFuncCloneMap.
end() &&
5863 AIt->second == BIt->second;
5867 DenseSet<const ContextNode *> ImplicitCallers;
5872 auto ProcessCaller = [&](
const std::shared_ptr<ContextEdge> &
Edge) {
5873 ContextNode *
Y =
Edge->Caller;
5874 ContextNode *Orig =
Y->getOrigNode();
5875 if (!
Y->hasCall() || Orig->Clones.empty())
5877 DenseSet<uint32_t> TrimmedIds =
5879 if (TrimmedIds.
empty())
5881 auto YIt = CallsiteToCalleeFuncCloneMap.
find(
Y);
5882 if (YIt == CallsiteToCalleeFuncCloneMap.
end())
5885 const FuncInfo YFuncClone = YIt->second;
5888 auto RequiredIt = FuncCloneToCurNodeCloneMap.find(YFuncClone);
5889 assert(RequiredIt != FuncCloneToCurNodeCloneMap.end());
5890 const ContextNode *
Required = RequiredIt->second;
5898 auto RecordImplicitSource = [&](
const FuncInfo &
F,
const ContextNode *Src) {
5901 if (
F.cloneNo() != 0)
5902 ImplicitSources.try_emplace({
Node,
F.cloneNo()},
5903 ImplicitSource{Src, *TrimmedIds.
begin()});
5909 if (K ==
Y || !
K->hasCall() ||
K->emptyContextIds() ||
5910 HasEdgeToNodeFamily(K) || ImplicitCallers.
contains(K))
5912 DenseMap<std::pair<ContextNode *, ContextNode *>, DenseSet<uint32_t>>
5914 if (!ImpliesContextIds(K,
Y, TrimmedIds, Visited, ImpliesContextIds))
5917 ImplicitCallers.
insert(K);
5918 auto KIt = CallsiteToCalleeFuncCloneMap.
find(K);
5919 if (KIt == CallsiteToCalleeFuncCloneMap.
end()) {
5922 CallsiteToCalleeFuncCloneMap[
K] = YFuncClone;
5923 RecordImplicitSource(YFuncClone, Required);
5924 NumImplicitCallersAssigned++;
5927 const FuncInfo KFuncClone = KIt->second;
5928 if (KFuncClone == YFuncClone) {
5930 RecordImplicitSource(YFuncClone, Required);
5933 unsigned KCloneNo = KFuncClone.cloneNo();
5934 auto KNodeCloneIt = FuncCloneToCurNodeCloneMap.find(KFuncClone);
5935 if (KNodeCloneIt == FuncCloneToCurNodeCloneMap.end()) {
5937 if (KCloneNo == 0) {
5941 if (
Node->IsAllocation) {
5942 if (allocTypeToUse(
Required->AllocTypes) == AllocationType::NotCold)
5944 }
else if (
auto It = CallsiteToCalleeFuncCloneMap.
find(Required);
5945 It != CallsiteToCalleeFuncCloneMap.
end() &&
5946 It->second.cloneNo() == 0)
5952 auto [It,
Inserted] = ImplicitSources.try_emplace(
5955 NumImplicitCallersSourced++;
5956 if (SameVersion(It->second.Source, Required))
5959 }
else if (SameVersion(KNodeCloneIt->second, Required)) {
5962 RecordImplicitSource(KFuncClone, KNodeCloneIt->second);
5966 NumImplicitCallersUnresolved++;
5972 for (
auto &
Edge :
Node->CallerEdges)
5973 ProcessCaller(
Edge);
5974 for (
auto *Clone :
Node->Clones)
5975 for (
auto &
Edge : Clone->CallerEdges)
5976 ProcessCaller(
Edge);
6020template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
6021bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignFunctions() {
6029 DenseSet<uint32_t> TrimmedContextIds;
6030 for (
auto &NodePtr : NodeOwner) {
6031 ContextNode *
N = NodePtr.get();
6032 if (
N->IsAllocation ||
N->CalleeEdges.empty() ||
6033 (
N->CallerEdges.empty() &&
N->Clones.empty() && !
N->CloneOf))
6038 DenseSet<uint32_t> CallerIds;
6039 for (
auto &
E :
N->CallerEdges)
6041 for (
auto &CalleeEdge :
N->CalleeEdges)
6042 for (
auto Id : CalleeEdge->getContextIds())
6044 TrimmedContextIds.
insert(Id);
6046 NumTrimmedContextIds += TrimmedContextIds.
size();
6050 DenseMap<ContextNode *, FuncInfo> CallsiteToCalleeFuncCloneMap;
6054 auto RecordCalleeFuncOfCallsite = [&](ContextNode *
Caller,
6055 const FuncInfo &CalleeFunc) {
6057 CallsiteToCalleeFuncCloneMap[
Caller] = CalleeFunc;
6061 struct FuncCloneInfo {
6066 DenseMap<CallInfo, CallInfo> CallMap;
6102 struct UnassignedCallCloneInfo {
6104 const ContextNode *
Source =
nullptr;
6106 DenseMap<const ContextNode *, std::map<unsigned, UnassignedCallCloneInfo>>
6107 UnassignedCallClones;
6111 for (
auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
6112 FuncInfo OrigFunc(Func);
6117 std::vector<FuncCloneInfo> FuncCloneInfos;
6124 std::vector<unsigned> FuncCloneParent;
6127 ImplicitSourceMap ImplicitSources;
6134 struct OrigCallsInfo {
6138 DenseMap<const ContextNode *, OrigCallsInfo> OrigNodeToOrigCalls;
6139 for (
auto &
Call : CallsWithMetadata) {
6140 ContextNode *
Node = getNodeForInst(
Call);
6142 OrigNodeToOrigCalls[
Node] = {
Call,
Node->MatchingCalls};
6144 for (
auto &
Call : CallsWithMetadata) {
6145 ContextNode *
Node = getNodeForInst(
Call);
6149 if (!Node ||
Node->Clones.empty())
6152 "Not having a call should have prevented cloning");
6156 std::map<FuncInfo, ContextNode *> FuncCloneToCurNodeCloneMap;
6160 auto AssignCallsiteCloneToFuncClone = [&](
const FuncInfo &FuncClone,
6162 ContextNode *CallsiteClone,
6165 FuncCloneToCurNodeCloneMap[FuncClone] = CallsiteClone;
6167 assert(FuncCloneInfos.size() > FuncClone.cloneNo());
6168 DenseMap<CallInfo, CallInfo> &CallMap =
6169 FuncCloneInfos[FuncClone.cloneNo()].CallMap;
6170 CallInfo CallClone(
Call);
6171 if (
auto It = CallMap.
find(
Call); It != CallMap.
end())
6172 CallClone = It->second;
6173 CallsiteClone->setCall(CallClone);
6179 CallsiteClone->MatchingCalls.clear();
6180 for (
const CallInfo &OrigMatchingCall :
6181 OrigNodeToOrigCalls[Node].MatchingCalls) {
6182 CallInfo CallClone(OrigMatchingCall);
6183 if (
auto It = CallMap.
find(OrigMatchingCall); It != CallMap.
end())
6184 CallClone = It->second;
6185 CallsiteClone->MatchingCalls.push_back(CallClone);
6193 auto MoveEdgeToNewCalleeCloneAndSetUp =
6194 [&](
const std::shared_ptr<ContextEdge> &
Edge) {
6195 ContextNode *OrigCallee =
Edge->Callee;
6196 ContextNode *NewClone = moveEdgeToNewCalleeClone(
Edge);
6197 removeNoneTypeCalleeEdges(NewClone);
6198 assert(NewClone->AllocTypes != (uint8_t)AllocationType::None);
6202 if (CallsiteToCalleeFuncCloneMap.
count(OrigCallee))
6203 RecordCalleeFuncOfCallsite(
6204 NewClone, CallsiteToCalleeFuncCloneMap[OrigCallee]);
6211 std::deque<ContextNode *> ClonesWorklist;
6213 if (!
Node->emptyContextIds())
6214 ClonesWorklist.push_back(Node);
6220 unsigned NodeCloneCount = 0;
6221 while (!ClonesWorklist.empty()) {
6222 ContextNode *Clone = ClonesWorklist.front();
6223 ClonesWorklist.pop_front();
6232 if (FuncCloneInfos.size() < NodeCloneCount) {
6234 if (NodeCloneCount == 1) {
6239 Clone->CallerEdges, [&](
const std::shared_ptr<ContextEdge> &
E) {
6240 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
6244 FuncCloneInfos.push_back(
6245 {OrigFunc, DenseMap<CallInfo, CallInfo>()});
6246 FuncCloneParent.push_back(0);
6247 AssignCallsiteCloneToFuncClone(
6248 OrigFunc,
Call, Clone,
6249 AllocationCallToContextNodeMap.count(
Call));
6250 for (
auto &CE : Clone->CallerEdges) {
6252 if (!
CE->Caller->hasCall())
6254 RecordCalleeFuncOfCallsite(
CE->Caller, OrigFunc);
6264 FuncInfo PreviousAssignedFuncClone;
6266 Clone->CallerEdges, [&](
const std::shared_ptr<ContextEdge> &
E) {
6267 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
6269 bool CallerAssignedToCloneOfFunc =
false;
6270 if (EI != Clone->CallerEdges.end()) {
6271 const std::shared_ptr<ContextEdge> &
Edge = *EI;
6272 PreviousAssignedFuncClone =
6273 CallsiteToCalleeFuncCloneMap[
Edge->Caller];
6274 CallerAssignedToCloneOfFunc =
true;
6279 DenseMap<CallInfo, CallInfo> NewCallMap;
6280 unsigned CloneNo = FuncCloneInfos.size();
6281 assert(CloneNo > 0 &&
"Clone 0 is the original function, which "
6282 "should already exist in the map");
6283 FuncInfo NewFuncClone = cloneFunctionForCallsite(
6284 OrigFunc,
Call, NewCallMap, CallsWithMetadata, CloneNo);
6285 FuncCloneInfos.push_back({NewFuncClone, std::move(NewCallMap)});
6288 FuncCloneParent.push_back(CallerAssignedToCloneOfFunc
6289 ? PreviousAssignedFuncClone.cloneNo()
6291 FunctionClonesAnalysis++;
6297 if (!CallerAssignedToCloneOfFunc) {
6298 AssignCallsiteCloneToFuncClone(
6299 NewFuncClone,
Call, Clone,
6300 AllocationCallToContextNodeMap.count(
Call));
6301 for (
auto &CE : Clone->CallerEdges) {
6303 if (!
CE->Caller->hasCall())
6305 RecordCalleeFuncOfCallsite(
CE->Caller, NewFuncClone);
6317 auto CallerEdges = Clone->CallerEdges;
6318 for (
auto CE : CallerEdges) {
6320 if (
CE->isRemoved()) {
6326 if (!
CE->Caller->hasCall())
6329 if (!CallsiteToCalleeFuncCloneMap.
count(
CE->Caller) ||
6333 CallsiteToCalleeFuncCloneMap[
CE->Caller] !=
6334 PreviousAssignedFuncClone)
6337 RecordCalleeFuncOfCallsite(
CE->Caller, NewFuncClone);
6350 auto CalleeEdges =
CE->Caller->CalleeEdges;
6351 for (
auto CalleeEdge : CalleeEdges) {
6354 if (CalleeEdge->isRemoved()) {
6359 ContextNode *
Callee = CalleeEdge->Callee;
6363 if (Callee == Clone || !
Callee->hasCall())
6368 if (Callee == CalleeEdge->Caller)
6370 ContextNode *NewClone =
6371 MoveEdgeToNewCalleeCloneAndSetUp(CalleeEdge);
6374 removeNoneTypeCalleeEdges(Callee);
6387 auto &OrigCalls = OrigNodeToOrigCalls[
Callee->getOrigNode()];
6388 DenseMap<CallInfo, CallInfo> &CallMap =
6389 FuncCloneInfos[NewFuncClone.cloneNo()].CallMap;
6391 CallInfo NewCall(CallMap[OrigCalls.Call]);
6393 NewClone->setCall(NewCall);
6395 NewClone->MatchingCalls.clear();
6396 for (
auto &OrigMatchingCall : OrigCalls.MatchingCalls) {
6398 CallInfo NewCall(CallMap[OrigMatchingCall]);
6400 NewClone->MatchingCalls.push_back(NewCall);
6409 auto FindFirstAvailFuncClone = [&]() {
6414 for (
auto &CF : FuncCloneInfos) {
6415 if (!FuncCloneToCurNodeCloneMap.count(CF.FuncClone))
6416 return CF.FuncClone;
6419 "Expected an available func clone for this callsite clone");
6436 std::map<FuncInfo, ContextNode *> FuncCloneToNewCallsiteCloneMap;
6437 FuncInfo FuncCloneAssignedToCurCallsiteClone;
6441 auto CloneCallerEdges = Clone->CallerEdges;
6442 for (
auto &
Edge : CloneCallerEdges) {
6446 if (
Edge->isRemoved())
6449 if (!
Edge->Caller->hasCall())
6453 if (CallsiteToCalleeFuncCloneMap.
count(
Edge->Caller)) {
6454 FuncInfo FuncCloneCalledByCaller =
6455 CallsiteToCalleeFuncCloneMap[
Edge->Caller];
6465 if ((FuncCloneToCurNodeCloneMap.count(FuncCloneCalledByCaller) &&
6466 FuncCloneToCurNodeCloneMap[FuncCloneCalledByCaller] !=
6474 (FuncCloneAssignedToCurCallsiteClone &&
6475 FuncCloneAssignedToCurCallsiteClone !=
6476 FuncCloneCalledByCaller)) {
6491 if (FuncCloneToNewCallsiteCloneMap.count(
6492 FuncCloneCalledByCaller)) {
6493 ContextNode *NewClone =
6494 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller];
6495 moveEdgeToExistingCalleeClone(
Edge, NewClone);
6497 removeNoneTypeCalleeEdges(NewClone);
6500 ContextNode *NewClone = MoveEdgeToNewCalleeCloneAndSetUp(
Edge);
6501 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller] =
6504 ClonesWorklist.push_back(NewClone);
6508 removeNoneTypeCalleeEdges(Clone);
6516 if (!FuncCloneAssignedToCurCallsiteClone) {
6517 FuncCloneAssignedToCurCallsiteClone = FuncCloneCalledByCaller;
6519 AssignCallsiteCloneToFuncClone(
6520 FuncCloneCalledByCaller,
Call, Clone,
6521 AllocationCallToContextNodeMap.count(
Call));
6525 assert(FuncCloneAssignedToCurCallsiteClone ==
6526 FuncCloneCalledByCaller);
6535 if (!FuncCloneAssignedToCurCallsiteClone) {
6536 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
6537 assert(FuncCloneAssignedToCurCallsiteClone);
6539 AssignCallsiteCloneToFuncClone(
6540 FuncCloneAssignedToCurCallsiteClone,
Call, Clone,
6541 AllocationCallToContextNodeMap.count(
Call));
6543 assert(FuncCloneToCurNodeCloneMap
6544 [FuncCloneAssignedToCurCallsiteClone] == Clone);
6546 RecordCalleeFuncOfCallsite(
Edge->Caller,
6547 FuncCloneAssignedToCurCallsiteClone);
6567 if (!FuncCloneAssignedToCurCallsiteClone) {
6568 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
6569 assert(FuncCloneAssignedToCurCallsiteClone &&
6570 "No available func clone for this callsite clone");
6571 AssignCallsiteCloneToFuncClone(
6572 FuncCloneAssignedToCurCallsiteClone,
Call, Clone,
6573 AllocationCallToContextNodeMap.contains(
Call));
6576 assignImplicitCallers(Node, TrimmedContextIds,
6577 CallsiteToCalleeFuncCloneMap,
6578 FuncCloneToCurNodeCloneMap, ImplicitSources);
6581 for (
const auto &PE :
Node->CalleeEdges)
6583 for (
const auto &CE :
Node->CallerEdges)
6585 for (
auto *Clone :
Node->Clones) {
6587 for (
const auto &PE : Clone->CalleeEdges)
6589 for (
const auto &CE : Clone->CallerEdges)
6596 FuncToNumClones[
Func] = std::max<unsigned>(1, FuncCloneInfos.size());
6597 if (FuncCloneInfos.size() < 2)
6603 for (
auto &
Call : CallsWithMetadata) {
6604 ContextNode *
Node = getNodeForInst(
Call);
6605 if (!Node || !
Node->hasCall() ||
Node->emptyContextIds())
6610 DenseMap<unsigned, const ContextNode *> FuncCloneToNodeClone;
6611 FuncCloneToNodeClone[
Node->Call.cloneNo()] =
Node;
6619 for (
auto *
C :
Node->Clones)
6620 if (!
C->emptyContextIds() ||
6621 !ImplicitSources.contains({Node, C->Call.cloneNo()}))
6622 FuncCloneToNodeClone[
C->Call.cloneNo()] =
C;
6625 if (FuncCloneToNodeClone.
size() >= FuncCloneInfos.size())
6628 for (
auto &FC : FuncCloneInfos) {
6629 unsigned I =
FC.FuncClone.cloneNo();
6632 if (
I == 0 || FuncCloneToNodeClone.
contains(
I)) {
6640 auto &
Info = UnassignedCallClones[
Node][
I];
6641 auto &CallVector =
Info.Calls;
6642 for (
unsigned P =
I;;
P = FuncCloneParent[
P]) {
6643 if (
auto It = ImplicitSources.find({Node, P});
6644 It != ImplicitSources.end()) {
6645 Info.Source = resolveImplicitSource(Node, It->second);
6648 if (
auto It = FuncCloneToNodeClone.
find(
P);
6649 It != FuncCloneToNodeClone.
end()) {
6650 Info.Source = It->second;
6656 DenseMap<CallInfo, CallInfo> &CallMap =
FC.CallMap;
6657 if (
auto It = CallMap.
find(
Call); It != CallMap.
end()) {
6658 CallInfo CallClone = It->second;
6659 CallVector.push_back(CallClone);
6663 assert(
false &&
"Expected to find call in CallMap");
6669 for (
const CallInfo &OrigMatchingCall :
6670 OrigNodeToOrigCalls[Node].MatchingCalls) {
6671 if (
auto It = CallMap.
find(OrigMatchingCall); It != CallMap.
end()) {
6672 CallInfo CallClone = It->second;
6673 CallVector.push_back(CallClone);
6677 assert(
false &&
"Expected to find call in CallMap");
6685 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
6687 auto UpdateCalls = [&](ContextNode *
Node,
6688 DenseSet<const ContextNode *> &Visited,
6689 auto &&UpdateCalls) {
6690 auto Inserted = Visited.insert(Node);
6694 for (
auto *Clone :
Node->Clones)
6695 UpdateCalls(Clone, Visited, UpdateCalls);
6697 for (
auto &
Edge :
Node->CallerEdges)
6698 UpdateCalls(
Edge->Caller, Visited, UpdateCalls);
6702 if (!
Node->hasCall() ||
Node->emptyContextIds())
6708 auto GetUnassignedCallClones = [&](ContextNode *
Node) {
6711 auto UnassignedIt = UnassignedCallClones.
find(Node);
6712 if (UnassignedIt == UnassignedCallClones.
end())
6714 DenseSet<unsigned> NodeCallClones;
6715 for (
auto *
C :
Node->Clones)
6716 if (!
C->emptyContextIds())
6717 NodeCallClones.
insert(
C->Call.cloneNo());
6718 for (
auto &[CloneNo, Info] : UnassignedIt->second) {
6722 if (NodeCallClones.
contains(CloneNo))
6729 if (
Node->IsAllocation) {
6730 auto GetAllocTypeToUse = [&](
const ContextNode *
Node) {
6731 auto AT = allocTypeToUse(
Node->AllocTypes);
6743 !ContextIdToContextSizeInfos.
empty()) {
6746 for (
auto Id :
Node->getContextIds()) {
6747 auto TypeI = ContextIdToAllocationType.
find(Id);
6748 assert(TypeI != ContextIdToAllocationType.
end());
6749 auto CSI = ContextIdToContextSizeInfos.
find(Id);
6750 if (CSI != ContextIdToContextSizeInfos.
end()) {
6751 for (
auto &Info : CSI->second) {
6753 if (TypeI->second == AllocationType::Cold)
6754 TotalCold +=
Info.TotalSize;
6759 AT = AllocationType::Cold;
6763 updateAllocationCall(
Node->Call, GetAllocTypeToUse(Node));
6765 OrigAllocAndCloneToNode[{
Node->getOrigNode(),
Node->Call.cloneNo()}] =
6770 for (
auto &[Source, Calls] : GetUnassignedCallClones(Node)) {
6771 auto AT = GetAllocTypeToUse(Source);
6772 for (
auto &
Call : Calls) {
6773 updateAllocationCall(
Call, AT);
6776 OrigAllocAndCloneToNode[{
Node->getOrigNode(),
Call.cloneNo()}] =
6783 auto CalleeFuncIt = CallsiteToCalleeFuncCloneMap.
find(Node);
6784 if (CalleeFuncIt != CallsiteToCalleeFuncCloneMap.
end()) {
6785 auto &CalleeFunc = CalleeFuncIt->second;
6786 updateCall(
Node->Call, CalleeFunc);
6788 OrigNodeAndCloneToCalleeClone[{
6789 Node->getOrigNode(),
Node->Call.cloneNo()}] = CalleeFunc.cloneNo();
6791 for (
auto &
Call :
Node->MatchingCalls)
6792 updateCall(
Call, CalleeFunc);
6798 for (
auto &[Source, Calls] : GetUnassignedCallClones(Node)) {
6799 auto It = CallsiteToCalleeFuncCloneMap.
find(Source);
6801 if (It == CallsiteToCalleeFuncCloneMap.
end())
6803 if (It == CallsiteToCalleeFuncCloneMap.
end())
6805 for (
auto &
Call : Calls) {
6806 updateCall(
Call, It->second);
6808 OrigNodeAndCloneToCalleeClone[{
Node->getOrigNode(),
Call.cloneNo()}] =
6809 It->second.cloneNo();
6819 DenseSet<const ContextNode *> Visited;
6820 for (
auto &Entry : AllocationCallToContextNodeMap)
6821 UpdateCalls(
Entry.second, Visited, UpdateCalls);
6843 for (
auto [Index, SN] :
enumerate(FS->callsites())) {
6848 SN.Clones.size() >
I &&
6849 "Callsite summary has fewer entries than other summaries in function");
6850 if (SN.Clones.size() <=
I || !SN.Clones[
I])
6852 AddRecord(
'c', Index, SN.Clones[
I]);
6855 for (
auto [Index, AN] :
enumerate(FS->allocs())) {
6859 assert(AN.Versions.size() >
I &&
6860 "Alloc summary has fewer entries than other summaries in function");
6861 if (AN.Versions.size() <=
I ||
6864 AddRecord(
'a', Index, AN.Versions[
I]);
6873 for (
auto &SN : FS->callsites()) {
6874 assert(SN.Clones.size() >
I && SN.Clones.size() > J &&
6875 "Callsite summary has fewer entries than other summaries in "
6877 if (SN.Clones[
I] != SN.Clones[J])
6880 for (
auto &AN : FS->allocs()) {
6881 assert(AN.Versions.size() >
I && AN.Versions.size() > J &&
6882 "Alloc summary has fewer entries than other summaries in function");
6883 if (AN.Versions[
I] != AN.Versions[J])
6899 NewGV->takeName(DeclGV);
6906 auto CloneFuncAliases = [&](
Function *NewF,
unsigned I) {
6907 if (!FuncToAliasMap.count(&
F))
6909 for (
auto *
A : FuncToAliasMap[&
F]) {
6911 auto *PrevA = M.getNamedAlias(AliasName);
6913 A->getType()->getPointerAddressSpace(),
6914 A->getLinkage(), AliasName, NewF);
6915 NewA->copyAttributesFrom(
A);
6917 TakeDeclNameAndReplace(PrevA, NewA);
6926 FunctionsClonedThinBackend++;
6943 for (
unsigned I = 1;
I < NumClones;
I++) {
6944 VMaps.
emplace_back(std::make_unique<ValueToValueMapTy>());
6950 if (
auto It = HashToFunc.
find(Hash); It != HashToFunc.
end()) {
6951 FunctionCloneDuplicatesThinBackend++;
6952 auto [Func, OrigI] = It->second;
6954 "Duplicate clone hash collision");
6955 if (Func->hasAvailableExternallyLinkage()) {
6961 auto Decl = M.getOrInsertFunction(Name, Func->getFunctionType());
6963 <<
"created clone decl " <<
ore::NV(
"Decl", Decl.getCallee()));
6966 auto *PrevF = M.getFunction(Name);
6969 TakeDeclNameAndReplace(PrevF, Alias);
6971 <<
"created clone alias " <<
ore::NV(
"Alias", Alias));
6974 CloneFuncAliases(Func,
I);
6978 HashToFunc[Hash] = {NewF,
I};
6979 FunctionClonesThinBackend++;
6981 NewF->
setMetadata(LLVMContext::MD_kcfi_type,
nullptr);
6984 for (
auto &BB : *NewF) {
6985 for (
auto &Inst : BB) {
6986 Inst.setMetadata(LLVMContext::MD_memprof,
nullptr);
6987 Inst.setMetadata(LLVMContext::MD_callsite,
nullptr);
6990 auto *PrevF = M.getFunction(Name);
6992 TakeDeclNameAndReplace(PrevF, NewF);
6994 NewF->setName(Name);
6997 <<
"created clone " <<
ore::NV(
"NewFunction", NewF));
7000 CloneFuncAliases(NewF,
I);
7009static std::optional<GlobalValue::GUID>
7011 if (
auto *MD =
F.getMetadata(
"thinlto_alias_guid"))
7013 return std::nullopt;
7020 const Function *CallingFunc =
nullptr) {
7024 assert(AliasVI &&
"Expected ValueInfo for imported alias GUID");
7047 MDNode *SrcFileMD = GO ? GO->getMetadata(
"thinlto_src_file") :
nullptr;
7057 SrcFileMD = CallingFunc->getMetadata(
"thinlto_src_file");
7064 StringRef SrcFile = M.getSourceFileName();
7101 &OrigNameGUIDToTailCallCallsite,
7105 auto End = MapTailCallCalleeVIToCallsite.
end();
7109 auto It = MapTailCallCalleeVIToCallsite.
find(VI);
7118 auto It = MapTailCallCalleeVIToCallsite.
find(LocalVI);
7128 if (!OrigNameGUIDToTailCallCallsite) {
7131 OrigNameGUIDToTailCallCallsite.emplace();
7132 for (
const auto &[CalleeVI, Callsite] : MapTailCallCalleeVIToCallsite) {
7141 AliasVIToGV.emplace();
7147 AliasVIToGV->try_emplace(VI, &
A);
7150 Callee = AliasVIToGV->lookup(CalleeVI);
7156 auto [It, Inserted] = OrigNameGUIDToTailCallCallsite->try_emplace(
7160 if (!Inserted && It->second != &Callsite)
7161 It->second =
nullptr;
7164 return OrigNameGUIDToTailCallCallsite->lookup(CandidateGUID);
7167bool MemProfContextDisambiguation::initializeIndirectCallPromotionInfo(
7169 ICallAnalysis = std::make_unique<ICallPromotionAnalysis>();
7170 Symtab = std::make_unique<InstrProfSymtab>();
7188 AliaseeGUIDToImportedAlias.reset();
7189 if (
Error E = Symtab->create(M,
true,
false,
7191 std::string SymtabFailure =
toString(std::move(
E));
7192 M.getContext().emitError(
"Failed to create symtab: " + SymtabFailure);
7205 auto MIBIter = AllocNode.
MIBs.begin();
7206 for (
auto &MDOp : MemProfMD->
operands()) {
7215 if (MIBIter->StackIdIndices.empty()) {
7219 auto StackIdIndexIter = MIBIter->StackIdIndices.begin();
7224 auto ContextIterBegin =
7228 (ContextIterBegin != StackContext.
end() && *ContextIterBegin == 0) ? 1
7230 for (
auto ContextIter = ContextIterBegin; ContextIter != StackContext.
end();
7235 if (LastStackContextId == *ContextIter)
7237 LastStackContextId = *ContextIter;
7238 assert(StackIdIndexIter != MIBIter->StackIdIndices.end());
7248bool MemProfContextDisambiguation::applyImport(
Module &M) {
7255 std::map<const Function *, SmallPtrSet<const GlobalAlias *, 1>>
7257 for (
auto &
A :
M.aliases()) {
7258 auto *Aliasee =
A.getAliaseeObject();
7260 FuncToAliasMap[
F].insert(&
A);
7263 if (!initializeIndirectCallPromotionInfo(M))
7269 std::optional<DenseMap<ValueInfo, const GlobalAlias *>> AliasVIToGV;
7275 OptimizationRemarkEmitter ORE(&
F);
7278 bool ClonesCreated =
false;
7279 unsigned NumClonesCreated = 0;
7280 auto CloneFuncIfNeeded = [&](
unsigned NumClones, FunctionSummary *
FS) {
7290 if (ClonesCreated) {
7291 assert(NumClonesCreated == NumClones);
7298 ClonesCreated =
true;
7299 NumClonesCreated = NumClones;
7302 auto CloneCallsite = [&](
const CallsiteInfo &StackNode, CallBase *CB,
7303 Function *CalledFunction, FunctionSummary *
FS) {
7305 CloneFuncIfNeeded(StackNode.
Clones.
size(), FS);
7317 if (CalledFunction != CB->getCalledOperand() &&
7318 (!GA || CalledFunction != GA->getAliaseeObject())) {
7319 SkippedCallsCloning++;
7325 auto CalleeOrigName = CalledFunction->getName();
7326 for (
unsigned J = 0; J < StackNode.
Clones.
size(); J++) {
7329 if (J > 0 && VMaps[J - 1]->
empty())
7333 if (!StackNode.
Clones[J])
7335 auto NewF =
M.getOrInsertFunction(
7337 CalledFunction->getFunctionType());
7351 ORE.emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofCall", CBClone)
7352 <<
ore::NV(
"Call", CBClone) <<
" in clone "
7354 <<
" assigned to call function clone "
7355 <<
ore::NV(
"Callee", NewF.getCallee()));
7369 ImportSummary->findSummaryInModule(TheFnVI,
M.getModuleIdentifier());
7373 auto SrcModuleMD =
F.getMetadata(
"thinlto_src_module");
7375 "enable-import-metadata is needed to emit thinlto_src_module");
7376 StringRef SrcModule =
7379 if (GVS->modulePath() == SrcModule) {
7380 GVSummary = GVS.get();
7384 assert(GVSummary && GVSummary->modulePath() == SrcModule);
7394 if (
FS->allocs().empty() &&
FS->callsites().empty())
7397 auto SI =
FS->callsites().begin();
7398 auto AI =
FS->allocs().begin();
7403 DenseMap<ValueInfo, CallsiteInfo> MapTailCallCalleeVIToCallsite;
7406 for (
auto CallsiteIt =
FS->callsites().rbegin();
7407 CallsiteIt !=
FS->callsites().rend(); CallsiteIt++) {
7408 auto &Callsite = *CallsiteIt;
7412 if (!Callsite.StackIdIndices.empty())
7414 MapTailCallCalleeVIToCallsite.
insert({Callsite.Callee, Callsite});
7418 std::optional<DenseMap<uint64_t, const CallsiteInfo *>>
7419 OrigNameGUIDToTailCallCallsite;
7427 for (
auto &BB :
F) {
7428 for (
auto &
I : BB) {
7434 auto *CalledValue = CB->getCalledOperand();
7435 auto *CalledFunction = CB->getCalledFunction();
7436 if (CalledValue && !CalledFunction) {
7437 CalledValue = CalledValue->stripPointerCasts();
7444 assert(!CalledFunction &&
7445 "Expected null called function in callsite for alias");
7449 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
7450 I.getMetadata(LLVMContext::MD_callsite));
7451 auto *MemProfMD =
I.getMetadata(LLVMContext::MD_memprof);
7457 if (CB->getAttributes().hasFnAttr(
"memprof") && !MemProfMD) {
7458 CB->getAttributes().getFnAttr(
"memprof").getValueAsString() ==
"cold"
7459 ? AllocTypeColdThinBackend++
7460 : AllocTypeNotColdThinBackend++;
7461 OrigAllocsThinBackend++;
7462 AllocVersionsThinBackend++;
7463 if (!MaxAllocVersionsThinBackend)
7464 MaxAllocVersionsThinBackend = 1;
7471 auto &AllocNode = *(AI++);
7479 CloneFuncIfNeeded(AllocNode.Versions.size(), FS);
7481 OrigAllocsThinBackend++;
7482 AllocVersionsThinBackend += AllocNode.Versions.size();
7483 if (MaxAllocVersionsThinBackend < AllocNode.Versions.size())
7484 MaxAllocVersionsThinBackend = AllocNode.Versions.size();
7496 if (AllocNode.Versions.size() == 1 &&
7498 UnclonableAllocsThinBackend++;
7501 for (
unsigned J = 0; J < AllocNode.Versions.size(); J++) {
7504 if (J > 0 && VMaps[J - 1]->
empty())
7507 if (AllocNode.Versions[J] == (uint8_t)AllocationType::None)
7515 AllocTy = AllocationType::NotCold;
7517 if (AllocTy == AllocationType::Cold)
7518 AllocTypeColdThinBackend++;
7519 else if (IsAmbiguous)
7520 AllocTypeAmbiguousThinBackend++;
7522 AllocTypeNotColdThinBackend++;
7542 ORE.emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofAttribute", CBClone)
7543 <<
ore::NV(
"AllocationCall", CBClone) <<
" in clone "
7545 <<
" marked with memprof allocation attribute "
7546 <<
ore::NV(
"Attribute", AllocTypeString));
7548 }
else if (!CallsiteContext.empty()) {
7549 if (!CalledFunction) {
7553 assert(!CI || !CI->isInlineAsm());
7563 auto NumClones = recordICPInfo(
7565 [&](
const InstrProfValueData &Candidate) {
7566 assert(SI !=
FS->callsites().end());
7568 auto CalleeValueInfo =
7569 ImportSummary->getValueInfo(Candidate.Value);
7571 ImportSummary->getGUIDFromOriginalID(Candidate.Value);
7579 assert(!CalleeValueInfo ||
SI->Callee == CalleeValueInfo ||
7580 (
SI->Callee &&
SI->Callee.getGUID() == LocalGUID));
7589 CloneFuncIfNeeded(NumClones, FS);
7594 assert(SI !=
FS->callsites().end());
7595 auto &StackNode = *(
SI++);
7601 for (
auto StackId : CallsiteContext) {
7603 assert(ImportSummary->getStackIdAtIndex(*StackIdIndexIter) ==
7609 CloneCallsite(StackNode, CB, CalledFunction, FS);
7611 }
else if (CB->isTailCall() && CalledFunction) {
7616 if (CalleeVI && MapTailCallCalleeVIToCallsite.
count(CalleeVI)) {
7617 auto Callsite = MapTailCallCalleeVIToCallsite.
find(CalleeVI);
7618 assert(Callsite != MapTailCallCalleeVIToCallsite.
end());
7619 CloneCallsite(Callsite->second, CB, CalledFunction, FS);
7621 }
else if (CB->isTailCall() && !CalledFunction &&
7622 !MapTailCallCalleeVIToCallsite.
empty()) {
7628 auto PrevNumICallAnalysisInfo = ICallAnalysisInfo.
size();
7629 auto NumClones = recordICPInfo(
7631 [&](
const InstrProfValueData &Candidate) {
7633 Candidate.Value, MapTailCallCalleeVIToCallsite,
7634 OrigNameGUIDToTailCallCallsite, AliasVIToGV, M,
7635 ImportSummary, *Symtab);
7638 if (ICallAnalysisInfo.
size() > PrevNumICallAnalysisInfo)
7639 IndirectTailCallsRecordedForICPThinBackend++;
7641 CloneFuncIfNeeded(NumClones, FS);
7647 performICP(M, VMaps, ICallAnalysisInfo, ORE);
7657 for (
auto &BB :
F) {
7658 for (
auto &
I : BB) {
7661 I.setMetadata(LLVMContext::MD_memprof,
nullptr);
7662 I.setMetadata(LLVMContext::MD_callsite,
nullptr);
7670unsigned MemProfContextDisambiguation::recordICPInfo(
7672 function_ref<
const CallsiteInfo *(
const InstrProfValueData &)> GetCallsite,
7675 uint32_t NumCandidates;
7677 auto CandidateProfileData =
7678 ICallAnalysis->getPromotionCandidatesForInstruction(
7679 CB, TotalCount, NumCandidates,
7681 if (CandidateProfileData.empty())
7687 bool ICPNeeded =
false;
7688 unsigned NumClones = 0;
7690 for (
const auto &Candidate : CandidateProfileData) {
7691 const CallsiteInfo *Callsite = GetCallsite(Candidate);
7699 [](
unsigned CloneNo) { return CloneNo != 0; });
7709 ICallAnalysisInfo.
push_back({CB, CandidateProfileData.vec(), NumCandidates,
7710 TotalCount, NumClones, std::move(Callsites)});
7714void MemProfContextDisambiguation::performICP(
7717 OptimizationRemarkEmitter &ORE) {
7724 for (
auto &Info : ICallAnalysisInfo) {
7726 auto TotalCount =
Info.TotalCount;
7727 unsigned NumClones =
Info.NumClones;
7730 assert(
Info.CandidateProfileData.size() ==
Info.Callsites.size());
7731 for (
unsigned I = 0;
I <
Info.CandidateProfileData.size();
I++) {
7732 auto &Candidate =
Info.CandidateProfileData[
I];
7733 const CallsiteInfo *StackNode =
Info.Callsites[
I];
7741 Function *TargetFunction = Symtab->getFunction(Candidate.Value);
7752 if (!TargetFunction && StackNode && StackNode->
Callee &&
7763 if (!TargetFunction) {
7764 if (!AliaseeGUIDToImportedAlias) {
7765 AliaseeGUIDToImportedAlias.emplace();
7769 if (
auto AliaseeGUID = Fn.getGUIDIfAssigned())
7770 AliaseeGUIDToImportedAlias->try_emplace(*AliaseeGUID, &Fn);
7773 TargetFunction = AliaseeGUIDToImportedAlias->lookup(Candidate.Value);
7774 if (!TargetFunction && StackNode && StackNode->
Callee &&
7777 AliaseeGUIDToImportedAlias->lookup(StackNode->
Callee.
getGUID());
7779 if (TargetFunction ==
nullptr ||
7787 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnableToFindTarget", CB)
7788 <<
"Memprof cannot promote indirect call: target with md5sum "
7789 <<
ore::NV(
"target md5sum", Candidate.Value) <<
" not found";
7794 RemainingCandidates.
push_back(Candidate);
7799 const char *Reason =
nullptr;
7802 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnableToPromote", CB)
7803 <<
"Memprof cannot promote indirect call to "
7804 <<
ore::NV(
"TargetFunction", TargetFunction)
7805 <<
" with count of " <<
ore::NV(
"TotalCount", TotalCount)
7808 RemainingCandidates.
push_back(Candidate);
7817 CallBase *CBClone = CB;
7818 for (
unsigned J = 0; J < NumClones; J++) {
7821 if (J > 0 && VMaps[J - 1]->
empty())
7831 TotalCount, isSamplePGO, &ORE);
7832 auto *TargetToUse = TargetFunction;
7835 if (StackNode && StackNode->
Clones[J]) {
7854 <<
ore::NV(
"Call", CBClone) <<
" in clone "
7856 <<
" promoted and assigned to call function clone "
7857 <<
ore::NV(
"Callee", TargetToUse));
7861 TotalCount -= Candidate.Count;
7865 CallBase *CBClone = CB;
7866 for (
unsigned J = 0; J < NumClones; J++) {
7869 if (J > 0 && VMaps[J - 1]->
empty())
7875 CBClone->
setMetadata(LLVMContext::MD_prof,
nullptr);
7878 if (TotalCount != 0)
7880 IPVK_IndirectCallTarget,
Info.NumCandidates);
7885template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
7886bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::process(
7887 function_ref<
void(StringRef, StringRef,
const Twine &)> EmitRemark,
7888 bool AllowExtraAnalysis) {
7890 dbgs() <<
"CCG before cloning:\n";
7894 exportToDot(
"postbuild");
7903 capturePreCloningContextInfo();
7912 dbgs() <<
"CCG after cloning:\n";
7916 exportToDot(
"cloned");
7918 bool Changed = assignFunctions();
7921 dbgs() <<
"CCG after assigning function clones:\n";
7925 exportToDot(
"clonefuncassign");
7934 populateFunctionsWithCallers();
7935 printTotalSizes(
errs(), EmitRemark);
7941bool MemProfContextDisambiguation::processModule(
7943 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter) {
7948 return applyImport(M);
7961 ModuleCallsiteContextGraph CCG(M, OREGetter);
7964 return CCG.process();
7969 : ImportSummary(Summary), isSamplePGO(isSamplePGO) {
7974 "-memprof-dot-scope=alloc requires -memprof-dot-alloc-id");
7978 "-memprof-dot-scope=context requires -memprof-dot-context-id");
7982 "-memprof-dot-scope=all can't have both -memprof-dot-alloc-id and "
7983 "-memprof-dot-context-id");
7984 if (ImportSummary) {
7994 auto ReadSummaryFile =
7996 if (!ReadSummaryFile) {
8003 if (!ImportSummaryForTestingOrErr) {
8009 ImportSummaryForTesting = std::move(*ImportSummaryForTestingOrErr);
8010 ImportSummary = ImportSummaryForTesting.get();
8019 if (!processModule(M, OREGetter))
8042 for (
auto &
I : Index) {
8043 auto VI = Index.getValueInfo(
I);
8044 for (
auto &S : VI.getSummaryList()) {
8048 !isPrevailing(VI.getGUID(), S.get()))
8051 if (!FS || FS->callsites().empty())
8053 CalleeToEdge.
clear();
8054 for (
auto &CI : FS->callsites()) {
8055 if (!CI.Callee ||
llvm::all_of(CI.Clones, [](
unsigned CloneNo) {
8056 return CloneNo == 0;
8063 NumClonedCalleeCallsites++;
8065 if (CalleeToEdge.
empty())
8066 for (
auto &[CalleeVI, Edge] : FS->mutableCalls())
8067 CalleeToEdge[CalleeVI] = &Edge;
8068 auto It = CalleeToEdge.
find(CI.Callee);
8069 if (It == CalleeToEdge.
end())
8076 if (!Edge->hasIndirectCall())
8078 NumClonedCalleeIndirectCallsites++;
8079 if (!Edge->requiresDeclImport()) {
8080 Edge->setRequiresDeclImport(
true);
8081 NumClonedCalleeEdgesMarkedRequiresDeclImport++;
8102 bool AllowExtraAnalysis =
8107 IndexCallsiteContextGraph CCG(Index, isPrevailing);
8108 Changed = CCG.process(EmitRemark, AllowExtraAnalysis);
8131 for (
auto &BB :
F) {
8132 for (
auto &
I : BB) {
8136 if (CI->hasFnAttr(
"memprof")) {
8137 CI->removeFnAttr(
"memprof");
8140 if (!CI->hasMetadata(LLVMContext::MD_callsite)) {
8141 assert(!CI->hasMetadata(LLVMContext::MD_memprof));
8147 CI->setMetadata(LLVMContext::MD_memprof,
nullptr);
8148 CI->setMetadata(LLVMContext::MD_callsite,
nullptr);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static cl::opt< unsigned > TailCallSearchDepth("memprof-tail-call-search-depth", cl::init(5), cl::Hidden, cl::desc("Max depth to recursively search for missing " "frames through tail calls."))
uint64_t ComputeHash(const FunctionSummary *FS, unsigned I)
static cl::opt< DotScope > DotGraphScope("memprof-dot-scope", cl::desc("Scope of graph to export to dot"), cl::Hidden, cl::init(DotScope::All), cl::values(clEnumValN(DotScope::All, "all", "Export full callsite graph"), clEnumValN(DotScope::Alloc, "alloc", "Export only nodes with contexts feeding given " "-memprof-dot-alloc-id"), clEnumValN(DotScope::Context, "context", "Export only nodes with given -memprof-dot-context-id")))
static cl::opt< bool > DoMergeIteration("memprof-merge-iteration", cl::init(true), cl::Hidden, cl::desc("Iteratively apply merging on a node to catch new callers"))
static cl::opt< unsigned > AllocIdForDot("memprof-dot-alloc-id", cl::init(0), cl::Hidden, cl::desc("Id of alloc to export if -memprof-dot-scope=alloc " "or to highlight if -memprof-dot-scope=all"))
static bool clonesHaveSameVersions(const FunctionSummary *FS, unsigned I, unsigned J)
static std::optional< GlobalValue::GUID > getImportedAliasGUID(const Function &F)
static void updateClonedCalleeEdgesForImport(ModuleSummaryIndex &Index, llvm::function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static cl::opt< unsigned > ContextIdForDot("memprof-dot-context-id", cl::init(0), cl::Hidden, cl::desc("Id of context to export if -memprof-dot-scope=context or to " "highlight otherwise"))
static cl::opt< bool > ExportToDot("memprof-export-to-dot", cl::init(false), cl::Hidden, cl::desc("Export graph to dot files."))
static ValueInfo findValueInfoForGV(const GlobalValue &GV, const Module &M, const ModuleSummaryIndex *ImportSummary, const Function *CallingFunc=nullptr)
static void checkEdge(const std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > &Edge)
static cl::opt< bool > AllowRecursiveCallsites("memprof-allow-recursive-callsites", cl::init(true), cl::Hidden, cl::desc("Allow cloning of callsites involved in recursive cycles"))
bool checkColdOrNotCold(uint8_t AllocType)
static cl::opt< bool > CloneRecursiveContexts("memprof-clone-recursive-contexts", cl::init(true), cl::Hidden, cl::desc("Allow cloning of contexts through recursive cycles"))
static std::string getAllocTypeString(uint8_t AllocTypes)
static cl::opt< bool > IndirectTailCallSearch("memprof-indirect-tail-call-search", cl::init(true), cl::Hidden, cl::desc("Search for missing frames through indirect tail calls to their " "profiled targets (ThinLTO)."))
bool DOTGraphTraits< constCallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * >::DoHighlight
static cl::opt< bool > AssignTrimmedInlinedContexts("memprof-assign-trimmed-inlined-contexts", cl::init(true), cl::Hidden, cl::desc("Assign contexts trimmed within a call's inlined stack id " "sequence to that call"))
static unsigned getMemProfCloneNum(const Function &F)
static cl::opt< unsigned > MemProfICPNoInlineThreshold("memprof-icp-noinline-threshold", cl::init(0), cl::Hidden, cl::desc("Minimum absolute count for promoted target to be inlinable"))
static SmallVector< std::unique_ptr< ValueToValueMapTy >, 4 > createFunctionClones(Function &F, unsigned NumClones, Module &M, OptimizationRemarkEmitter &ORE, std::map< const Function *, SmallPtrSet< const GlobalAlias *, 1 > > &FuncToAliasMap, FunctionSummary *FS)
static cl::opt< bool > VerifyCCG("memprof-verify-ccg", cl::init(false), cl::Hidden, cl::desc("Perform verification checks on CallingContextGraph."))
static void checkNode(const ContextNode< DerivedCCG, FuncTy, CallTy > *Node, bool CheckEdges=true)
static cl::opt< bool > MergeClones("memprof-merge-clones", cl::init(true), cl::Hidden, cl::desc("Merge clones before assigning functions"))
static std::string getMemProfFuncName(Twine Base, unsigned CloneNo)
static cl::opt< std::string > MemProfImportSummary("memprof-import-summary", cl::desc("Import summary to use for testing the ThinLTO backend via opt"), cl::Hidden)
static const CallsiteInfo * findIndirectTailCallCallsite(uint64_t CandidateGUID, const DenseMap< ValueInfo, CallsiteInfo > &MapTailCallCalleeVIToCallsite, std::optional< DenseMap< uint64_t, const CallsiteInfo * > > &OrigNameGUIDToTailCallCallsite, std::optional< DenseMap< ValueInfo, const GlobalAlias * > > &AliasVIToGV, const Module &M, const ModuleSummaryIndex *ImportSummary, InstrProfSymtab &Symtab)
static void updateSubprogramLinkageName(Function *NewFunc, StringRef Name)
static cl::opt< bool > AllowRecursiveContexts("memprof-allow-recursive-contexts", cl::init(true), cl::Hidden, cl::desc("Allow cloning of contexts having recursive cycles"))
static cl::opt< std::string > DotFilePathPrefix("memprof-dot-file-path-prefix", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path prefix of the MemProf dot files."))
static cl::opt< bool > VerifyNodes("memprof-verify-nodes", cl::init(false), cl::Hidden, cl::desc("Perform frequent verification checks on nodes."))
static void checkAllocContextIds(const AllocInfo &AllocNode, const MDNode *MemProfMD, const CallStack< MDNode, MDNode::op_iterator > &CallsiteContext, const ModuleSummaryIndex *ImportSummary)
static cl::opt< bool > DumpCCG("memprof-dump-ccg", cl::init(false), cl::Hidden, cl::desc("Dump CallingContextGraph to stdout after each stage."))
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...
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
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)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
ValueInfo getAliaseeVI() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
bool empty() const
Check if the array is empty.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
void setCalledOperand(Value *V)
Subprogram description. Uses SubclassData1.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
bool erase(const KeyT &Val)
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Function summary information to aid decisions and implementation of importing.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
DISubprogram * getSubprogram() const
Get the attached subprogram.
const Function & getFunction() const
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...
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.
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...
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.
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
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....
bool isWeakForLinker() const
@ InternalLinkage
Rename collisions when linking (static functions).
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Function * getFunction(uint64_t FuncMD5Hash) const
Return function from the name's md5 hash. Return nullptr if not found.
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.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
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.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
This class implements a map that also provides access to all stored values in a deterministic order.
size_type count(const KeyT &Key) const
LLVM_ABI MemProfContextDisambiguation(const ModuleSummaryIndex *Summary=nullptr, bool isSamplePGO=false)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
uint64_t getStackIdAtIndex(unsigned Index) const
GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const
Return the GUID for OriginalId in the OidGuidMap.
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
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.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
A class that wrap the SHA1 algorithm.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
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().
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.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
std::pair< StringRef, StringRef > rsplit(StringRef Separator) const
Split into two substrings around the last occurrence of a separator string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
bool erase(const ValueT &V)
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CE
Windows NT (Windows on ARM)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
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)
NodeAddr< NodeBase * > Node
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
uint64_t read64le(const void *P)
void write32le(void *P, uint32_t V)
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.
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.
void stable_sort(R &&Range)
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.
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,...
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.
LLVM_ABI bool mayHaveMemprofSummary(const CallBase *CB)
Returns true if the instruction could have memprof metadata, used to ensure consistency between summa...
constexpr from_range_t from_range
static cl::opt< bool > MemProfRequireDefinitionForPromotion("memprof-require-definition-for-promotion", cl::init(false), cl::Hidden, cl::desc("Require target function definition when promoting indirect calls"))
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
cl::opt< unsigned > MemProfTopNImportant("memprof-top-n-important", cl::init(10), cl::Hidden, cl::desc("Number of largest cold contexts to consider important"))
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
static cl::opt< bool > MemProfImportClonedIndirectTargets("memprof-import-cloned-indirect-targets", cl::init(true), cl::Hidden, cl::desc("Import at least a declaration of the indirect call targets of " "callsites assigned to call a cloned callee (needed for MemProf " "ICP in the ThinLTO backend)"))
void set_subtract(S1Ty &S1, const S2Ty &S2)
set_subtract(A, B) - Compute A := A - B
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool isa_and_nonnull(const Y &Val)
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
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)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
static cl::opt< bool > MemProfReportHintedSizesDetail("memprof-report-hinted-sizes-detail", cl::init(false), cl::Hidden, cl::desc("Append post-cloning call path and matching details to each " "-memprof-report-hinted-sizes line"))
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
cl::opt< bool > SupportsHotColdNew
Indicate we are linking with an allocator that supports hot/cold operator new interfaces.
static cl::opt< unsigned > MemProfReportHintedSizesDetailMaxPathLen("memprof-report-hinted-sizes-detail-max-path-len", cl::init(7), cl::Hidden, cl::desc("Maximum number of functions printed in full for a post-cloning " "call path in the -memprof-report-hinted-sizes-detail suffix; " "longer paths are elided in the middle"))
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
S1Ty set_intersection(const S1Ty &S1, const S2Ty &S2)
set_intersection(A, B) - Return A ^ B
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getMaxSummaryIndirectEdges(const LLVMContext &C)
Return -module-summary-max-indirect-edges.
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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>.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
constexpr StringLiteral MemProfCloneSuffix
@ End
Run the machine verifier once, at the end of the pipeline.
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.
cl::opt< bool > MemProfFixupImportant("memprof-fixup-important", cl::init(true), cl::Hidden, cl::desc("Enables edge fixup for important contexts"))
DOTGraphTraits(bool IsSimple=false)
typename GTraits::NodeRef NodeRef
static std::string getEdgeAttributes(NodeRef, ChildIteratorType ChildIter, GraphType G)
const CallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * GraphType
typename GTraits::ChildIteratorType ChildIteratorType
static std::string getNodeAttributes(NodeRef Node, GraphType G)
static bool isNodeHidden(NodeRef Node, GraphType G)
static std::string getNodeLabel(NodeRef Node, GraphType G)
GraphTraits< GraphType > GTraits
static NodeRef getNode(const NodePtrTy &P)
static const ContextNode< DerivedCCG, FuncTy, CallTy > * GetCallee(const EdgePtrTy &P)
static ChildIteratorType child_end(NodeRef N)
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
const CallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * GraphType
const ContextNode< DerivedCCG, FuncTy, CallTy > * NodeRef
mapped_iterator< typename std::vector< NodePtrTy >::const_iterator, decltype(&getNode)> nodes_iterator
static ChildIteratorType child_begin(NodeRef N)
static NodeRef getEntryNode(GraphType G)
static nodes_iterator nodes_begin(GraphType G)
static nodes_iterator nodes_end(GraphType G)
std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > EdgePtrTy
Summary of memprof metadata on allocations.
std::vector< MIBInfo > MIBs
Class to accumulate and hold information about a callee.
Summary of memprof callsite metadata.
SmallVector< unsigned > StackIdIndices
SmallVector< unsigned > Clones
DefaultDOTGraphTraits(bool simple=false)
An information struct used to provide DenseMap with the various necessary components for a given valu...
typename GraphType::UnknownGraphTypeError NodeRef
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...