xref: /llvm-project/llvm/lib/Transforms/Utils/SplitModule.cpp (revision d19d4d30d84cf6befcda72ff957bf31a7e4e7335)
1 //===- SplitModule.cpp - Split a module into partitions -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the function llvm::SplitModule, which splits a module
11 // into multiple linkable partitions. It can be used to implement parallel code
12 // generation for link-time optimization.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #define DEBUG_TYPE "split-module"
17 
18 #include "llvm/Transforms/Utils/SplitModule.h"
19 #include "llvm/ADT/EquivalenceClasses.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/MapVector.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalAlias.h"
25 #include "llvm/IR/GlobalObject.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MD5.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include <queue>
34 
35 using namespace llvm;
36 
37 namespace {
38 typedef EquivalenceClasses<const GlobalValue *> ClusterMapType;
39 typedef DenseMap<const Comdat *, const GlobalValue *> ComdatMembersType;
40 typedef DenseMap<const GlobalValue *, unsigned> ClusterIDMapType;
41 }
42 
43 static void addNonConstUser(ClusterMapType &GVtoClusterMap,
44                             const GlobalValue *GV, const User *U) {
45   assert((!isa<Constant>(U) || isa<GlobalValue>(U)) && "Bad user");
46 
47   if (const Instruction *I = dyn_cast<Instruction>(U)) {
48     const GlobalValue *F = I->getParent()->getParent();
49     GVtoClusterMap.unionSets(GV, F);
50   } else if (isa<GlobalAlias>(U) || isa<Function>(U) ||
51              isa<GlobalVariable>(U)) {
52     GVtoClusterMap.unionSets(GV, cast<GlobalValue>(U));
53   } else {
54     llvm_unreachable("Underimplemented use case");
55   }
56 }
57 
58 // Find partitions for module in the way that no locals need to be
59 // globalized.
60 // Try to balance pack those partitions into N files since this roughly equals
61 // thread balancing for the backend codegen step.
62 static void findPartitions(Module *M, ClusterIDMapType &ClusterIDMap,
63                            unsigned N) {
64   // At this point module should have the proper mix of globals and locals.
65   // As we attempt to partition this module, we must not change any
66   // locals to globals.
67 
68   DEBUG(dbgs() << "Partition module with (" << M->size() << ")functions\n");
69   ClusterMapType GVtoClusterMap;
70   ComdatMembersType ComdatMembers;
71 
72   auto recordGVSet = [&GVtoClusterMap, &ComdatMembers](GlobalValue &GV) {
73     if (GV.isDeclaration())
74       return;
75 
76     if (!GV.hasName())
77       GV.setName("__llvmsplit_unnamed");
78 
79     // Comdat groups must not be partitioned. For comdat groups that contain
80     // locals, record all their members here so we can keep them together.
81     // Comdat groups that only contain external globals are already handled by
82     // the MD5-based partitioning.
83     if (const Comdat *C = GV.getComdat()) {
84       auto &Member = ComdatMembers[C];
85       if (Member)
86         GVtoClusterMap.unionSets(Member, &GV);
87       else
88         Member = &GV;
89     }
90 
91     // Further only iterate over local GVs.
92     if (!GV.hasLocalLinkage())
93       return;
94 
95     for (auto *U : GV.users()) {
96       SmallVector<const User *, 4> Worklist;
97       Worklist.push_back(U);
98       while (!Worklist.empty()) {
99         const User *UU = Worklist.pop_back_val();
100         // For each constant that is not a GV (a pure const) recurse.
101         if (isa<Constant>(UU) && !isa<GlobalValue>(UU)) {
102           Worklist.append(UU->user_begin(), UU->user_end());
103           continue;
104         }
105         addNonConstUser(GVtoClusterMap, &GV, UU);
106       }
107     }
108   };
109 
110   std::for_each(M->begin(), M->end(), recordGVSet);
111   std::for_each(M->global_begin(), M->global_end(), recordGVSet);
112   std::for_each(M->alias_begin(), M->alias_end(), recordGVSet);
113 
114   // Assigned all GVs to merged clusters while balancing number of objects in
115   // each.
116   auto CompareClusters = [](const std::pair<unsigned, unsigned> &a,
117                             const std::pair<unsigned, unsigned> &b) {
118     if (a.second || b.second)
119       return a.second > b.second;
120     else
121       return a.first > b.first;
122   };
123 
124   std::priority_queue<std::pair<unsigned, unsigned>,
125                       std::vector<std::pair<unsigned, unsigned>>,
126                       decltype(CompareClusters)>
127       BalancinQueue(CompareClusters);
128   // Pre-populate priority queue with N slot blanks.
129   for (unsigned i = 0; i < N; ++i)
130     BalancinQueue.push(std::make_pair(i, 0));
131 
132   typedef std::pair<unsigned, ClusterMapType::iterator> SortType;
133   SmallVector<SortType, 64> Sets;
134   SmallPtrSet<const GlobalValue *, 64> Visited;
135 
136   // To guarantee determinism, we have to sort SCC according to size.
137   // When size is the same, use leader's name.
138   for (ClusterMapType::iterator I = GVtoClusterMap.begin(),
139                                 E = GVtoClusterMap.end(); I != E; ++I)
140     if (I->isLeader())
141       Sets.push_back(
142           std::make_pair(std::distance(GVtoClusterMap.member_begin(I),
143                                        GVtoClusterMap.member_end()), I));
144 
145   std::sort(Sets.begin(), Sets.end(), [](const SortType &a, const SortType &b) {
146     if (a.first == b.first)
147       return a.second->getData()->getName() > b.second->getData()->getName();
148     else
149       return a.first > b.first;
150   });
151 
152   for (auto &I : Sets) {
153     unsigned CurrentClusterID = BalancinQueue.top().first;
154     unsigned CurrentClusterSize = BalancinQueue.top().second;
155     BalancinQueue.pop();
156 
157     DEBUG(dbgs() << "Root[" << CurrentClusterID << "] cluster_size(" << I.first
158                  << ") ----> " << I.second->getData()->getName() << "\n");
159 
160     for (ClusterMapType::member_iterator MI =
161              GVtoClusterMap.findLeader(I.second);
162          MI != GVtoClusterMap.member_end(); ++MI) {
163       if (!Visited.insert(*MI).second)
164         continue;
165       DEBUG(dbgs() << "----> " << (*MI)->getName()
166                    << ((*MI)->hasLocalLinkage() ? " l " : " e ") << "\n");
167       Visited.insert(*MI);
168       ClusterIDMap[*MI] = CurrentClusterID;
169       CurrentClusterSize++;
170     }
171     // Add this set size to the number of entries in this cluster.
172     BalancinQueue.push(std::make_pair(CurrentClusterID, CurrentClusterSize));
173   }
174 }
175 
176 static void externalize(GlobalValue *GV) {
177   if (GV->hasLocalLinkage()) {
178     GV->setLinkage(GlobalValue::ExternalLinkage);
179     GV->setVisibility(GlobalValue::HiddenVisibility);
180   }
181 
182   // Unnamed entities must be named consistently between modules. setName will
183   // give a distinct name to each such entity.
184   if (!GV->hasName())
185     GV->setName("__llvmsplit_unnamed");
186 }
187 
188 // Returns whether GV should be in partition (0-based) I of N.
189 static bool isInPartition(const GlobalValue *GV, unsigned I, unsigned N) {
190   if (auto GA = dyn_cast<GlobalAlias>(GV))
191     if (const GlobalObject *Base = GA->getBaseObject())
192       GV = Base;
193 
194   StringRef Name;
195   if (const Comdat *C = GV->getComdat())
196     Name = C->getName();
197   else
198     Name = GV->getName();
199 
200   // Partition by MD5 hash. We only need a few bits for evenness as the number
201   // of partitions will generally be in the 1-2 figure range; the low 16 bits
202   // are enough.
203   MD5 H;
204   MD5::MD5Result R;
205   H.update(Name);
206   H.final(R);
207   return (R[0] | (R[1] << 8)) % N == I;
208 }
209 
210 void llvm::SplitModule(
211     std::unique_ptr<Module> M, unsigned N,
212     std::function<void(std::unique_ptr<Module> MPart)> ModuleCallback,
213     bool PreserveLocals) {
214   if (!PreserveLocals) {
215     for (Function &F : *M)
216       externalize(&F);
217     for (GlobalVariable &GV : M->globals())
218       externalize(&GV);
219     for (GlobalAlias &GA : M->aliases())
220       externalize(&GA);
221 
222     // FIXME: We should be able to reuse M as the last partition instead of
223     // cloning it.
224     for (unsigned I = 0; I != N; ++I) {
225       ValueToValueMapTy VMap;
226       std::unique_ptr<Module> MPart(
227           CloneModule(M.get(), VMap, [=](const GlobalValue *GV) {
228             return isInPartition(GV, I, N);
229           }));
230       if (I != 0)
231         MPart->setModuleInlineAsm("");
232       ModuleCallback(std::move(MPart));
233     }
234   } else {
235     // This performs splitting without a need for externalization, which might not
236     // always be possible.
237     ClusterIDMapType ClusterIDMap;
238     findPartitions(M.get(), ClusterIDMap, N);
239 
240     for (unsigned I = 0; I < N; ++I) {
241       ValueToValueMapTy VMap;
242       std::unique_ptr<Module> MPart(
243           CloneModule(M.get(), VMap, [&](const GlobalValue *GV) {
244              if (ClusterIDMap.count(GV))
245                return (ClusterIDMap[GV] == I);
246              else
247                return isInPartition(GV, I, N);
248           }));
249       if (I != 0)
250         MPart->setModuleInlineAsm("");
251       ModuleCallback(std::move(MPart));
252     }
253   }
254 }
255