xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/SplitModule.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1dd58ef01SDimitry Andric //===- SplitModule.cpp - Split a module into partitions -------------------===//
2dd58ef01SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dd58ef01SDimitry Andric //
7dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
8dd58ef01SDimitry Andric //
9dd58ef01SDimitry Andric // This file defines the function llvm::SplitModule, which splits a module
10dd58ef01SDimitry Andric // into multiple linkable partitions. It can be used to implement parallel code
11dd58ef01SDimitry Andric // generation for link-time optimization.
12dd58ef01SDimitry Andric //
13dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
14dd58ef01SDimitry Andric 
15dd58ef01SDimitry Andric #include "llvm/Transforms/Utils/SplitModule.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/DenseMap.h"
1701095a5dSDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
20044eb2f6SDimitry Andric #include "llvm/ADT/StringRef.h"
21044eb2f6SDimitry Andric #include "llvm/IR/Comdat.h"
22044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
2301095a5dSDimitry Andric #include "llvm/IR/Constants.h"
24dd58ef01SDimitry Andric #include "llvm/IR/Function.h"
25dd58ef01SDimitry Andric #include "llvm/IR/GlobalAlias.h"
26dd58ef01SDimitry Andric #include "llvm/IR/GlobalObject.h"
27dd58ef01SDimitry Andric #include "llvm/IR/GlobalValue.h"
28044eb2f6SDimitry Andric #include "llvm/IR/GlobalVariable.h"
29044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
30dd58ef01SDimitry Andric #include "llvm/IR/Module.h"
31044eb2f6SDimitry Andric #include "llvm/IR/User.h"
32044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
33044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
3401095a5dSDimitry Andric #include "llvm/Support/Debug.h"
35044eb2f6SDimitry Andric #include "llvm/Support/ErrorHandling.h"
36dd58ef01SDimitry Andric #include "llvm/Support/MD5.h"
37dd58ef01SDimitry Andric #include "llvm/Support/raw_ostream.h"
38dd58ef01SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
39044eb2f6SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
40044eb2f6SDimitry Andric #include <algorithm>
41044eb2f6SDimitry Andric #include <cassert>
42044eb2f6SDimitry Andric #include <iterator>
43044eb2f6SDimitry Andric #include <memory>
4401095a5dSDimitry Andric #include <queue>
45044eb2f6SDimitry Andric #include <utility>
46044eb2f6SDimitry Andric #include <vector>
47dd58ef01SDimitry Andric 
48dd58ef01SDimitry Andric using namespace llvm;
49dd58ef01SDimitry Andric 
50044eb2f6SDimitry Andric #define DEBUG_TYPE "split-module"
51044eb2f6SDimitry Andric 
5201095a5dSDimitry Andric namespace {
53044eb2f6SDimitry Andric 
54044eb2f6SDimitry Andric using ClusterMapType = EquivalenceClasses<const GlobalValue *>;
55044eb2f6SDimitry Andric using ComdatMembersType = DenseMap<const Comdat *, const GlobalValue *>;
56044eb2f6SDimitry Andric using ClusterIDMapType = DenseMap<const GlobalValue *, unsigned>;
57044eb2f6SDimitry Andric 
compareClusters(const std::pair<unsigned,unsigned> & A,const std::pair<unsigned,unsigned> & B)58ac9a064cSDimitry Andric bool compareClusters(const std::pair<unsigned, unsigned> &A,
59ac9a064cSDimitry Andric                      const std::pair<unsigned, unsigned> &B) {
60ac9a064cSDimitry Andric   if (A.second || B.second)
61ac9a064cSDimitry Andric     return A.second > B.second;
62ac9a064cSDimitry Andric   return A.first > B.first;
63ac9a064cSDimitry Andric }
64ac9a064cSDimitry Andric 
65ac9a064cSDimitry Andric using BalancingQueueType =
66ac9a064cSDimitry Andric     std::priority_queue<std::pair<unsigned, unsigned>,
67ac9a064cSDimitry Andric                         std::vector<std::pair<unsigned, unsigned>>,
68ac9a064cSDimitry Andric                         decltype(compareClusters) *>;
69ac9a064cSDimitry Andric 
70044eb2f6SDimitry Andric } // end anonymous namespace
7101095a5dSDimitry Andric 
addNonConstUser(ClusterMapType & GVtoClusterMap,const GlobalValue * GV,const User * U)7201095a5dSDimitry Andric static void addNonConstUser(ClusterMapType &GVtoClusterMap,
7301095a5dSDimitry Andric                             const GlobalValue *GV, const User *U) {
7401095a5dSDimitry Andric   assert((!isa<Constant>(U) || isa<GlobalValue>(U)) && "Bad user");
7501095a5dSDimitry Andric 
7601095a5dSDimitry Andric   if (const Instruction *I = dyn_cast<Instruction>(U)) {
7701095a5dSDimitry Andric     const GlobalValue *F = I->getParent()->getParent();
7801095a5dSDimitry Andric     GVtoClusterMap.unionSets(GV, F);
79c0981da4SDimitry Andric   } else if (const GlobalValue *GVU = dyn_cast<GlobalValue>(U)) {
80c0981da4SDimitry Andric     GVtoClusterMap.unionSets(GV, GVU);
8101095a5dSDimitry Andric   } else {
8201095a5dSDimitry Andric     llvm_unreachable("Underimplemented use case");
8301095a5dSDimitry Andric   }
8401095a5dSDimitry Andric }
8501095a5dSDimitry Andric 
8601095a5dSDimitry Andric // Adds all GlobalValue users of V to the same cluster as GV.
addAllGlobalValueUsers(ClusterMapType & GVtoClusterMap,const GlobalValue * GV,const Value * V)8701095a5dSDimitry Andric static void addAllGlobalValueUsers(ClusterMapType &GVtoClusterMap,
8801095a5dSDimitry Andric                                    const GlobalValue *GV, const Value *V) {
89e3b55780SDimitry Andric   for (const auto *U : V->users()) {
9001095a5dSDimitry Andric     SmallVector<const User *, 4> Worklist;
9101095a5dSDimitry Andric     Worklist.push_back(U);
9201095a5dSDimitry Andric     while (!Worklist.empty()) {
9301095a5dSDimitry Andric       const User *UU = Worklist.pop_back_val();
9401095a5dSDimitry Andric       // For each constant that is not a GV (a pure const) recurse.
9501095a5dSDimitry Andric       if (isa<Constant>(UU) && !isa<GlobalValue>(UU)) {
9601095a5dSDimitry Andric         Worklist.append(UU->user_begin(), UU->user_end());
9701095a5dSDimitry Andric         continue;
9801095a5dSDimitry Andric       }
9901095a5dSDimitry Andric       addNonConstUser(GVtoClusterMap, GV, UU);
10001095a5dSDimitry Andric     }
10101095a5dSDimitry Andric   }
10201095a5dSDimitry Andric }
10301095a5dSDimitry Andric 
getGVPartitioningRoot(const GlobalValue * GV)104c0981da4SDimitry Andric static const GlobalObject *getGVPartitioningRoot(const GlobalValue *GV) {
105c0981da4SDimitry Andric   const GlobalObject *GO = GV->getAliaseeObject();
106c0981da4SDimitry Andric   if (const auto *GI = dyn_cast_or_null<GlobalIFunc>(GO))
107c0981da4SDimitry Andric     GO = GI->getResolverFunction();
108c0981da4SDimitry Andric   return GO;
109c0981da4SDimitry Andric }
110c0981da4SDimitry Andric 
11101095a5dSDimitry Andric // Find partitions for module in the way that no locals need to be
11201095a5dSDimitry Andric // globalized.
11301095a5dSDimitry Andric // Try to balance pack those partitions into N files since this roughly equals
11401095a5dSDimitry Andric // thread balancing for the backend codegen step.
findPartitions(Module & M,ClusterIDMapType & ClusterIDMap,unsigned N)115344a3780SDimitry Andric static void findPartitions(Module &M, ClusterIDMapType &ClusterIDMap,
11601095a5dSDimitry Andric                            unsigned N) {
11701095a5dSDimitry Andric   // At this point module should have the proper mix of globals and locals.
11801095a5dSDimitry Andric   // As we attempt to partition this module, we must not change any
11901095a5dSDimitry Andric   // locals to globals.
120ac9a064cSDimitry Andric   LLVM_DEBUG(dbgs() << "Partition module with (" << M.size()
121ac9a064cSDimitry Andric                     << ") functions\n");
12201095a5dSDimitry Andric   ClusterMapType GVtoClusterMap;
12301095a5dSDimitry Andric   ComdatMembersType ComdatMembers;
12401095a5dSDimitry Andric 
12501095a5dSDimitry Andric   auto recordGVSet = [&GVtoClusterMap, &ComdatMembers](GlobalValue &GV) {
12601095a5dSDimitry Andric     if (GV.isDeclaration())
12701095a5dSDimitry Andric       return;
12801095a5dSDimitry Andric 
12901095a5dSDimitry Andric     if (!GV.hasName())
13001095a5dSDimitry Andric       GV.setName("__llvmsplit_unnamed");
13101095a5dSDimitry Andric 
13201095a5dSDimitry Andric     // Comdat groups must not be partitioned. For comdat groups that contain
13301095a5dSDimitry Andric     // locals, record all their members here so we can keep them together.
13401095a5dSDimitry Andric     // Comdat groups that only contain external globals are already handled by
13501095a5dSDimitry Andric     // the MD5-based partitioning.
13601095a5dSDimitry Andric     if (const Comdat *C = GV.getComdat()) {
13701095a5dSDimitry Andric       auto &Member = ComdatMembers[C];
13801095a5dSDimitry Andric       if (Member)
13901095a5dSDimitry Andric         GVtoClusterMap.unionSets(Member, &GV);
14001095a5dSDimitry Andric       else
14101095a5dSDimitry Andric         Member = &GV;
14201095a5dSDimitry Andric     }
14301095a5dSDimitry Andric 
144c0981da4SDimitry Andric     // Aliases should not be separated from their aliasees and ifuncs should
145c0981da4SDimitry Andric     // not be separated from their resolvers regardless of linkage.
146c0981da4SDimitry Andric     if (const GlobalObject *Root = getGVPartitioningRoot(&GV))
147c0981da4SDimitry Andric       if (&GV != Root)
148c0981da4SDimitry Andric         GVtoClusterMap.unionSets(&GV, Root);
14901095a5dSDimitry Andric 
15001095a5dSDimitry Andric     if (const Function *F = dyn_cast<Function>(&GV)) {
15101095a5dSDimitry Andric       for (const BasicBlock &BB : *F) {
15201095a5dSDimitry Andric         BlockAddress *BA = BlockAddress::lookup(&BB);
15301095a5dSDimitry Andric         if (!BA || !BA->isConstantUsed())
15401095a5dSDimitry Andric           continue;
15501095a5dSDimitry Andric         addAllGlobalValueUsers(GVtoClusterMap, F, BA);
15601095a5dSDimitry Andric       }
15701095a5dSDimitry Andric     }
15801095a5dSDimitry Andric 
15901095a5dSDimitry Andric     if (GV.hasLocalLinkage())
16001095a5dSDimitry Andric       addAllGlobalValueUsers(GVtoClusterMap, &GV, &GV);
16101095a5dSDimitry Andric   };
16201095a5dSDimitry Andric 
163344a3780SDimitry Andric   llvm::for_each(M.functions(), recordGVSet);
164344a3780SDimitry Andric   llvm::for_each(M.globals(), recordGVSet);
165344a3780SDimitry Andric   llvm::for_each(M.aliases(), recordGVSet);
16601095a5dSDimitry Andric 
16701095a5dSDimitry Andric   // Assigned all GVs to merged clusters while balancing number of objects in
16801095a5dSDimitry Andric   // each.
169ac9a064cSDimitry Andric   BalancingQueueType BalancingQueue(compareClusters);
17001095a5dSDimitry Andric   // Pre-populate priority queue with N slot blanks.
17101095a5dSDimitry Andric   for (unsigned i = 0; i < N; ++i)
172ac9a064cSDimitry Andric     BalancingQueue.push(std::make_pair(i, 0));
17301095a5dSDimitry Andric 
174044eb2f6SDimitry Andric   using SortType = std::pair<unsigned, ClusterMapType::iterator>;
175044eb2f6SDimitry Andric 
17601095a5dSDimitry Andric   SmallVector<SortType, 64> Sets;
17701095a5dSDimitry Andric   SmallPtrSet<const GlobalValue *, 32> Visited;
17801095a5dSDimitry Andric 
17901095a5dSDimitry Andric   // To guarantee determinism, we have to sort SCC according to size.
18001095a5dSDimitry Andric   // When size is the same, use leader's name.
18101095a5dSDimitry Andric   for (ClusterMapType::iterator I = GVtoClusterMap.begin(),
182ac9a064cSDimitry Andric                                 E = GVtoClusterMap.end();
183ac9a064cSDimitry Andric        I != E; ++I)
18401095a5dSDimitry Andric     if (I->isLeader())
18501095a5dSDimitry Andric       Sets.push_back(
18601095a5dSDimitry Andric           std::make_pair(std::distance(GVtoClusterMap.member_begin(I),
187ac9a064cSDimitry Andric                                        GVtoClusterMap.member_end()),
188ac9a064cSDimitry Andric                          I));
18901095a5dSDimitry Andric 
190d8e91e46SDimitry Andric   llvm::sort(Sets, [](const SortType &a, const SortType &b) {
19101095a5dSDimitry Andric     if (a.first == b.first)
192d8e91e46SDimitry Andric       return a.second->getData()->getName() > b.second->getData()->getName();
19301095a5dSDimitry Andric     else
19401095a5dSDimitry Andric       return a.first > b.first;
19501095a5dSDimitry Andric   });
19601095a5dSDimitry Andric 
19701095a5dSDimitry Andric   for (auto &I : Sets) {
198ac9a064cSDimitry Andric     unsigned CurrentClusterID = BalancingQueue.top().first;
199ac9a064cSDimitry Andric     unsigned CurrentClusterSize = BalancingQueue.top().second;
200ac9a064cSDimitry Andric     BalancingQueue.pop();
20101095a5dSDimitry Andric 
202eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Root[" << CurrentClusterID << "] cluster_size("
203eb11fae6SDimitry Andric                       << I.first << ") ----> " << I.second->getData()->getName()
204eb11fae6SDimitry Andric                       << "\n");
20501095a5dSDimitry Andric 
20601095a5dSDimitry Andric     for (ClusterMapType::member_iterator MI =
20701095a5dSDimitry Andric              GVtoClusterMap.findLeader(I.second);
20801095a5dSDimitry Andric          MI != GVtoClusterMap.member_end(); ++MI) {
20901095a5dSDimitry Andric       if (!Visited.insert(*MI).second)
21001095a5dSDimitry Andric         continue;
211eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "----> " << (*MI)->getName()
21201095a5dSDimitry Andric                         << ((*MI)->hasLocalLinkage() ? " l " : " e ") << "\n");
21301095a5dSDimitry Andric       Visited.insert(*MI);
21401095a5dSDimitry Andric       ClusterIDMap[*MI] = CurrentClusterID;
21501095a5dSDimitry Andric       CurrentClusterSize++;
21601095a5dSDimitry Andric     }
21701095a5dSDimitry Andric     // Add this set size to the number of entries in this cluster.
218ac9a064cSDimitry Andric     BalancingQueue.push(std::make_pair(CurrentClusterID, CurrentClusterSize));
21901095a5dSDimitry Andric   }
22001095a5dSDimitry Andric }
22101095a5dSDimitry Andric 
externalize(GlobalValue * GV)222dd58ef01SDimitry Andric static void externalize(GlobalValue *GV) {
223dd58ef01SDimitry Andric   if (GV->hasLocalLinkage()) {
224dd58ef01SDimitry Andric     GV->setLinkage(GlobalValue::ExternalLinkage);
225dd58ef01SDimitry Andric     GV->setVisibility(GlobalValue::HiddenVisibility);
226dd58ef01SDimitry Andric   }
227dd58ef01SDimitry Andric 
228dd58ef01SDimitry Andric   // Unnamed entities must be named consistently between modules. setName will
229dd58ef01SDimitry Andric   // give a distinct name to each such entity.
230dd58ef01SDimitry Andric   if (!GV->hasName())
231dd58ef01SDimitry Andric     GV->setName("__llvmsplit_unnamed");
232dd58ef01SDimitry Andric }
233dd58ef01SDimitry Andric 
234dd58ef01SDimitry Andric // Returns whether GV should be in partition (0-based) I of N.
isInPartition(const GlobalValue * GV,unsigned I,unsigned N)235dd58ef01SDimitry Andric static bool isInPartition(const GlobalValue *GV, unsigned I, unsigned N) {
236c0981da4SDimitry Andric   if (const GlobalObject *Root = getGVPartitioningRoot(GV))
237c0981da4SDimitry Andric     GV = Root;
238dd58ef01SDimitry Andric 
239dd58ef01SDimitry Andric   StringRef Name;
240dd58ef01SDimitry Andric   if (const Comdat *C = GV->getComdat())
241dd58ef01SDimitry Andric     Name = C->getName();
242dd58ef01SDimitry Andric   else
243dd58ef01SDimitry Andric     Name = GV->getName();
244dd58ef01SDimitry Andric 
245dd58ef01SDimitry Andric   // Partition by MD5 hash. We only need a few bits for evenness as the number
246dd58ef01SDimitry Andric   // of partitions will generally be in the 1-2 figure range; the low 16 bits
247dd58ef01SDimitry Andric   // are enough.
248dd58ef01SDimitry Andric   MD5 H;
249dd58ef01SDimitry Andric   MD5::MD5Result R;
250dd58ef01SDimitry Andric   H.update(Name);
251dd58ef01SDimitry Andric   H.final(R);
252dd58ef01SDimitry Andric   return (R[0] | (R[1] << 8)) % N == I;
253dd58ef01SDimitry Andric }
254dd58ef01SDimitry Andric 
SplitModule(Module & M,unsigned N,function_ref<void (std::unique_ptr<Module> MPart)> ModuleCallback,bool PreserveLocals,bool RoundRobin)255dd58ef01SDimitry Andric void llvm::SplitModule(
256344a3780SDimitry Andric     Module &M, unsigned N,
25701095a5dSDimitry Andric     function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback,
258ac9a064cSDimitry Andric     bool PreserveLocals, bool RoundRobin) {
25901095a5dSDimitry Andric   if (!PreserveLocals) {
260344a3780SDimitry Andric     for (Function &F : M)
261dd58ef01SDimitry Andric       externalize(&F);
262344a3780SDimitry Andric     for (GlobalVariable &GV : M.globals())
263dd58ef01SDimitry Andric       externalize(&GV);
264344a3780SDimitry Andric     for (GlobalAlias &GA : M.aliases())
265dd58ef01SDimitry Andric       externalize(&GA);
266344a3780SDimitry Andric     for (GlobalIFunc &GIF : M.ifuncs())
26701095a5dSDimitry Andric       externalize(&GIF);
26801095a5dSDimitry Andric   }
26901095a5dSDimitry Andric 
27001095a5dSDimitry Andric   // This performs splitting without a need for externalization, which might not
27101095a5dSDimitry Andric   // always be possible.
27201095a5dSDimitry Andric   ClusterIDMapType ClusterIDMap;
273344a3780SDimitry Andric   findPartitions(M, ClusterIDMap, N);
274dd58ef01SDimitry Andric 
275ac9a064cSDimitry Andric   // Find functions not mapped to modules in ClusterIDMap and count functions
276ac9a064cSDimitry Andric   // per module. Map unmapped functions using round-robin so that they skip
277ac9a064cSDimitry Andric   // being distributed by isInPartition() based on function name hashes below.
278ac9a064cSDimitry Andric   // This provides better uniformity of distribution of functions to modules
279ac9a064cSDimitry Andric   // in some cases - for example when the number of functions equals to N.
280ac9a064cSDimitry Andric   if (RoundRobin) {
281ac9a064cSDimitry Andric     DenseMap<unsigned, unsigned> ModuleFunctionCount;
282ac9a064cSDimitry Andric     SmallVector<const GlobalValue *> UnmappedFunctions;
283ac9a064cSDimitry Andric     for (const auto &F : M.functions()) {
284ac9a064cSDimitry Andric       if (F.isDeclaration() ||
285ac9a064cSDimitry Andric           F.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
286ac9a064cSDimitry Andric         continue;
287ac9a064cSDimitry Andric       auto It = ClusterIDMap.find(&F);
288ac9a064cSDimitry Andric       if (It == ClusterIDMap.end())
289ac9a064cSDimitry Andric         UnmappedFunctions.push_back(&F);
290ac9a064cSDimitry Andric       else
291ac9a064cSDimitry Andric         ++ModuleFunctionCount[It->second];
292ac9a064cSDimitry Andric     }
293ac9a064cSDimitry Andric     BalancingQueueType BalancingQueue(compareClusters);
294ac9a064cSDimitry Andric     for (unsigned I = 0; I < N; ++I) {
295ac9a064cSDimitry Andric       if (auto It = ModuleFunctionCount.find(I);
296ac9a064cSDimitry Andric           It != ModuleFunctionCount.end())
297ac9a064cSDimitry Andric         BalancingQueue.push(*It);
298ac9a064cSDimitry Andric       else
299ac9a064cSDimitry Andric         BalancingQueue.push({I, 0});
300ac9a064cSDimitry Andric     }
301ac9a064cSDimitry Andric     for (const auto *const F : UnmappedFunctions) {
302ac9a064cSDimitry Andric       const unsigned I = BalancingQueue.top().first;
303ac9a064cSDimitry Andric       const unsigned Count = BalancingQueue.top().second;
304ac9a064cSDimitry Andric       BalancingQueue.pop();
305ac9a064cSDimitry Andric       ClusterIDMap.insert({F, I});
306ac9a064cSDimitry Andric       BalancingQueue.push({I, Count + 1});
307ac9a064cSDimitry Andric     }
308ac9a064cSDimitry Andric   }
309ac9a064cSDimitry Andric 
310dd58ef01SDimitry Andric   // FIXME: We should be able to reuse M as the last partition instead of
311344a3780SDimitry Andric   // cloning it. Note that the callers at the moment expect the module to
312344a3780SDimitry Andric   // be preserved, so will need some adjustments as well.
31301095a5dSDimitry Andric   for (unsigned I = 0; I < N; ++I) {
314dd58ef01SDimitry Andric     ValueToValueMapTy VMap;
315dd58ef01SDimitry Andric     std::unique_ptr<Module> MPart(
316344a3780SDimitry Andric         CloneModule(M, VMap, [&](const GlobalValue *GV) {
317ac9a064cSDimitry Andric           if (auto It = ClusterIDMap.find(GV); It != ClusterIDMap.end())
318ac9a064cSDimitry Andric             return It->second == I;
31901095a5dSDimitry Andric           else
320dd58ef01SDimitry Andric             return isInPartition(GV, I, N);
321dd58ef01SDimitry Andric         }));
322dd58ef01SDimitry Andric     if (I != 0)
323dd58ef01SDimitry Andric       MPart->setModuleInlineAsm("");
324dd58ef01SDimitry Andric     ModuleCallback(std::move(MPart));
325dd58ef01SDimitry Andric   }
326dd58ef01SDimitry Andric }
327