blob: 990d0677e24efdc6e750fbf2e4c85617c8e3fbf8 [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"
Quentin Colombete5728092013-03-18 22:30:07 +000067#include "llvm/Support/CommandLine.h"
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000068#include "llvm/Target/TargetLowering.h"
Bob Wilson05646092010-11-17 21:25:39 +000069#include "llvm/Target/TargetLoweringObjectFile.h"
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000070using namespace llvm;
71
Stephen Hinesdce4a402014-05-29 02:49:00 -070072#define DEBUG_TYPE "global-merge"
73
Stephen Hines36b56882014-04-23 16:57:46 -070074cl::opt<bool>
75EnableGlobalMerge("global-merge", cl::Hidden,
76 cl::desc("Enable global merge pass"),
77 cl::init(true));
78
Quentin Colombete5728092013-03-18 22:30:07 +000079static cl::opt<bool>
80EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
Jakub Staszakdca13e02013-07-22 21:11:30 +000081 cl::desc("Enable global merge pass on constants"),
82 cl::init(false));
Quentin Colombete5728092013-03-18 22:30:07 +000083
Devang Patel827454e2011-10-17 17:17:43 +000084STATISTIC(NumMerged , "Number of globals merged");
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000085namespace {
Devang Patel827454e2011-10-17 17:17:43 +000086 class GlobalMerge : public FunctionPass {
Bill Wendlingf9fd58a2013-06-19 21:07:11 +000087 const TargetMachine *TM;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000088
89 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangae9716592013-01-07 12:31:25 +000090 Module &M, bool isConst, unsigned AddrSpace) const;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +000091
Quentin Colombete5728092013-03-18 22:30:07 +000092 /// \brief Check if the given variable has been identified as must keep
93 /// \pre setMustKeepGlobalVariables must have been called on the Module that
94 /// contains GV
95 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
96 return MustKeepGlobalVariables.count(GV);
97 }
98
99 /// Collect every variables marked as "used" or used in a landing pad
100 /// instruction for this Module.
101 void setMustKeepGlobalVariables(Module &M);
102
103 /// Collect every variables marked as "used"
104 void collectUsedGlobalVariables(Module &M);
105
Quentin Colombet9deb9172013-03-19 21:46:49 +0000106 /// Keep track of the GlobalVariable that must not be merged away
Quentin Colombete5728092013-03-18 22:30:07 +0000107 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
108
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000109 public:
110 static char ID; // Pass identification, replacement for typeid.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700111 explicit GlobalMerge(const TargetMachine *TM = nullptr)
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000112 : FunctionPass(ID), TM(TM) {
Devang Patel827454e2011-10-17 17:17:43 +0000113 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
114 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000115
Stephen Hines36b56882014-04-23 16:57:46 -0700116 bool doInitialization(Module &M) override;
117 bool runOnFunction(Function &F) override;
118 bool doFinalization(Module &M) override;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000119
Stephen Hines36b56882014-04-23 16:57:46 -0700120 const char *getPassName() const override {
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000121 return "Merge internal globals";
122 }
123
Stephen Hines36b56882014-04-23 16:57:46 -0700124 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000125 AU.setPreservesCFG();
126 FunctionPass::getAnalysisUsage(AU);
127 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000128 };
129} // end anonymous namespace
130
Devang Patel827454e2011-10-17 17:17:43 +0000131char GlobalMerge::ID = 0;
132INITIALIZE_PASS(GlobalMerge, "global-merge",
133 "Global Merge", false, false)
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000134
Devang Patel827454e2011-10-17 17:17:43 +0000135
136bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangae9716592013-01-07 12:31:25 +0000137 Module &M, bool isConst, unsigned AddrSpace) const {
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000138 const TargetLowering *TLI = TM->getTargetLowering();
Stephen Hines36b56882014-04-23 16:57:46 -0700139 const DataLayout *DL = TLI->getDataLayout();
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000140
141 // FIXME: Infer the maximum possible offset depending on the actual users
142 // (these max offsets are different for the users inside Thumb or ARM
143 // functions)
144 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
145
146 // FIXME: Find better heuristics
Stephen Hines36b56882014-04-23 16:57:46 -0700147 std::stable_sort(Globals.begin(), Globals.end(),
148 [DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
149 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
150 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
151
152 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
153 });
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000154
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000155 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000156
157 for (size_t i = 0, e = Globals.size(); i != e; ) {
158 size_t j = 0;
159 uint64_t MergedSize = 0;
Jay Foad5fdd6c82011-07-12 14:06:48 +0000160 std::vector<Type*> Tys;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000161 std::vector<Constant*> Inits;
Bob Wilson619a3722010-11-17 21:25:36 +0000162 for (j = i; j != e; ++j) {
Jay Foad5fdd6c82011-07-12 14:06:48 +0000163 Type *Ty = Globals[j]->getType()->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700164 MergedSize += DL->getTypeAllocSize(Ty);
Bob Wilson619a3722010-11-17 21:25:36 +0000165 if (MergedSize > MaxOffset) {
166 break;
167 }
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000168 Tys.push_back(Ty);
169 Inits.push_back(Globals[j]->getInitializer());
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000170 }
171
Chris Lattner252b4912010-09-05 21:18:45 +0000172 StructType *MergedTy = StructType::get(M.getContext(), Tys);
173 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
174 GlobalVariable *MergedGV = new GlobalVariable(M, MergedTy, isConst,
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000175 GlobalValue::InternalLinkage,
Silviu Barangae9716592013-01-07 12:31:25 +0000176 MergedInit, "_MergedGlobals",
Stephen Hinesdce4a402014-05-29 02:49:00 -0700177 nullptr,
178 GlobalVariable::NotThreadLocal,
Silviu Barangae9716592013-01-07 12:31:25 +0000179 AddrSpace);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000180 for (size_t k = i; k < j; ++k) {
Chris Lattner252b4912010-09-05 21:18:45 +0000181 Constant *Idx[2] = {
182 ConstantInt::get(Int32Ty, 0),
183 ConstantInt::get(Int32Ty, k-i)
184 };
Jay Foaddab3d292011-07-21 14:31:17 +0000185 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000186 Globals[k]->replaceAllUsesWith(GEP);
187 Globals[k]->eraseFromParent();
Devang Patel827454e2011-10-17 17:17:43 +0000188 NumMerged++;
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000189 }
190 i = j;
191 }
192
193 return true;
194}
195
Quentin Colombete5728092013-03-18 22:30:07 +0000196void GlobalMerge::collectUsedGlobalVariables(Module &M) {
197 // Extract global variables from llvm.used array
198 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
199 if (!GV || !GV->hasInitializer()) return;
200
201 // Should be an array of 'i8*'.
Rafael Espindolacde25b42013-04-22 14:58:02 +0000202 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
203
Quentin Colombete5728092013-03-18 22:30:07 +0000204 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
205 if (const GlobalVariable *G =
206 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
207 MustKeepGlobalVariables.insert(G);
208}
209
210void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
Quentin Colombete5728092013-03-18 22:30:07 +0000211 collectUsedGlobalVariables(M);
212
213 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
214 ++IFn) {
215 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
216 IBB != IEndBB; ++IBB) {
Stephen Hines36b56882014-04-23 16:57:46 -0700217 // Follow the invoke link to find the landing pad instruction
Quentin Colombete5728092013-03-18 22:30:07 +0000218 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
219 if (!II) continue;
220
221 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
222 // Look for globals in the clauses of the landing pad instruction
223 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
224 Idx != NumClauses; ++Idx)
225 if (const GlobalVariable *GV =
226 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
227 ->stripPointerCasts()))
228 MustKeepGlobalVariables.insert(GV);
229 }
230 }
231}
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000232
Devang Patel827454e2011-10-17 17:17:43 +0000233bool GlobalMerge::doInitialization(Module &M) {
Stephen Hines36b56882014-04-23 16:57:46 -0700234 if (!EnableGlobalMerge)
235 return false;
236
Silviu Barangae9716592013-01-07 12:31:25 +0000237 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
238 BSSGlobals;
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000239 const TargetLowering *TLI = TM->getTargetLowering();
Stephen Hines36b56882014-04-23 16:57:46 -0700240 const DataLayout *DL = TLI->getDataLayout();
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000241 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
242 bool Changed = false;
Quentin Colombete5728092013-03-18 22:30:07 +0000243 setMustKeepGlobalVariables(M);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000244
245 // Grab all non-const globals.
246 for (Module::global_iterator I = M.global_begin(),
247 E = M.global_end(); I != E; ++I) {
248 // Merge is safe for "normal" internal globals only
249 if (!I->hasLocalLinkage() || I->isThreadLocal() || I->hasSection())
250 continue;
251
Silviu Barangae9716592013-01-07 12:31:25 +0000252 PointerType *PT = dyn_cast<PointerType>(I->getType());
253 assert(PT && "Global variable is not a pointer!");
254
255 unsigned AddressSpace = PT->getAddressSpace();
256
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000257 // Ignore fancy-aligned globals for now.
Stephen Hines36b56882014-04-23 16:57:46 -0700258 unsigned Alignment = DL->getPreferredAlignment(I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000259 Type *Ty = I->getType()->getElementType();
Stephen Hines36b56882014-04-23 16:57:46 -0700260 if (Alignment > DL->getABITypeAlignment(Ty))
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000261 continue;
262
Anton Korobeynikovb5a0ef92010-07-26 18:45:39 +0000263 // Ignore all 'special' globals.
264 if (I->getName().startswith("llvm.") ||
265 I->getName().startswith(".llvm."))
266 continue;
267
Quentin Colombete5728092013-03-18 22:30:07 +0000268 // Ignore all "required" globals:
Quentin Colombete5728092013-03-18 22:30:07 +0000269 if (isMustKeepGlobalVariable(I))
270 continue;
271
Stephen Hines36b56882014-04-23 16:57:46 -0700272 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
Ahmed Charlesb83a67e2012-02-13 06:30:56 +0000273 if (TargetLoweringObjectFile::getKindForGlobal(I, TLI->getTargetMachine())
274 .isBSSLocal())
Silviu Barangae9716592013-01-07 12:31:25 +0000275 BSSGlobals[AddressSpace].push_back(I);
Bob Wilson05646092010-11-17 21:25:39 +0000276 else if (I->isConstant())
Silviu Barangae9716592013-01-07 12:31:25 +0000277 ConstGlobals[AddressSpace].push_back(I);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000278 else
Silviu Barangae9716592013-01-07 12:31:25 +0000279 Globals[AddressSpace].push_back(I);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000280 }
281 }
282
Silviu Barangae9716592013-01-07 12:31:25 +0000283 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
284 I = Globals.begin(), E = Globals.end(); I != E; ++I)
285 if (I->second.size() > 1)
286 Changed |= doMerge(I->second, M, false, I->first);
287
288 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
289 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
290 if (I->second.size() > 1)
291 Changed |= doMerge(I->second, M, false, I->first);
Bob Wilson05646092010-11-17 21:25:39 +0000292
Quentin Colombete5728092013-03-18 22:30:07 +0000293 if (EnableGlobalMergeOnConst)
294 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
295 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
296 if (I->second.size() > 1)
297 Changed |= doMerge(I->second, M, true, I->first);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000298
299 return Changed;
300}
301
Devang Patel827454e2011-10-17 17:17:43 +0000302bool GlobalMerge::runOnFunction(Function &F) {
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000303 return false;
304}
305
Quentin Colombet9deb9172013-03-19 21:46:49 +0000306bool GlobalMerge::doFinalization(Module &M) {
307 MustKeepGlobalVariables.clear();
308 return false;
309}
310
Bill Wendlingf9fd58a2013-06-19 21:07:11 +0000311Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
312 return new GlobalMerge(TM);
Anton Korobeynikovcec36f42010-07-24 21:52:08 +0000313}