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