blob: 457d7d647b1a64853d17d6c518afc2ec959e23d8 [file] [log] [blame]
Devang Patel827454e2011-10-17 17:17:43 +00001//===-- GlobalMerge.cpp - Internal globals merging -----------------------===//
Anton Korobeynikovcec36f42010-07-24 21:52:08 +00002//
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// This pass merges globals with internal linkage into one. This way all the
10// globals which were merged into a biggest one can be addressed using offsets
11// from the same base pointer (no need for separate base pointer for each of the
12// global). Such a transformation can significantly reduce the register pressure
13// when many globals are involved.
14//
Nadav Rotema94d6e82012-07-24 10:51:42 +000015// For example, consider the code which touches several global variables at
Eric Christophera99c3e92010-09-28 04:18:29 +000016// once:
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000017//
18// static int foo[N], bar[N], baz[N];
19//
20// for (i = 0; i < N; ++i) {
21// foo[i] = bar[i] * baz[i];
22// }
23//
24// On ARM the addresses of 3 arrays should be kept in the registers, thus
25// this code has quite large register pressure (loop body):
26//
27// ldr r1, [r5], #4
28// ldr r2, [r6], #4
29// mul r1, r2, r1
30// str r1, [r0], #4
31//
32// Pass converts the code to something like:
33//
34// static struct {
35// int foo[N];
36// int bar[N];
37// int baz[N];
38// } merged;
39//
40// for (i = 0; i < N; ++i) {
41// merged.foo[i] = merged.bar[i] * merged.baz[i];
42// }
43//
44// and in ARM code this becomes:
45//
46// ldr r0, [r5, #40]
47// ldr r1, [r5, #80]
48// mul r0, r1, r0
49// str r0, [r5], #4
50//
51// note that we saved 2 registers here almostly "for free".
Eric Christophera99c3e92010-09-28 04:18:29 +000052// ===---------------------------------------------------------------------===//
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000053
Devang Patel827454e2011-10-17 17:17:43 +000054#include "llvm/Transforms/Scalar.h"
Quentin Colombete5728092013-03-18 22:30:07 +000055#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000056#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000057#include "llvm/IR/Attributes.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/DerivedTypes.h"
61#include "llvm/IR/Function.h"
62#include "llvm/IR/GlobalVariable.h"
63#include "llvm/IR/Instructions.h"
64#include "llvm/IR/Intrinsics.h"
65#include "llvm/IR/Module.h"
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000066#include "llvm/Pass.h"
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070067#include "llvm/CodeGen/Passes.h"
Quentin Colombete5728092013-03-18 22:30:07 +000068#include "llvm/Support/CommandLine.h"
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000069#include "llvm/Target/TargetLowering.h"
Bob Wilson05646092010-11-17 21:25:39 +000070#include "llvm/Target/TargetLoweringObjectFile.h"
Stephen Hines37ed9c12014-12-01 14:51:49 -080071#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000072using namespace llvm;
73
Stephen Hinesdce4a402014-05-29 02:49:00 -070074#define DEBUG_TYPE "global-merge"
75
Stephen Hines36b56882014-04-23 16:57:46 -070076cl::opt<bool>
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070077EnableGlobalMerge("enable-global-merge", cl::Hidden,
Stephen Hines36b56882014-04-23 16:57:46 -070078 cl::desc("Enable global merge pass"),
79 cl::init(true));
80
Quentin Colombete5728092013-03-18 22:30:07 +000081static cl::opt<bool>
82EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
Jakub Staszakdca13e02013-07-22 21:11:30 +000083 cl::desc("Enable global merge pass on constants"),
84 cl::init(false));
Quentin Colombete5728092013-03-18 22:30:07 +000085
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070086// FIXME: this could be a transitional option, and we probably need to remove
87// it if only we are sure this optimization could always benefit all targets.
88static cl::opt<bool>
89EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
90 cl::desc("Enable global merge pass on external linkage"),
91 cl::init(false));
92
Devang Patel827454e2011-10-17 17:17:43 +000093STATISTIC(NumMerged , "Number of globals merged");
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000094namespace {
Devang Patel827454e2011-10-17 17:17:43 +000095 class GlobalMerge : public FunctionPass {
Bill Wendlingf9fd58a2013-06-19 21:07:11 +000096 const TargetMachine *TM;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000097
98 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangae9716592013-01-07 12:31:25 +000099 Module &M, bool isConst, unsigned AddrSpace) const;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000100
Quentin Colombete5728092013-03-18 22:30:07 +0000101 /// \brief Check if the given variable has been identified as must keep
102 /// \pre setMustKeepGlobalVariables must have been called on the Module that
103 /// contains GV
104 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
105 return MustKeepGlobalVariables.count(GV);
106 }
107
108 /// Collect every variables marked as "used" or used in a landing pad
109 /// instruction for this Module.
110 void setMustKeepGlobalVariables(Module &M);
111
112 /// Collect every variables marked as "used"
113 void collectUsedGlobalVariables(Module &M);
114
Quentin Colombet9deb9172013-03-19 21:46:49 +0000115 /// Keep track of the GlobalVariable that must not be merged away
Quentin Colombete5728092013-03-18 22:30:07 +0000116 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
117
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000118 public:
119 static char ID; // Pass identification, replacement for typeid.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700120 explicit GlobalMerge(const TargetMachine *TM = nullptr)
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000121 : FunctionPass(ID), TM(TM) {
Devang Patel827454e2011-10-17 17:17:43 +0000122 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
123 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000124
Stephen Hines36b56882014-04-23 16:57:46 -0700125 bool doInitialization(Module &M) override;
126 bool runOnFunction(Function &F) override;
127 bool doFinalization(Module &M) override;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000128
Stephen Hines36b56882014-04-23 16:57:46 -0700129 const char *getPassName() const override {
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000130 return "Merge internal globals";
131 }
132
Stephen Hines36b56882014-04-23 16:57:46 -0700133 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000134 AU.setPreservesCFG();
135 FunctionPass::getAnalysisUsage(AU);
136 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000137 };
138} // end anonymous namespace
139
Devang Patel827454e2011-10-17 17:17:43 +0000140char GlobalMerge::ID = 0;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700141INITIALIZE_TM_PASS(GlobalMerge, "global-merge", "Merge global variables",
142 false, false)
Devang Patel827454e2011-10-17 17:17:43 +0000143
144bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangae9716592013-01-07 12:31:25 +0000145 Module &M, bool isConst, unsigned AddrSpace) const {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800146 const TargetLowering *TLI = TM->getSubtargetImpl()->getTargetLowering();
Stephen Hines36b56882014-04-23 16:57:46 -0700147 const DataLayout *DL = TLI->getDataLayout();
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000148
149 // FIXME: Infer the maximum possible offset depending on the actual users
150 // (these max offsets are different for the users inside Thumb or ARM
151 // functions)
152 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
153
154 // FIXME: Find better heuristics
Stephen Hines36b56882014-04-23 16:57:46 -0700155 std::stable_sort(Globals.begin(), Globals.end(),
156 [DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
157 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
158 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
159
160 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
161 });
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000162
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000163 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000164
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700165 assert(Globals.size() > 1);
166
167 // FIXME: This simple solution merges globals all together as maximum as
168 // possible. However, with this solution it would be hard to remove dead
169 // global symbols at link-time. An alternative solution could be checking
170 // global symbols references function by function, and make the symbols
171 // being referred in the same function merged and we would probably need
172 // to introduce heuristic algorithm to solve the merge conflict from
173 // different functions.
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000174 for (size_t i = 0, e = Globals.size(); i != e; ) {
175 size_t j = 0;
176 uint64_t MergedSize = 0;
Jay Foad5fdd6c82011-07-12 14:06:48 +0000177 std::vector<Type*> Tys;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000178 std::vector<Constant*> Inits;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700179
180 bool HasExternal = false;
181 GlobalVariable *TheFirstExternal = 0;
Bob Wilson619a3722010-11-17 21:25:36 +0000182 for (j = i; j != e; ++j) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000183 Type *Ty = Globals[j]->getType()->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700184 MergedSize += DL->getTypeAllocSize(Ty);
Bob Wilson619a3722010-11-17 21:25:36 +0000185 if (MergedSize > MaxOffset) {
186 break;
187 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000188 Tys.push_back(Ty);
189 Inits.push_back(Globals[j]->getInitializer());
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700190
191 if (Globals[j]->hasExternalLinkage() && !HasExternal) {
192 HasExternal = true;
193 TheFirstExternal = Globals[j];
194 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000195 }
196
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700197 // If merged variables doesn't have external linkage, we needn't to expose
198 // the symbol after merging.
199 GlobalValue::LinkageTypes Linkage = HasExternal
200 ? GlobalValue::ExternalLinkage
201 : GlobalValue::InternalLinkage;
202
Chris Lattner252b4912010-09-05 21:18:45 +0000203 StructType *MergedTy = StructType::get(M.getContext(), Tys);
204 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700205
206 // If merged variables have external linkage, we use symbol name of the
207 // first variable merged as the suffix of global symbol name. This would
208 // be able to avoid the link-time naming conflict for globalm symbols.
209 GlobalVariable *MergedGV = new GlobalVariable(
210 M, MergedTy, isConst, Linkage, MergedInit,
211 HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName()
212 : "_MergedGlobals",
213 nullptr, GlobalVariable::NotThreadLocal, AddrSpace);
214
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000215 for (size_t k = i; k < j; ++k) {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700216 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
217 std::string Name = Globals[k]->getName();
218
Chris Lattner252b4912010-09-05 21:18:45 +0000219 Constant *Idx[2] = {
220 ConstantInt::get(Int32Ty, 0),
221 ConstantInt::get(Int32Ty, k-i)
222 };
Jay Foaddab3d292011-07-21 14:31:17 +0000223 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000224 Globals[k]->replaceAllUsesWith(GEP);
225 Globals[k]->eraseFromParent();
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700226
227 if (Linkage != GlobalValue::InternalLinkage) {
228 // Generate a new alias...
229 auto *PTy = cast<PointerType>(GEP->getType());
230 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
231 Linkage, Name, GEP, &M);
232 }
233
Devang Patel827454e2011-10-17 17:17:43 +0000234 NumMerged++;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000235 }
236 i = j;
237 }
238
239 return true;
240}
241
Quentin Colombete5728092013-03-18 22:30:07 +0000242void GlobalMerge::collectUsedGlobalVariables(Module &M) {
243 // Extract global variables from llvm.used array
244 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
245 if (!GV || !GV->hasInitializer()) return;
246
247 // Should be an array of 'i8*'.
Rafael Espindolacde25b42013-04-22 14:58:02 +0000248 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
249
Quentin Colombete5728092013-03-18 22:30:07 +0000250 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
251 if (const GlobalVariable *G =
252 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
253 MustKeepGlobalVariables.insert(G);
254}
255
256void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
Quentin Colombete5728092013-03-18 22:30:07 +0000257 collectUsedGlobalVariables(M);
258
259 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
260 ++IFn) {
261 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
262 IBB != IEndBB; ++IBB) {
Stephen Hines36b56882014-04-23 16:57:46 -0700263 // Follow the invoke link to find the landing pad instruction
Quentin Colombete5728092013-03-18 22:30:07 +0000264 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
265 if (!II) continue;
266
267 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
268 // Look for globals in the clauses of the landing pad instruction
269 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
270 Idx != NumClauses; ++Idx)
271 if (const GlobalVariable *GV =
272 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
273 ->stripPointerCasts()))
274 MustKeepGlobalVariables.insert(GV);
275 }
276 }
277}
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000278
Devang Patel827454e2011-10-17 17:17:43 +0000279bool GlobalMerge::doInitialization(Module &M) {
Stephen Hines36b56882014-04-23 16:57:46 -0700280 if (!EnableGlobalMerge)
281 return false;
282
Silviu Barangae9716592013-01-07 12:31:25 +0000283 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
284 BSSGlobals;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800285 const TargetLowering *TLI = TM->getSubtargetImpl()->getTargetLowering();
Stephen Hines36b56882014-04-23 16:57:46 -0700286 const DataLayout *DL = TLI->getDataLayout();
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000287 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
288 bool Changed = false;
Quentin Colombete5728092013-03-18 22:30:07 +0000289 setMustKeepGlobalVariables(M);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000290
291 // Grab all non-const globals.
292 for (Module::global_iterator I = M.global_begin(),
293 E = M.global_end(); I != E; ++I) {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700294 // Merge is safe for "normal" internal or external globals only
295 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
296 continue;
297
298 if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
299 !I->hasInternalLinkage())
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000300 continue;
301
Silviu Barangae9716592013-01-07 12:31:25 +0000302 PointerType *PT = dyn_cast<PointerType>(I->getType());
303 assert(PT && "Global variable is not a pointer!");
304
305 unsigned AddressSpace = PT->getAddressSpace();
306
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000307 // Ignore fancy-aligned globals for now.
Stephen Hines36b56882014-04-23 16:57:46 -0700308 unsigned Alignment = DL->getPreferredAlignment(I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000309 Type *Ty = I->getType()->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700310 if (Alignment > DL->getABITypeAlignment(Ty))
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000311 continue;
312
Anton Korobeynikovb5a0ef92010-07-26 18:45:39 +0000313 // Ignore all 'special' globals.
314 if (I->getName().startswith("llvm.") ||
315 I->getName().startswith(".llvm."))
316 continue;
317
Quentin Colombete5728092013-03-18 22:30:07 +0000318 // Ignore all "required" globals:
Quentin Colombete5728092013-03-18 22:30:07 +0000319 if (isMustKeepGlobalVariable(I))
320 continue;
321
Stephen Hines36b56882014-04-23 16:57:46 -0700322 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700323 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
Silviu Barangae9716592013-01-07 12:31:25 +0000324 BSSGlobals[AddressSpace].push_back(I);
Bob Wilson05646092010-11-17 21:25:39 +0000325 else if (I->isConstant())
Silviu Barangae9716592013-01-07 12:31:25 +0000326 ConstGlobals[AddressSpace].push_back(I);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000327 else
Silviu Barangae9716592013-01-07 12:31:25 +0000328 Globals[AddressSpace].push_back(I);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000329 }
330 }
331
Silviu Barangae9716592013-01-07 12:31:25 +0000332 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
333 I = Globals.begin(), E = Globals.end(); I != E; ++I)
334 if (I->second.size() > 1)
335 Changed |= doMerge(I->second, M, false, I->first);
336
337 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
338 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
339 if (I->second.size() > 1)
340 Changed |= doMerge(I->second, M, false, I->first);
Bob Wilson05646092010-11-17 21:25:39 +0000341
Quentin Colombete5728092013-03-18 22:30:07 +0000342 if (EnableGlobalMergeOnConst)
343 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
344 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
345 if (I->second.size() > 1)
346 Changed |= doMerge(I->second, M, true, I->first);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000347
348 return Changed;
349}
350
Devang Patel827454e2011-10-17 17:17:43 +0000351bool GlobalMerge::runOnFunction(Function &F) {
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000352 return false;
353}
354
Quentin Colombet9deb9172013-03-19 21:46:49 +0000355bool GlobalMerge::doFinalization(Module &M) {
356 MustKeepGlobalVariables.clear();
357 return false;
358}
359
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000360Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
361 return new GlobalMerge(TM);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000362}