LLVM 24.0.0git
AMDGPUSplitModule.cpp
Go to the documentation of this file.
1//===- AMDGPUSplitModule.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file Implements a module splitting algorithm designed to support the
10/// FullLTO --lto-partitions option for parallel codegen.
11///
12/// The role of this module splitting pass is the same as
13/// lib/Transforms/Utils/SplitModule.cpp: load-balance the module's functions
14/// across a set of N partitions to allow for parallel codegen.
15///
16/// The similarities mostly end here, as this pass achieves load-balancing in a
17/// more elaborate fashion which is targeted towards AMDGPU modules. It can take
18/// advantage of the structure of AMDGPU modules (which are mostly
19/// self-contained) to allow for more efficient splitting without affecting
20/// codegen negatively, or causing innaccurate resource usage analysis.
21///
22/// High-level pass overview:
23/// - SplitGraph & associated classes
24/// - Graph representation of the module and of the dependencies that
25/// matter for splitting.
26/// - RecursiveSearchSplitting
27/// - Core splitting algorithm.
28/// - SplitProposal
29/// - Represents a suggested solution for splitting the input module. These
30/// solutions can be scored to determine the best one when multiple
31/// solutions are available.
32/// - Driver/pass "run" function glues everything together.
33
34#include "AMDGPUSplitModule.h"
40#include "llvm/ADT/StringRef.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalAlias.h"
46#include "llvm/IR/Instruction.h"
47#include "llvm/IR/Module.h"
49#include "llvm/IR/Value.h"
53#include "llvm/Support/Debug.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/Timer.h"
59#include <cassert>
60#include <cmath>
61#include <utility>
62
63#ifndef NDEBUG
65#endif
66
67#define DEBUG_TYPE "amdgpu-split-module"
68
69namespace llvm {
70namespace {
71
72static cl::opt<unsigned> MaxDepth(
73 "amdgpu-module-splitting-max-depth",
74 cl::desc(
75 "maximum search depth. 0 forces a greedy approach. "
76 "warning: the algorithm is up to O(2^N), where N is the max depth."),
77 cl::init(8));
78
79static cl::opt<float> LargeFnFactor(
80 "amdgpu-module-splitting-large-threshold", cl::init(2.0f), cl::Hidden,
81 cl::desc(
82 "when max depth is reached and we can no longer branch out, this "
83 "value determines if a function is worth merging into an already "
84 "existing partition to reduce code duplication. This is a factor "
85 "of the ideal partition size, e.g. 2.0 means we consider the "
86 "function for merging if its cost (including its callees) is 2x the "
87 "size of an ideal partition."));
88
89static cl::opt<float> LargeFnOverlapForMerge(
90 "amdgpu-module-splitting-merge-threshold", cl::init(0.7f), cl::Hidden,
91 cl::desc("when a function is considered for merging into a partition that "
92 "already contains some of its callees, do the merge if at least "
93 "n% of the code it can reach is already present inside the "
94 "partition; e.g. 0.7 means only merge >70%"));
95
96static cl::opt<bool> NoExternalizeGlobals(
97 "amdgpu-module-splitting-no-externalize-globals", cl::Hidden,
98 cl::desc("disables externalization of global variable with local linkage; "
99 "may cause globals to be duplicated which increases binary size"));
100
101static cl::opt<bool> NoExternalizeOnAddrTaken(
102 "amdgpu-module-splitting-no-externalize-address-taken", cl::Hidden,
103 cl::desc(
104 "disables externalization of functions whose addresses are taken"));
105
107 ModuleDotCfgOutput("amdgpu-module-splitting-print-module-dotcfg",
109 cl::desc("output file to write out the dotgraph "
110 "representation of the input module"));
111
112static cl::opt<std::string> PartitionSummariesOutput(
113 "amdgpu-module-splitting-print-partition-summaries", cl::Hidden,
114 cl::desc("output file to write out a summary of "
115 "the partitions created for each module"));
116
117#ifndef NDEBUG
118static cl::opt<bool>
119 UseLockFile("amdgpu-module-splitting-serial-execution", cl::Hidden,
120 cl::desc("use a lock file so only one process in the system "
121 "can run this pass at once. useful to avoid mangled "
122 "debug output in multithreaded environments."));
123
124static cl::opt<bool>
125 DebugProposalSearch("amdgpu-module-splitting-debug-proposal-search",
127 cl::desc("print all proposals received and whether "
128 "they were rejected or accepted"));
129#endif
130
131struct SplitModuleTimer : NamedRegionTimer {
132 SplitModuleTimer(StringRef Name, StringRef Desc)
133 : NamedRegionTimer(Name, Desc, DEBUG_TYPE, "AMDGPU Module Splitting",
135};
136
137//===----------------------------------------------------------------------===//
138// Utils
139//===----------------------------------------------------------------------===//
140
141using CostType = InstructionCost::CostType;
142using FunctionsCostMap = DenseMap<const Function *, CostType>;
143using GetTTIFn = function_ref<const TargetTransformInfo &(Function &)>;
144static constexpr unsigned InvalidPID = -1;
145
146/// \param Num numerator
147/// \param Dem denominator
148/// \returns a printable object to print (Num/Dem) using "%0.2f".
149static auto formatRatioOf(CostType Num, CostType Dem) {
150 CostType DemOr1 = Dem ? Dem : 1;
151 return format("%0.2f", (static_cast<double>(Num) / DemOr1) * 100);
152}
153
154/// Checks whether a given function is non-copyable.
155///
156/// Non-copyable functions cannot be cloned into multiple partitions, and only
157/// one copy of the function can be present across all partitions.
158///
159/// Kernel functions and external functions fall into this category. If we were
160/// to clone them, we would end up with multiple symbol definitions and a very
161/// unhappy linker.
162static bool isNonCopyable(const Function &F) {
163 return F.hasExternalLinkage() || !F.isDefinitionExact() ||
164 AMDGPU::isEntryFunctionCC(F.getCallingConv());
165}
166
167/// If \p GV has local linkage, make it external + hidden.
168static void externalize(GlobalValue &GV) {
169 if (GV.hasLocalLinkage()) {
170 GV.setLinkage(GlobalValue::ExternalLinkage);
171 GV.setVisibility(GlobalValue::HiddenVisibility);
172 }
173
174 // Unnamed entities must be named consistently between modules. setName will
175 // give a distinct name to each such entity.
176 if (!GV.hasName())
177 GV.setName("__llvmsplit_unnamed");
178}
179
180/// Cost analysis function. Calculates the cost of each function in \p M
181///
182/// \param GetTTI Abstract getter for TargetTransformInfo.
183/// \param M Module to analyze.
184/// \param CostMap[out] Resulting Function -> Cost map.
185/// \return The module's total cost.
186static CostType calculateFunctionCosts(GetTTIFn GetTTI, Module &M,
187 FunctionsCostMap &CostMap) {
188 SplitModuleTimer SMT("calculateFunctionCosts", "cost analysis");
189
190 LLVM_DEBUG(dbgs() << "[cost analysis] calculating function costs\n");
191 CostType ModuleCost = 0;
192 [[maybe_unused]] CostType KernelCost = 0;
193
194 for (auto &Fn : M) {
195 if (Fn.isDeclaration())
196 continue;
197
198 CostType FnCost = 0;
199 const auto &TTI = GetTTI(Fn);
200 for (const auto &BB : Fn) {
201 for (const auto &I : BB) {
202 auto Cost =
205 // Assume expensive if we can't tell the cost of an instruction.
206 CostType CostVal = Cost.isValid()
207 ? Cost.getValue()
209 assert((FnCost + CostVal) >= FnCost && "Overflow!");
210 FnCost += CostVal;
211 }
212 }
213
214 assert(FnCost != 0);
215
216 CostMap[&Fn] = FnCost;
217 assert((ModuleCost + FnCost) >= ModuleCost && "Overflow!");
218 ModuleCost += FnCost;
219
220 if (AMDGPU::isEntryFunctionCC(Fn.getCallingConv()))
221 KernelCost += FnCost;
222 }
223
224 if (CostMap.empty())
225 return 0;
226
227 assert(ModuleCost);
228 LLVM_DEBUG({
229 const CostType FnCost = ModuleCost - KernelCost;
230 dbgs() << " - total module cost is " << ModuleCost << ". kernels cost "
231 << "" << KernelCost << " ("
232 << format("%0.2f", (float(KernelCost) / ModuleCost) * 100)
233 << "% of the module), functions cost " << FnCost << " ("
234 << format("%0.2f", (float(FnCost) / ModuleCost) * 100)
235 << "% of the module)\n";
236 });
237
238 return ModuleCost;
239}
240
241/// \return true if \p F can be indirectly called
242static bool canBeIndirectlyCalled(const Function &F) {
243 if (F.isDeclaration() || AMDGPU::isEntryFunctionCC(F.getCallingConv()))
244 return false;
245 return !F.hasLocalLinkage() ||
246 F.hasAddressTaken(/*PutOffender=*/nullptr,
247 /*IgnoreCallbackUses=*/false,
248 /*IgnoreAssumeLikeCalls=*/true,
249 /*IgnoreLLVMUsed=*/true,
250 /*IgnoreARCAttachedCall=*/false,
251 /*IgnoreCastedDirectCall=*/true);
252}
253
254//===----------------------------------------------------------------------===//
255// Graph-based Module Representation
256//===----------------------------------------------------------------------===//
257
258/// AMDGPUSplitModule's view of the source Module, as a graph of all components
259/// that can be split into different modules.
260///
261/// The most trivial instance of this graph is just the CallGraph of the module,
262/// but it is not guaranteed that the graph is strictly equal to the CG. It
263/// currently always is but it's designed in a way that would eventually allow
264/// us to create abstract nodes, or nodes for different entities such as global
265/// variables or any other meaningful constraint we must consider.
266///
267/// The graph is only mutable by this class, and is generally not modified
268/// after \ref SplitGraph::buildGraph runs. No consumers of the graph can
269/// mutate it.
270class SplitGraph {
271public:
272 class Node;
273
274 enum class EdgeKind : uint8_t {
275 /// The nodes are related through a direct call. This is a "strong" edge as
276 /// it means the Src will directly reference the Dst.
278 /// The nodes are related through an indirect call.
279 /// This is a "weaker" edge and is only considered when traversing the graph
280 /// starting from a kernel. We need this edge for resource usage analysis.
281 ///
282 /// The reason why we have this edge in the first place is due to how
283 /// AMDGPUResourceUsageAnalysis works. In the presence of an indirect call,
284 /// the resource usage of the kernel containing the indirect call is the
285 /// max resource usage of all functions that can be indirectly called.
287 };
288
289 /// An edge between two nodes. Edges are directional, and tagged with a
290 /// "kind".
291 struct Edge {
292 Edge(Node *Src, Node *Dst, EdgeKind Kind)
293 : Src(Src), Dst(Dst), Kind(Kind) {}
294
295 Node *Src; ///< Source
296 Node *Dst; ///< Destination
297 EdgeKind Kind;
298 };
299
300 using EdgesVec = SmallVector<const Edge *, 0>;
301 using edges_iterator = EdgesVec::const_iterator;
302 using nodes_iterator = const Node *const *;
303
304 SplitGraph(const Module &M, const FunctionsCostMap &CostMap,
305 CostType ModuleCost)
306 : M(M), CostMap(CostMap), ModuleCost(ModuleCost) {}
307
308 void buildGraph(CallGraph &CG);
309
310#ifndef NDEBUG
311 bool verifyGraph() const;
312#endif
313
314 bool empty() const { return Nodes.empty(); }
315 iterator_range<nodes_iterator> nodes() const { return Nodes; }
316 const Node &getNode(unsigned ID) const { return *Nodes[ID]; }
317
318 unsigned getNumNodes() const { return Nodes.size(); }
319 BitVector createNodesBitVector() const { return BitVector(Nodes.size()); }
320
321 const Module &getModule() const { return M; }
322
323 CostType getModuleCost() const { return ModuleCost; }
324 CostType getCost(const Function &F) const { return CostMap.at(&F); }
325
326 /// \returns the aggregated cost of all nodes in \p BV (bits set to 1 = node
327 /// IDs).
328 CostType calculateCost(const BitVector &BV) const;
329
330private:
331 /// Retrieves the node for \p GV in \p Cache, or creates a new node for it and
332 /// updates \p Cache.
333 Node &getNode(DenseMap<const GlobalValue *, Node *> &Cache,
334 const GlobalValue &GV);
335
336 // Create a new edge between two nodes and add it to both nodes.
337 const Edge &createEdge(Node &Src, Node &Dst, EdgeKind EK);
338
339 const Module &M;
340 const FunctionsCostMap &CostMap;
341 CostType ModuleCost;
342
343 // Final list of nodes with stable ordering.
345
346 SpecificBumpPtrAllocator<Node> NodesPool;
347
348 // Edges are trivially destructible objects, so as a small optimization we
349 // use a BumpPtrAllocator which avoids destructor calls but also makes
350 // allocation faster.
351 static_assert(
352 std::is_trivially_destructible_v<Edge>,
353 "Edge must be trivially destructible to use the BumpPtrAllocator");
354 BumpPtrAllocator EdgesPool;
355};
356
357/// Nodes in the SplitGraph contain both incoming, and outgoing edges.
358/// Incoming edges have this node as their Dst, and Outgoing ones have this node
359/// as their Src.
360///
361/// Edge objects are shared by both nodes in Src/Dst. They provide immediate
362/// feedback on how two nodes are related, and in which direction they are
363/// related, which is valuable information to make splitting decisions.
364///
365/// Nodes are fundamentally abstract, and any consumers of the graph should
366/// treat them as such. While a node will be a function most of the time, we
367/// could also create nodes for any other reason. In the future, we could have
368/// single nodes for multiple functions, or nodes for GVs, etc.
369class SplitGraph::Node {
370 friend class SplitGraph;
371
372public:
373 Node(unsigned ID, const GlobalValue &GV, CostType IndividualCost,
374 bool IsNonCopyable)
375 : ID(ID), GV(GV), IndividualCost(IndividualCost),
376 IsNonCopyable(IsNonCopyable), IsEntryFnCC(false), IsGraphEntry(false) {
377 if (auto *Fn = dyn_cast<Function>(&GV))
378 IsEntryFnCC = AMDGPU::isEntryFunctionCC(Fn->getCallingConv());
379 }
380
381 /// An 0-indexed ID for the node. The maximum ID (exclusive) is the number of
382 /// nodes in the graph. This ID can be used as an index in a BitVector.
383 unsigned getID() const { return ID; }
384
385 const Function &getFunction() const { return cast<Function>(GV); }
386
387 /// \returns the cost to import this component into a given module, not
388 /// accounting for any dependencies that may need to be imported as well.
389 CostType getIndividualCost() const { return IndividualCost; }
390
391 bool isNonCopyable() const { return IsNonCopyable; }
392 bool isEntryFunctionCC() const { return IsEntryFnCC; }
393
394 /// \returns whether this is an entry point in the graph. Entry points are
395 /// defined as follows: if you take all entry points in the graph, and iterate
396 /// their dependencies, you are guaranteed to visit all nodes in the graph at
397 /// least once.
398 bool isGraphEntryPoint() const { return IsGraphEntry; }
399
400 StringRef getName() const { return GV.getName(); }
401
402 bool hasAnyIncomingEdges() const { return IncomingEdges.size(); }
403 bool hasAnyIncomingEdgesOfKind(EdgeKind EK) const {
404 return any_of(IncomingEdges, [&](const auto *E) { return E->Kind == EK; });
405 }
406
407 bool hasAnyOutgoingEdges() const { return OutgoingEdges.size(); }
408 bool hasAnyOutgoingEdgesOfKind(EdgeKind EK) const {
409 return any_of(OutgoingEdges, [&](const auto *E) { return E->Kind == EK; });
410 }
411
412 iterator_range<edges_iterator> incoming_edges() const {
413 return IncomingEdges;
414 }
415
416 iterator_range<edges_iterator> outgoing_edges() const {
417 return OutgoingEdges;
418 }
419
420 bool shouldFollowIndirectCalls() const { return isEntryFunctionCC(); }
421
422 /// Visit all children of this node in a recursive fashion. Also visits Self.
423 /// If \ref shouldFollowIndirectCalls returns false, then this only follows
424 /// DirectCall edges.
425 ///
426 /// \param Visitor Visitor Function.
427 void visitAllDependencies(std::function<void(const Node &)> Visitor) const;
428
429 /// Adds the depedencies of this node in \p BV by setting the bit
430 /// corresponding to each node.
431 ///
432 /// Implemented using \ref visitAllDependencies, hence it follows the same
433 /// rules regarding dependencies traversal.
434 ///
435 /// \param[out] BV The bitvector where the bits should be set.
436 void getDependencies(BitVector &BV) const {
437 visitAllDependencies([&](const Node &N) { BV.set(N.getID()); });
438 }
439
440private:
441 void markAsGraphEntry() { IsGraphEntry = true; }
442
443 unsigned ID;
444 const GlobalValue &GV;
445 CostType IndividualCost;
446 bool IsNonCopyable : 1;
447 bool IsEntryFnCC : 1;
448 bool IsGraphEntry : 1;
449
450 // TODO: Use a single sorted vector (with all incoming/outgoing edges grouped
451 // together)
452 EdgesVec IncomingEdges;
453 EdgesVec OutgoingEdges;
454};
455
456void SplitGraph::Node::visitAllDependencies(
457 std::function<void(const Node &)> Visitor) const {
458 const bool FollowIndirect = shouldFollowIndirectCalls();
459 // FIXME: If this can access SplitGraph in the future, use a BitVector
460 // instead.
461 DenseSet<const Node *> Seen;
462 SmallVector<const Node *, 8> WorkList({this});
463 while (!WorkList.empty()) {
464 const Node *CurN = WorkList.pop_back_val();
465 if (auto [It, Inserted] = Seen.insert(CurN); !Inserted)
466 continue;
467
468 Visitor(*CurN);
469
470 for (const Edge *E : CurN->outgoing_edges()) {
471 if (!FollowIndirect && E->Kind == EdgeKind::IndirectCall)
472 continue;
473 WorkList.push_back(E->Dst);
474 }
475 }
476}
477
478/// Checks if \p I has MD_callees and if it does, parse it and put the function
479/// in \p Callees.
480///
481/// \returns true if there was metadata and it was parsed correctly. false if
482/// there was no MD or if it contained unknown entries and parsing failed.
483/// If this returns false, \p Callees will contain incomplete information
484/// and must not be used.
485static bool handleCalleesMD(const Instruction &I,
486 SetVector<Function *> &Callees) {
487 auto *MD = I.getMetadata(LLVMContext::MD_callees);
488 if (!MD)
489 return false;
490
491 for (const auto &Op : MD->operands()) {
492 Function *Callee = mdconst::extract_or_null<Function>(Op);
493 if (!Callee)
494 return false;
495 Callees.insert(Callee);
496 }
497
498 return true;
499}
500
501void SplitGraph::buildGraph(CallGraph &CG) {
502 SplitModuleTimer SMT("buildGraph", "graph construction");
504 dbgs()
505 << "[build graph] constructing graph representation of the input\n");
506
507 // FIXME(?): Is the callgraph really worth using if we have to iterate the
508 // function again whenever it fails to give us enough information?
509
510 // We build the graph by just iterating all functions in the module and
511 // working on their direct callees. At the end, all nodes should be linked
512 // together as expected.
513 DenseMap<const GlobalValue *, Node *> Cache;
514 SmallVector<const Function *> FnsWithIndirectCalls, IndirectlyCallableFns;
515 for (const Function &Fn : M) {
516 if (Fn.isDeclaration())
517 continue;
518
519 // Look at direct callees and create the necessary edges in the graph.
520 SetVector<const Function *> DirectCallees;
521 bool CallsExternal = false;
522 for (auto &CGEntry : *CG[&Fn]) {
523 auto *CGNode = CGEntry.second;
524 if (auto *Callee = CGNode->getFunction()) {
525 if (!Callee->isDeclaration())
526 DirectCallees.insert(Callee);
527 } else if (CGNode == CG.getCallsExternalNode())
528 CallsExternal = true;
529 }
530
531 // Keep track of this function if it contains an indirect call and/or if it
532 // can be indirectly called.
533 if (CallsExternal) {
534 LLVM_DEBUG(dbgs() << " [!] callgraph is incomplete for ";
535 Fn.printAsOperand(dbgs());
536 dbgs() << " - analyzing function\n");
537
538 SetVector<Function *> KnownCallees;
539 bool HasUnknownIndirectCall = false;
540 for (const auto &Inst : instructions(Fn)) {
541 // look at all calls without a direct callee.
542 const auto *CB = dyn_cast<CallBase>(&Inst);
543 if (!CB || CB->getCalledFunction())
544 continue;
545
546 // inline assembly can be ignored, unless InlineAsmIsIndirectCall is
547 // true.
548 if (CB->isInlineAsm()) {
549 LLVM_DEBUG(dbgs() << " found inline assembly\n");
550 continue;
551 }
552
553 if (handleCalleesMD(Inst, KnownCallees))
554 continue;
555 // If we failed to parse any !callees MD, or some was missing,
556 // the entire KnownCallees list is now unreliable.
557 KnownCallees.clear();
558
559 // Everything else is handled conservatively. If we fall into the
560 // conservative case don't bother analyzing further.
561 HasUnknownIndirectCall = true;
562 break;
563 }
564
565 if (HasUnknownIndirectCall) {
566 LLVM_DEBUG(dbgs() << " indirect call found\n");
567 FnsWithIndirectCalls.push_back(&Fn);
568 } else if (!KnownCallees.empty())
569 DirectCallees.insert_range(KnownCallees);
570 }
571
572 Node &N = getNode(Cache, Fn);
573 for (const auto *Callee : DirectCallees)
574 createEdge(N, getNode(Cache, *Callee), EdgeKind::DirectCall);
575
576 if (canBeIndirectlyCalled(Fn))
577 IndirectlyCallableFns.push_back(&Fn);
578 }
579
580 // Post-process functions with indirect calls.
581 for (const Function *Fn : FnsWithIndirectCalls) {
582 for (const Function *Candidate : IndirectlyCallableFns) {
583 Node &Src = getNode(Cache, *Fn);
584 Node &Dst = getNode(Cache, *Candidate);
585 createEdge(Src, Dst, EdgeKind::IndirectCall);
586 }
587 }
588
589 // Now, find all entry points.
590 SmallVector<Node *, 16> CandidateEntryPoints;
591 BitVector NodesReachableByKernels = createNodesBitVector();
592 for (Node *N : Nodes) {
593 // Functions with an Entry CC are always graph entry points too.
594 if (N->isEntryFunctionCC()) {
595 N->markAsGraphEntry();
596 N->getDependencies(NodesReachableByKernels);
597 } else if (!N->hasAnyIncomingEdgesOfKind(EdgeKind::DirectCall))
598 CandidateEntryPoints.push_back(N);
599 }
600
601 for (Node *N : CandidateEntryPoints) {
602 // This can be another entry point if it's not reachable by a kernel
603 // TODO: We could sort all of the possible new entries in a stable order
604 // (e.g. by cost), then consume them one by one until
605 // NodesReachableByKernels is all 1s. It'd allow us to avoid
606 // considering some nodes as non-entries in some specific cases.
607 if (!NodesReachableByKernels.test(N->getID()))
608 N->markAsGraphEntry();
609 }
610
611#ifndef NDEBUG
612 assert(verifyGraph());
613#endif
614}
615
616#ifndef NDEBUG
617bool SplitGraph::verifyGraph() const {
618 unsigned ExpectedID = 0;
619 // Exceptionally using a set here in case IDs are messed up.
620 DenseSet<const Node *> SeenNodes;
621 DenseSet<const Function *> SeenFunctionNodes;
622 for (const Node *N : Nodes) {
623 if (N->getID() != (ExpectedID++)) {
624 errs() << "Node IDs are incorrect!\n";
625 return false;
626 }
627
628 if (!SeenNodes.insert(N).second) {
629 errs() << "Node seen more than once!\n";
630 return false;
631 }
632
633 if (&getNode(N->getID()) != N) {
634 errs() << "getNode doesn't return the right node\n";
635 return false;
636 }
637
638 for (const Edge *E : N->IncomingEdges) {
639 if (!E->Src || !E->Dst || (E->Dst != N) ||
640 (find(E->Src->OutgoingEdges, E) == E->Src->OutgoingEdges.end())) {
641 errs() << "ill-formed incoming edges\n";
642 return false;
643 }
644 }
645
646 for (const Edge *E : N->OutgoingEdges) {
647 if (!E->Src || !E->Dst || (E->Src != N) ||
648 (find(E->Dst->IncomingEdges, E) == E->Dst->IncomingEdges.end())) {
649 errs() << "ill-formed outgoing edges\n";
650 return false;
651 }
652 }
653
654 const Function &Fn = N->getFunction();
655 if (AMDGPU::isEntryFunctionCC(Fn.getCallingConv())) {
656 if (N->hasAnyIncomingEdges()) {
657 errs() << "Kernels cannot have incoming edges\n";
658 return false;
659 }
660 }
661
662 if (Fn.isDeclaration()) {
663 errs() << "declarations shouldn't have nodes!\n";
664 return false;
665 }
666
667 auto [It, Inserted] = SeenFunctionNodes.insert(&Fn);
668 if (!Inserted) {
669 errs() << "one function has multiple nodes!\n";
670 return false;
671 }
672 }
673
674 if (ExpectedID != Nodes.size()) {
675 errs() << "Node IDs out of sync!\n";
676 return false;
677 }
678
679 if (createNodesBitVector().size() != getNumNodes()) {
680 errs() << "nodes bit vector doesn't have the right size!\n";
681 return false;
682 }
683
684 // Check we respect the promise of Node::isKernel
685 BitVector BV = createNodesBitVector();
686 for (const Node *N : nodes()) {
687 if (N->isGraphEntryPoint())
688 N->getDependencies(BV);
689 }
690
691 // Ensure each function in the module has an associated node.
692 for (const auto &Fn : M) {
693 if (!Fn.isDeclaration()) {
694 if (!SeenFunctionNodes.contains(&Fn)) {
695 errs() << "Fn has no associated node in the graph!\n";
696 return false;
697 }
698 }
699 }
700
701 if (!BV.all()) {
702 errs() << "not all nodes are reachable through the graph's entry points!\n";
703 return false;
704 }
705
706 return true;
707}
708#endif
709
710CostType SplitGraph::calculateCost(const BitVector &BV) const {
711 CostType Cost = 0;
712 for (unsigned NodeID : BV.set_bits())
713 Cost += getNode(NodeID).getIndividualCost();
714 return Cost;
715}
716
717SplitGraph::Node &
718SplitGraph::getNode(DenseMap<const GlobalValue *, Node *> &Cache,
719 const GlobalValue &GV) {
720 auto &N = Cache[&GV];
721 if (N)
722 return *N;
723
724 CostType Cost = 0;
725 bool NonCopyable = false;
726 if (const Function *Fn = dyn_cast<Function>(&GV)) {
727 NonCopyable = isNonCopyable(*Fn);
728 Cost = CostMap.at(Fn);
729 }
730 N = new (NodesPool.Allocate()) Node(Nodes.size(), GV, Cost, NonCopyable);
731 Nodes.push_back(N);
732 assert(&getNode(N->getID()) == N);
733 return *N;
734}
735
736const SplitGraph::Edge &SplitGraph::createEdge(Node &Src, Node &Dst,
737 EdgeKind EK) {
738 const Edge *E = new (EdgesPool.Allocate<Edge>(1)) Edge(&Src, &Dst, EK);
739 Src.OutgoingEdges.push_back(E);
740 Dst.IncomingEdges.push_back(E);
741 return *E;
742}
743
744//===----------------------------------------------------------------------===//
745// Split Proposals
746//===----------------------------------------------------------------------===//
747
748/// Represents a module splitting proposal.
749///
750/// Proposals are made of N BitVectors, one for each partition, where each bit
751/// set indicates that the node is present and should be copied inside that
752/// partition.
753///
754/// Proposals have several metrics attached so they can be compared/sorted,
755/// which the driver to try multiple strategies resultings in multiple proposals
756/// and choose the best one out of them.
757class SplitProposal {
758public:
759 SplitProposal(const SplitGraph &SG, unsigned MaxPartitions) : SG(&SG) {
760 Partitions.resize(MaxPartitions, {0, SG.createNodesBitVector()});
761 }
762
763 void setName(StringRef NewName) { Name = NewName; }
764 StringRef getName() const { return Name; }
765
766 const BitVector &operator[](unsigned PID) const {
767 return Partitions[PID].second;
768 }
769
770 void add(unsigned PID, const BitVector &BV) {
771 Partitions[PID].second |= BV;
772 updateScore(PID);
773 }
774
775 void print(raw_ostream &OS) const;
776 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
777
778 // Find the cheapest partition (lowest cost). In case of ties, always returns
779 // the highest partition number.
780 unsigned findCheapestPartition() const;
781
782 /// Calculate the CodeSize and Bottleneck scores.
783 void calculateScores();
784
785#ifndef NDEBUG
786 void verifyCompleteness() const;
787#endif
788
789 /// Only available after \ref calculateScores is called.
790 ///
791 /// A positive number indicating the % of code duplication that this proposal
792 /// creates. e.g. 0.2 means this proposal adds roughly 20% code size by
793 /// duplicating some functions across partitions.
794 ///
795 /// Value is always rounded up to 3 decimal places.
796 ///
797 /// A perfect score would be 0.0, and anything approaching 1.0 is very bad.
798 double getCodeSizeScore() const { return CodeSizeScore; }
799
800 /// Only available after \ref calculateScores is called.
801 ///
802 /// A number between [0, 1] which indicates how big of a bottleneck is
803 /// expected from the largest partition.
804 ///
805 /// A score of 1.0 means the biggest partition is as big as the source module,
806 /// so build time will be equal to or greater than the build time of the
807 /// initial input.
808 ///
809 /// Value is always rounded up to 3 decimal places.
810 ///
811 /// This is one of the metrics used to estimate this proposal's build time.
812 double getBottleneckScore() const { return BottleneckScore; }
813
814private:
815 void updateScore(unsigned PID) {
816 assert(SG);
817 for (auto &[PCost, Nodes] : Partitions) {
818 TotalCost -= PCost;
819 PCost = SG->calculateCost(Nodes);
820 TotalCost += PCost;
821 }
822 }
823
824 /// \see getCodeSizeScore
825 double CodeSizeScore = 0.0;
826 /// \see getBottleneckScore
827 double BottleneckScore = 0.0;
828 /// Aggregated cost of all partitions
829 CostType TotalCost = 0;
830
831 const SplitGraph *SG = nullptr;
832 std::string Name;
833
834 std::vector<std::pair<CostType, BitVector>> Partitions;
835};
836
837void SplitProposal::print(raw_ostream &OS) const {
838 assert(SG);
839
840 OS << "[proposal] " << Name << ", total cost:" << TotalCost
841 << ", code size score:" << format("%0.3f", CodeSizeScore)
842 << ", bottleneck score:" << format("%0.3f", BottleneckScore) << '\n';
843 for (const auto &[PID, Part] : enumerate(Partitions)) {
844 const auto &[Cost, NodeIDs] = Part;
845 OS << " - P" << PID << " nodes:" << NodeIDs.count() << " cost: " << Cost
846 << '|' << formatRatioOf(Cost, SG->getModuleCost()) << "%\n";
847 }
848}
849
850unsigned SplitProposal::findCheapestPartition() const {
851 assert(!Partitions.empty());
852 CostType CurCost = std::numeric_limits<CostType>::max();
853 unsigned CurPID = InvalidPID;
854 for (const auto &[Idx, Part] : enumerate(Partitions)) {
855 if (Part.first <= CurCost) {
856 CurPID = Idx;
857 CurCost = Part.first;
858 }
859 }
860 assert(CurPID != InvalidPID);
861 return CurPID;
862}
863
864void SplitProposal::calculateScores() {
865 if (Partitions.empty())
866 return;
867
868 assert(SG);
869 CostType LargestPCost = 0;
870 for (auto &[PCost, Nodes] : Partitions) {
871 if (PCost > LargestPCost)
872 LargestPCost = PCost;
873 }
874
875 CostType ModuleCost = SG->getModuleCost();
876 CodeSizeScore = double(TotalCost) / ModuleCost;
877 assert(CodeSizeScore >= 0.0);
878
879 BottleneckScore = double(LargestPCost) / ModuleCost;
880
881 CodeSizeScore = std::ceil(CodeSizeScore * 100.0) / 100.0;
882 BottleneckScore = std::ceil(BottleneckScore * 100.0) / 100.0;
883}
884
885#ifndef NDEBUG
886void SplitProposal::verifyCompleteness() const {
887 if (Partitions.empty())
888 return;
889
890 BitVector Result = Partitions[0].second;
891 for (const auto &P : drop_begin(Partitions))
892 Result |= P.second;
893 assert(Result.all() && "some nodes are missing from this proposal!");
894}
895#endif
896
897//===-- RecursiveSearchStrategy -------------------------------------------===//
898
899/// Partitioning algorithm.
900///
901/// This is a recursive search algorithm that can explore multiple possiblities.
902///
903/// When a cluster of nodes can go into more than one partition, and we haven't
904/// reached maximum search depth, we recurse and explore both options and their
905/// consequences. Both branches will yield a proposal, and the driver will grade
906/// both and choose the best one.
907///
908/// If max depth is reached, we will use some heuristics to make a choice. Most
909/// of the time we will just use the least-pressured (cheapest) partition, but
910/// if a cluster is particularly big and there is a good amount of overlap with
911/// an existing partition, we will choose that partition instead.
912class RecursiveSearchSplitting {
913public:
914 using SubmitProposalFn = function_ref<void(SplitProposal)>;
915
916 RecursiveSearchSplitting(const SplitGraph &SG, unsigned NumParts,
917 SubmitProposalFn SubmitProposal);
918
919 void run();
920
921private:
922 struct WorkListEntry {
923 WorkListEntry(const BitVector &BV) : Cluster(BV) {}
924
925 unsigned NumNonEntryNodes = 0;
926 CostType TotalCost = 0;
927 CostType CostExcludingGraphEntryPoints = 0;
928 BitVector Cluster;
929 };
930
931 /// Collects all graph entry points's clusters and sort them so the most
932 /// expensive clusters are viewed first. This will merge clusters together if
933 /// they share a non-copyable dependency.
934 void setupWorkList();
935
936 /// Recursive function that assigns the worklist item at \p Idx into a
937 /// partition of \p SP.
938 ///
939 /// \p Depth is the current search depth. When this value is equal to
940 /// \ref MaxDepth, we can no longer recurse.
941 ///
942 /// This function only recurses if there is more than one possible assignment,
943 /// otherwise it is iterative to avoid creating a call stack that is as big as
944 /// \ref WorkList.
945 void pickPartition(unsigned Depth, unsigned Idx, SplitProposal SP);
946
947 /// \return A pair: first element is the PID of the partition that has the
948 /// most similarities with \p Entry, or \ref InvalidPID if no partition was
949 /// found with at least one element in common. The second element is the
950 /// aggregated cost of all dependencies in common between \p Entry and that
951 /// partition.
952 std::pair<unsigned, CostType>
953 findMostSimilarPartition(const WorkListEntry &Entry, const SplitProposal &SP);
954
955 const SplitGraph &SG;
956 unsigned NumParts;
957 SubmitProposalFn SubmitProposal;
958
959 // A Cluster is considered large when its cost, excluding entry points,
960 // exceeds this value.
961 CostType LargeClusterThreshold = 0;
962 unsigned NumProposalsSubmitted = 0;
963 SmallVector<WorkListEntry> WorkList;
964};
965
966RecursiveSearchSplitting::RecursiveSearchSplitting(
967 const SplitGraph &SG, unsigned NumParts, SubmitProposalFn SubmitProposal)
968 : SG(SG), NumParts(NumParts), SubmitProposal(SubmitProposal) {
969 // arbitrary max value as a safeguard. Anything above 10 will already be
970 // slow, this is just a max value to prevent extreme resource exhaustion or
971 // unbounded run time.
972 if (MaxDepth > 16)
973 report_fatal_error("[amdgpu-split-module] search depth of " +
974 Twine(MaxDepth) + " is too high!");
975 LargeClusterThreshold =
976 (LargeFnFactor != 0.0)
977 ? CostType(((SG.getModuleCost() / NumParts) * LargeFnFactor))
978 : std::numeric_limits<CostType>::max();
979 LLVM_DEBUG(dbgs() << "[recursive search] large cluster threshold set at "
980 << LargeClusterThreshold << "\n");
981}
982
983void RecursiveSearchSplitting::run() {
984 {
985 SplitModuleTimer SMT("recursive_search_prepare", "preparing worklist");
986 setupWorkList();
987 }
988
989 {
990 SplitModuleTimer SMT("recursive_search_pick", "partitioning");
991 SplitProposal SP(SG, NumParts);
992 pickPartition(/*BranchDepth=*/0, /*Idx=*/0, std::move(SP));
993 }
994}
995
996void RecursiveSearchSplitting::setupWorkList() {
997 // e.g. if A and B are two worklist item, and they both call a non copyable
998 // dependency C, this does:
999 // A=C
1000 // B=C
1001 // => NodeEC will create a single group (A, B, C) and we create a new
1002 // WorkList entry for that group.
1003
1004 EquivalenceClasses<unsigned> NodeEC;
1005 for (const SplitGraph::Node *N : SG.nodes()) {
1006 if (!N->isGraphEntryPoint())
1007 continue;
1008
1009 NodeEC.insert(N->getID());
1010 N->visitAllDependencies([&](const SplitGraph::Node &Dep) {
1011 if (&Dep != N && Dep.isNonCopyable())
1012 NodeEC.unionSets(N->getID(), Dep.getID());
1013 });
1014 }
1015
1016 for (const auto &Node : NodeEC) {
1017 if (!Node->isLeader())
1018 continue;
1019
1020 BitVector Cluster = SG.createNodesBitVector();
1021 for (unsigned M : NodeEC.members(*Node)) {
1022 const SplitGraph::Node &N = SG.getNode(M);
1023 if (N.isGraphEntryPoint())
1024 N.getDependencies(Cluster);
1025 }
1026 WorkList.emplace_back(std::move(Cluster));
1027 }
1028
1029 // Calculate costs and other useful information.
1030 for (WorkListEntry &Entry : WorkList) {
1031 for (unsigned NodeID : Entry.Cluster.set_bits()) {
1032 const SplitGraph::Node &N = SG.getNode(NodeID);
1033 const CostType Cost = N.getIndividualCost();
1034
1035 Entry.TotalCost += Cost;
1036 if (!N.isGraphEntryPoint()) {
1037 Entry.CostExcludingGraphEntryPoints += Cost;
1038 ++Entry.NumNonEntryNodes;
1039 }
1040 }
1041 }
1042
1043 stable_sort(WorkList, [](const WorkListEntry &A, const WorkListEntry &B) {
1044 if (A.TotalCost != B.TotalCost)
1045 return A.TotalCost > B.TotalCost;
1046
1047 if (A.CostExcludingGraphEntryPoints != B.CostExcludingGraphEntryPoints)
1048 return A.CostExcludingGraphEntryPoints > B.CostExcludingGraphEntryPoints;
1049
1050 if (A.NumNonEntryNodes != B.NumNonEntryNodes)
1051 return A.NumNonEntryNodes > B.NumNonEntryNodes;
1052
1053 return A.Cluster.count() > B.Cluster.count();
1054 });
1055
1056 LLVM_DEBUG({
1057 dbgs() << "[recursive search] worklist:\n";
1058 for (const auto &[Idx, Entry] : enumerate(WorkList)) {
1059 dbgs() << " - [" << Idx << "]: ";
1060 for (unsigned NodeID : Entry.Cluster.set_bits())
1061 dbgs() << NodeID << " ";
1062 dbgs() << "(total_cost:" << Entry.TotalCost
1063 << ", cost_excl_entries:" << Entry.CostExcludingGraphEntryPoints
1064 << ")\n";
1065 }
1066 });
1067}
1068
1069void RecursiveSearchSplitting::pickPartition(unsigned Depth, unsigned Idx,
1070 SplitProposal SP) {
1071 while (Idx < WorkList.size()) {
1072 // Step 1: Determine candidate PIDs.
1073 //
1074 const WorkListEntry &Entry = WorkList[Idx];
1075 const BitVector &Cluster = Entry.Cluster;
1076
1077 // Default option is to do load-balancing, AKA assign to least pressured
1078 // partition.
1079 const unsigned CheapestPID = SP.findCheapestPartition();
1080 assert(CheapestPID != InvalidPID);
1081
1082 // Explore assigning to the kernel that contains the most dependencies in
1083 // common.
1084 const auto [MostSimilarPID, SimilarDepsCost] =
1085 findMostSimilarPartition(Entry, SP);
1086
1087 // We can chose to explore only one path if we only have one valid path, or
1088 // if we reached maximum search depth and can no longer branch out.
1089 unsigned SinglePIDToTry = InvalidPID;
1090 if (MostSimilarPID == InvalidPID) // no similar PID found
1091 SinglePIDToTry = CheapestPID;
1092 else if (MostSimilarPID == CheapestPID) // both landed on the same PID
1093 SinglePIDToTry = CheapestPID;
1094 else if (Depth >= MaxDepth) {
1095 // We have to choose one path. Use a heuristic to guess which one will be
1096 // more appropriate.
1097 if (Entry.CostExcludingGraphEntryPoints > LargeClusterThreshold) {
1098 // Check if the amount of code in common makes it worth it.
1099 assert(SimilarDepsCost && Entry.CostExcludingGraphEntryPoints);
1100 const double Ratio = static_cast<double>(SimilarDepsCost) /
1101 Entry.CostExcludingGraphEntryPoints;
1102 assert(Ratio >= 0.0 && Ratio <= 1.0);
1103 if (Ratio > LargeFnOverlapForMerge) {
1104 // For debug, just print "L", so we'll see "L3=P3" for instance, which
1105 // will mean we reached max depth and chose P3 based on this
1106 // heuristic.
1107 LLVM_DEBUG(dbgs() << 'L');
1108 SinglePIDToTry = MostSimilarPID;
1109 }
1110 } else
1111 SinglePIDToTry = CheapestPID;
1112 }
1113
1114 // Step 2: Explore candidates.
1115
1116 // When we only explore one possible path, and thus branch depth doesn't
1117 // increase, do not recurse, iterate instead.
1118 if (SinglePIDToTry != InvalidPID) {
1119 LLVM_DEBUG(dbgs() << Idx << "=P" << SinglePIDToTry << ' ');
1120 // Only one path to explore, don't clone SP, don't increase depth.
1121 SP.add(SinglePIDToTry, Cluster);
1122 ++Idx;
1123 continue;
1124 }
1125
1126 assert(MostSimilarPID != InvalidPID);
1127
1128 // We explore multiple paths: recurse at increased depth, then stop this
1129 // function.
1130
1131 LLVM_DEBUG(dbgs() << '\n');
1132
1133 // lb = load balancing = put in cheapest partition
1134 {
1135 SplitProposal BranchSP = SP;
1136 LLVM_DEBUG(dbgs().indent(Depth)
1137 << " [lb] " << Idx << "=P" << CheapestPID << "? ");
1138 BranchSP.add(CheapestPID, Cluster);
1139 pickPartition(Depth + 1, Idx + 1, std::move(BranchSP));
1140 }
1141
1142 // ms = most similar = put in partition with the most in common
1143 {
1144 SplitProposal BranchSP = SP;
1145 LLVM_DEBUG(dbgs().indent(Depth)
1146 << " [ms] " << Idx << "=P" << MostSimilarPID << "? ");
1147 BranchSP.add(MostSimilarPID, Cluster);
1148 pickPartition(Depth + 1, Idx + 1, std::move(BranchSP));
1149 }
1150
1151 return;
1152 }
1153
1154 // Step 3: If we assigned all WorkList items, submit the proposal.
1155
1156 assert(Idx == WorkList.size());
1157 assert(NumProposalsSubmitted <= (2u << MaxDepth) &&
1158 "Search got out of bounds?");
1159 SP.setName("recursive_search (depth=" + std::to_string(Depth) + ") #" +
1160 std::to_string(NumProposalsSubmitted++));
1161 LLVM_DEBUG(dbgs() << '\n');
1162 SubmitProposal(std::move(SP));
1163}
1164
1165std::pair<unsigned, CostType>
1166RecursiveSearchSplitting::findMostSimilarPartition(const WorkListEntry &Entry,
1167 const SplitProposal &SP) {
1168 if (!Entry.NumNonEntryNodes)
1169 return {InvalidPID, 0};
1170
1171 // We take the partition that is the most similar using Cost as a metric.
1172 // So we take the set of nodes in common, compute their aggregated cost, and
1173 // pick the partition with the highest cost in common.
1174 unsigned ChosenPID = InvalidPID;
1175 CostType ChosenCost = 0;
1176 for (unsigned PID = 0; PID < NumParts; ++PID) {
1177 BitVector BV = SP[PID];
1178 BV &= Entry.Cluster; // FIXME: & doesn't work between BVs?!
1179
1180 if (BV.none())
1181 continue;
1182
1183 const CostType Cost = SG.calculateCost(BV);
1184
1185 if (ChosenPID == InvalidPID || ChosenCost < Cost ||
1186 (ChosenCost == Cost && PID > ChosenPID)) {
1187 ChosenPID = PID;
1188 ChosenCost = Cost;
1189 }
1190 }
1191
1192 return {ChosenPID, ChosenCost};
1193}
1194
1195//===----------------------------------------------------------------------===//
1196// DOTGraph Printing Support
1197//===----------------------------------------------------------------------===//
1198
1199const SplitGraph::Node *mapEdgeToDst(const SplitGraph::Edge *E) {
1200 return E->Dst;
1201}
1202
1203using SplitGraphEdgeDstIterator =
1204 mapped_iterator<SplitGraph::edges_iterator, decltype(&mapEdgeToDst)>;
1205
1206} // namespace
1207
1208template <> struct GraphTraits<SplitGraph> {
1209 using NodeRef = const SplitGraph::Node *;
1210 using nodes_iterator = SplitGraph::nodes_iterator;
1211 using ChildIteratorType = SplitGraphEdgeDstIterator;
1212
1213 using EdgeRef = const SplitGraph::Edge *;
1214 using ChildEdgeIteratorType = SplitGraph::edges_iterator;
1215
1216 static NodeRef getEntryNode(NodeRef N) { return N; }
1217
1219 return {Ref->outgoing_edges().begin(), mapEdgeToDst};
1220 }
1222 return {Ref->outgoing_edges().end(), mapEdgeToDst};
1223 }
1224
1225 static nodes_iterator nodes_begin(const SplitGraph &G) {
1226 return G.nodes().begin();
1227 }
1228 static nodes_iterator nodes_end(const SplitGraph &G) {
1229 return G.nodes().end();
1230 }
1231};
1232
1233template <> struct DOTGraphTraits<SplitGraph> : public DefaultDOTGraphTraits {
1234 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
1235
1236 static std::string getGraphName(const SplitGraph &SG) {
1237 return SG.getModule().getName().str();
1238 }
1239
1240 std::string getNodeLabel(const SplitGraph::Node *N, const SplitGraph &SG) {
1241 return N->getName().str();
1242 }
1243
1244 static std::string getNodeDescription(const SplitGraph::Node *N,
1245 const SplitGraph &SG) {
1246 std::string Result;
1247 if (N->isEntryFunctionCC())
1248 Result += "entry-fn-cc ";
1249 if (N->isNonCopyable())
1250 Result += "non-copyable ";
1251 Result += "cost:" + std::to_string(N->getIndividualCost());
1252 return Result;
1253 }
1254
1255 static std::string getNodeAttributes(const SplitGraph::Node *N,
1256 const SplitGraph &SG) {
1257 return N->hasAnyIncomingEdges() ? "" : "color=\"red\"";
1258 }
1259
1260 static std::string getEdgeAttributes(const SplitGraph::Node *N,
1261 SplitGraphEdgeDstIterator EI,
1262 const SplitGraph &SG) {
1263
1264 switch ((*EI.getCurrent())->Kind) {
1265 case SplitGraph::EdgeKind::DirectCall:
1266 return "";
1267 case SplitGraph::EdgeKind::IndirectCall:
1268 return "style=\"dashed\"";
1269 }
1270 llvm_unreachable("Unknown SplitGraph::EdgeKind enum");
1271 }
1272};
1273
1274//===----------------------------------------------------------------------===//
1275// Driver
1276//===----------------------------------------------------------------------===//
1277
1278namespace {
1279
1280// If we didn't externalize GVs, then local GVs need to be conservatively
1281// imported into every module (including their initializers), and then cleaned
1282// up afterwards.
1283static bool needsConservativeImport(const GlobalValue *GV) {
1284 if (const auto *Var = dyn_cast<GlobalVariable>(GV))
1285 return Var->hasLocalLinkage();
1286 if (const auto *GA = dyn_cast<GlobalAlias>(GV))
1287 return GA->hasLocalLinkage();
1288 return false;
1289}
1290
1291/// Prints a summary of the partition \p N, represented by module \p M, to \p
1292/// OS.
1293static void printPartitionSummary(raw_ostream &OS, unsigned N, const Module &M,
1294 unsigned PartCost, unsigned ModuleCost) {
1295 OS << "*** Partition P" << N << " ***\n";
1296
1297 for (const auto &Fn : M) {
1298 if (!Fn.isDeclaration())
1299 OS << " - [function] " << Fn.getName() << "\n";
1300 }
1301
1302 for (const auto &GV : M.globals()) {
1303 if (GV.hasInitializer())
1304 OS << " - [global] " << GV.getName() << "\n";
1305 }
1306
1307 OS << "Partition contains " << formatRatioOf(PartCost, ModuleCost)
1308 << "% of the source\n";
1309}
1310
1311static void evaluateProposal(SplitProposal &Best, SplitProposal New) {
1312 SplitModuleTimer SMT("proposal_evaluation", "proposal ranking algorithm");
1313
1314 LLVM_DEBUG({
1315 New.verifyCompleteness();
1316 if (DebugProposalSearch)
1317 New.print(dbgs());
1318 });
1319
1320 const double CurBScore = Best.getBottleneckScore();
1321 const double CurCSScore = Best.getCodeSizeScore();
1322 const double NewBScore = New.getBottleneckScore();
1323 const double NewCSScore = New.getCodeSizeScore();
1324
1325 // TODO: Improve this
1326 // We can probably lower the precision of the comparison at first
1327 // e.g. if we have
1328 // - (Current): BScore: 0.489 CSCore 1.105
1329 // - (New): BScore: 0.475 CSCore 1.305
1330 // Currently we'd choose the new one because the bottleneck score is
1331 // lower, but the new one duplicates more code. It may be worth it to
1332 // discard the new proposal as the impact on build time is negligible.
1333
1334 // Compare them
1335 bool IsBest = false;
1336 if (NewBScore < CurBScore)
1337 IsBest = true;
1338 else if (NewBScore == CurBScore)
1339 IsBest = (NewCSScore < CurCSScore); // Use code size as tie breaker.
1340
1341 if (IsBest)
1342 Best = std::move(New);
1343
1344 LLVM_DEBUG(if (DebugProposalSearch) {
1345 if (IsBest)
1346 dbgs() << "[search] new best proposal!\n";
1347 else
1348 dbgs() << "[search] discarding - not profitable\n";
1349 });
1350}
1351
1352/// Trivial helper to create an identical copy of \p M.
1353static std::unique_ptr<Module> cloneAll(const Module &M) {
1354 ValueToValueMapTy VMap;
1355 return CloneModule(M, VMap, [&](const GlobalValue *GV) { return true; });
1356}
1357
1358/// Writes \p SG as a DOTGraph to \ref ModuleDotCfgDir if requested.
1359static void writeDOTGraph(const SplitGraph &SG) {
1360 if (ModuleDotCfgOutput.empty())
1361 return;
1362
1363 std::error_code EC;
1364 raw_fd_ostream OS(ModuleDotCfgOutput, EC);
1365 if (EC) {
1366 errs() << "[" DEBUG_TYPE "]: cannot open '" << ModuleDotCfgOutput
1367 << "' - DOTGraph will not be printed\n";
1368 }
1369 WriteGraph(OS, SG, /*ShortName=*/false,
1370 /*Title=*/SG.getModule().getName());
1371}
1372
1373static void splitAMDGPUModule(
1374 GetTTIFn GetTTI, Module &M, unsigned NumParts,
1375 function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
1376 CallGraph CG(M);
1377
1378 // Externalize functions whose address are taken.
1379 //
1380 // This is needed because partitioning is purely based on calls, but sometimes
1381 // a kernel/function may just look at the address of another local function
1382 // and not do anything (no calls). After partitioning, that local function may
1383 // end up in a different module (so it's just a declaration in the module
1384 // where its address is taken), which emits a "undefined hidden symbol" linker
1385 // error.
1386 //
1387 // Additionally, it guides partitioning to not duplicate this function if it's
1388 // called directly at some point.
1389 //
1390 // TODO: Could we be smarter about this ? This makes all functions whose
1391 // addresses are taken non-copyable. We should probably model this type of
1392 // constraint in the graph and use it to guide splitting, instead of
1393 // externalizing like this. Maybe non-copyable should really mean "keep one
1394 // visible copy, then internalize all other copies" for some functions?
1395 if (!NoExternalizeOnAddrTaken) {
1396 for (auto &Fn : M) {
1397 if (Fn.hasLocalLinkage() && Fn.hasAddressTaken()) {
1398 LLVM_DEBUG(dbgs() << "[externalize] "; Fn.printAsOperand(dbgs());
1399 dbgs() << " because its address is taken\n");
1400 externalize(Fn);
1401 }
1402 }
1403 }
1404
1405 // Externalize local GVs, which avoids duplicating their initializers, which
1406 // in turns helps keep code size in check.
1407 if (!NoExternalizeGlobals) {
1408 for (auto &GV : M.globals()) {
1409 if (GV.hasLocalLinkage())
1410 LLVM_DEBUG(dbgs() << "[externalize] GV " << GV.getName() << '\n');
1411 externalize(GV);
1412 }
1413 }
1414
1415 for (auto &GA : M.aliases()) {
1416 if (GA.hasLocalLinkage()) {
1417 LLVM_DEBUG(dbgs() << "[externalize] alias " << GA.getName() << '\n');
1418 externalize(GA);
1419 }
1420 }
1421
1422 // Start by calculating the cost of every function in the module, as well as
1423 // the module's overall cost.
1424 FunctionsCostMap FnCosts;
1425 const CostType ModuleCost = calculateFunctionCosts(GetTTI, M, FnCosts);
1426
1427 // Build the SplitGraph, which represents the module's functions and models
1428 // their dependencies accurately.
1429 SplitGraph SG(M, FnCosts, ModuleCost);
1430 SG.buildGraph(CG);
1431
1432 if (SG.empty()) {
1433 LLVM_DEBUG(
1434 dbgs()
1435 << "[!] no nodes in graph, input is empty - no splitting possible\n");
1436 ModuleCallback(cloneAll(M));
1437 return;
1438 }
1439
1440 LLVM_DEBUG({
1441 dbgs() << "[graph] nodes:\n";
1442 for (const SplitGraph::Node *N : SG.nodes()) {
1443 dbgs() << " - [" << N->getID() << "]: " << N->getName() << " "
1444 << (N->isGraphEntryPoint() ? "(entry)" : "") << " "
1445 << (N->isNonCopyable() ? "(noncopyable)" : "") << "\n";
1446 }
1447 });
1448
1449 writeDOTGraph(SG);
1450
1451 LLVM_DEBUG(dbgs() << "[search] testing splitting strategies\n");
1452
1453 std::optional<SplitProposal> Proposal;
1454 const auto EvaluateProposal = [&](SplitProposal SP) {
1455 SP.calculateScores();
1456 if (!Proposal)
1457 Proposal = std::move(SP);
1458 else
1459 evaluateProposal(*Proposal, std::move(SP));
1460 };
1461
1462 // TODO: It would be very easy to create new strategies by just adding a base
1463 // class to RecursiveSearchSplitting and abstracting it away.
1464 RecursiveSearchSplitting(SG, NumParts, EvaluateProposal).run();
1465 LLVM_DEBUG(if (Proposal) dbgs() << "[search done] selected proposal: "
1466 << Proposal->getName() << "\n";);
1467
1468 if (!Proposal) {
1469 LLVM_DEBUG(dbgs() << "[!] no proposal made, no splitting possible!\n");
1470 ModuleCallback(cloneAll(M));
1471 return;
1472 }
1473
1474 LLVM_DEBUG(Proposal->print(dbgs()););
1475
1476 std::optional<raw_fd_ostream> SummariesOS;
1477 if (!PartitionSummariesOutput.empty()) {
1478 std::error_code EC;
1479 SummariesOS.emplace(PartitionSummariesOutput, EC);
1480 if (EC)
1481 errs() << "[" DEBUG_TYPE "]: cannot open '" << PartitionSummariesOutput
1482 << "' - Partition summaries will not be printed\n";
1483 }
1484
1485 // One module will import all GlobalValues that are not Functions
1486 // and are not subject to conservative import.
1487 bool ImportAllGVs = true;
1488
1489 for (unsigned PID = 0; PID < NumParts; ++PID) {
1490 SplitModuleTimer SMT2("modules_creation",
1491 "creating modules for each partition");
1492 LLVM_DEBUG(dbgs() << "[split] creating new modules\n");
1493
1494 DenseSet<const Function *> FnsInPart;
1495 for (unsigned NodeID : (*Proposal)[PID].set_bits())
1496 FnsInPart.insert(&SG.getNode(NodeID).getFunction());
1497
1498 // Don't create empty modules.
1499 if (FnsInPart.empty()) {
1500 LLVM_DEBUG(dbgs() << "[split] P" << PID
1501 << " is empty, not creating module\n");
1502 continue;
1503 }
1504
1505 ValueToValueMapTy VMap;
1506 CostType PartCost = 0;
1507 std::unique_ptr<Module> MPart(
1508 CloneModule(M, VMap, [&](const GlobalValue *GV) {
1509 // Functions go in their assigned partition.
1510 if (const auto *Fn = dyn_cast<Function>(GV)) {
1511 if (FnsInPart.contains(Fn)) {
1512 PartCost += SG.getCost(*Fn);
1513 return true;
1514 }
1515 return false;
1516 }
1517
1518 // Aliases should not be separated from their underlying object.
1519 if (const auto *GA = dyn_cast<GlobalAlias>(GV)) {
1520 if (const auto *Fn = dyn_cast<Function>(GA->getAliaseeObject()))
1521 return FnsInPart.contains(Fn);
1522 }
1523
1524 // Everything else goes in the first non-empty module we create.
1525 return ImportAllGVs || needsConservativeImport(GV);
1526 }));
1527
1528 ImportAllGVs = false;
1529
1530 // Clean-up conservatively imported GVs without any users.
1531 for (auto &GV : make_early_inc_range(MPart->global_values())) {
1532 if (needsConservativeImport(&GV) && GV.use_empty())
1533 GV.eraseFromParent();
1534 }
1535
1536 if (SummariesOS)
1537 printPartitionSummary(*SummariesOS, PID, *MPart, PartCost, ModuleCost);
1538
1539 LLVM_DEBUG(
1540 printPartitionSummary(dbgs(), PID, *MPart, PartCost, ModuleCost));
1541
1542 ModuleCallback(std::move(MPart));
1543 }
1544}
1545} // namespace
1546
1549 SplitModuleTimer SMT(
1550 "total", "total pass runtime (incl. potentially waiting for lockfile)");
1551
1553 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1554 const auto TTIGetter = [&FAM](Function &F) -> const TargetTransformInfo & {
1555 return FAM.getResult<TargetIRAnalysis>(F);
1556 };
1557
1558 bool Done = false;
1559#ifndef NDEBUG
1560 if (UseLockFile) {
1561 SmallString<128> LockFilePath;
1562 sys::path::system_temp_directory(/*ErasedOnReboot=*/true, LockFilePath);
1563 sys::path::append(LockFilePath, "amdgpu-split-module-debug");
1564 LLVM_DEBUG(dbgs() << DEBUG_TYPE " using lockfile '" << LockFilePath
1565 << "'\n");
1566
1567 while (true) {
1568 llvm::LockFileManager Lock(LockFilePath.str());
1569 bool Owned;
1570 if (Error Err = Lock.tryLock().moveInto(Owned)) {
1571 consumeError(std::move(Err));
1572 LLVM_DEBUG(
1573 dbgs() << "[amdgpu-split-module] unable to acquire lockfile, debug "
1574 "output may be mangled by other processes\n");
1575 } else if (!Owned) {
1576 switch (Lock.waitForUnlockFor(std::chrono::seconds(90))) {
1578 break;
1580 continue; // try again to get the lock.
1582 LLVM_DEBUG(
1583 dbgs()
1584 << "[amdgpu-split-module] unable to acquire lockfile, debug "
1585 "output may be mangled by other processes\n");
1586 Lock.unsafeUnlock();
1587 break; // give up
1588 }
1589 }
1590
1591 splitAMDGPUModule(TTIGetter, M, N, ModuleCallback);
1592 Done = true;
1593 break;
1594 }
1595 }
1596#endif
1597
1598 if (!Done)
1599 splitAMDGPUModule(TTIGetter, M, N, ModuleCallback);
1600
1601 // We can change linkage/visibilities in the input, consider that nothing is
1602 // preserved just to be safe. This pass runs last anyway.
1603 return PreservedAnalyses::none();
1604}
1605} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
function_ref< const TargetTransformInfo *(Function &)> GetTTIFn
Unify divergent function exit nodes
This file defines the BumpPtrAllocator interface.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
static InstructionCost getCost(Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:73
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This header defines classes/functions to handle pass execution timing information with interfaces for...
static StringRef getName(Value *V)
std::pair< BasicBlock *, BasicBlock * > Edge
This file defines the SmallVector class.
static void externalize(GlobalValue *GV)
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
This pass exposes codegen information to IR-level passes.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
static InstructionCost getMax()
Class that manages the creation of a lock file to aid implicit coordination between different process...
std::error_code unsafeUnlock() override
Remove the lock file.
WaitForUnlockResult waitForUnlockFor(std::chrono::seconds MaxSeconds) override
For a shared lock, wait until the owner releases the lock.
Expected< bool > tryLock() override
Tries to acquire the lock without blocking.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_CodeSize
Instruction code size.
@ TCC_Expensive
The cost of a 'div' instruction on x86.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
template class LLVM_TEMPLATE_ABI opt< bool >
template class LLVM_TEMPLATE_ABI opt< unsigned >
initializer< Ty > init(const Ty &Val)
template class LLVM_TEMPLATE_ABI opt< std::string >
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Op::Description Desc
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
@ Success
The lock was released successfully.
@ OwnerDied
Owner died while holding the lock.
@ Timeout
Reached timeout while waiting for the owner to release the lock.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
TargetTransformInfo TTI
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
static std::string getEdgeAttributes(const SplitGraph::Node *N, SplitGraphEdgeDstIterator EI, const SplitGraph &SG)
static std::string getGraphName(const SplitGraph &SG)
static std::string getNodeAttributes(const SplitGraph::Node *N, const SplitGraph &SG)
static std::string getNodeDescription(const SplitGraph::Node *N, const SplitGraph &SG)
std::string getNodeLabel(const SplitGraph::Node *N, const SplitGraph &SG)
DefaultDOTGraphTraits(bool simple=false)
static NodeRef getEntryNode(NodeRef N)
SplitGraph::nodes_iterator nodes_iterator
SplitGraph::edges_iterator ChildEdgeIteratorType
SplitGraphEdgeDstIterator ChildIteratorType
static nodes_iterator nodes_end(const SplitGraph &G)
static ChildIteratorType child_begin(NodeRef Ref)
static nodes_iterator nodes_begin(const SplitGraph &G)
static ChildIteratorType child_end(NodeRef Ref)