1 //===-- GlobalMerge.cpp - Internal globals merging -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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.
15 // For example, consider the code which touches several global variables at
18 // static int foo[N], bar[N], baz[N];
20 // for (i = 0; i < N; ++i) {
21 // foo[i] = bar[i] * baz[i];
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):
32 // Pass converts the code to something like:
40 // for (i = 0; i < N; ++i) {
41 // merged.foo[i] = merged.bar[i] * merged.baz[i];
44 // and in ARM code this becomes:
51 // note that we saved 2 registers here almostly "for free".
52 // ===---------------------------------------------------------------------===//
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #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"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Target/TargetLowering.h"
69 #include "llvm/Target/TargetLoweringObjectFile.h"
72 #define DEBUG_TYPE "global-merge"
75 EnableGlobalMerge("enable-global-merge", cl::Hidden,
76 cl::desc("Enable global merge pass"),
80 EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
81 cl::desc("Enable global merge pass on constants"),
84 // FIXME: this could be a transitional option, and we probably need to remove
85 // it if only we are sure this optimization could always benefit all targets.
87 EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
88 cl::desc("Enable global merge pass on external linkage"),
91 STATISTIC(NumMerged , "Number of globals merged");
93 class GlobalMerge : public FunctionPass {
94 const TargetMachine *TM;
96 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
97 Module &M, bool isConst, unsigned AddrSpace) const;
99 /// \brief Check if the given variable has been identified as must keep
100 /// \pre setMustKeepGlobalVariables must have been called on the Module that
102 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
103 return MustKeepGlobalVariables.count(GV);
106 /// Collect every variables marked as "used" or used in a landing pad
107 /// instruction for this Module.
108 void setMustKeepGlobalVariables(Module &M);
110 /// Collect every variables marked as "used"
111 void collectUsedGlobalVariables(Module &M);
113 /// Keep track of the GlobalVariable that must not be merged away
114 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
117 static char ID; // Pass identification, replacement for typeid.
118 explicit GlobalMerge(const TargetMachine *TM = nullptr)
119 : FunctionPass(ID), TM(TM) {
120 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
123 bool doInitialization(Module &M) override;
124 bool runOnFunction(Function &F) override;
125 bool doFinalization(Module &M) override;
127 const char *getPassName() const override {
128 return "Merge internal globals";
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.setPreservesCFG();
133 FunctionPass::getAnalysisUsage(AU);
136 } // end anonymous namespace
138 char GlobalMerge::ID = 0;
140 static void *initializeGlobalMergePassOnce(PassRegistry &Registry) {
141 PassInfo *PI = new PassInfo(
142 "Merge global variables", "global-merge", &GlobalMerge::ID,
143 PassInfo::NormalCtor_t(callDefaultCtor<GlobalMerge>), false, false,
144 PassInfo::TargetMachineCtor_t(callTargetMachineCtor<GlobalMerge>));
145 Registry.registerPass(*PI, true);
149 void llvm::initializeGlobalMergePass(PassRegistry &Registry) {
150 CALL_ONCE_INITIALIZATION(initializeGlobalMergePassOnce)
153 bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
154 Module &M, bool isConst, unsigned AddrSpace) const {
155 const TargetLowering *TLI = TM->getTargetLowering();
156 const DataLayout *DL = TLI->getDataLayout();
158 // FIXME: Infer the maximum possible offset depending on the actual users
159 // (these max offsets are different for the users inside Thumb or ARM
161 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
163 // FIXME: Find better heuristics
164 std::stable_sort(Globals.begin(), Globals.end(),
165 [DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
166 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
167 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
169 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
172 Type *Int32Ty = Type::getInt32Ty(M.getContext());
174 assert(Globals.size() > 1);
176 // FIXME: This simple solution merges globals all together as maximum as
177 // possible. However, with this solution it would be hard to remove dead
178 // global symbols at link-time. An alternative solution could be checking
179 // global symbols references function by function, and make the symbols
180 // being referred in the same function merged and we would probably need
181 // to introduce heuristic algorithm to solve the merge conflict from
182 // different functions.
183 for (size_t i = 0, e = Globals.size(); i != e; ) {
185 uint64_t MergedSize = 0;
186 std::vector<Type*> Tys;
187 std::vector<Constant*> Inits;
189 bool HasExternal = false;
190 GlobalVariable *TheFirstExternal = 0;
191 for (j = i; j != e; ++j) {
192 Type *Ty = Globals[j]->getType()->getElementType();
193 MergedSize += DL->getTypeAllocSize(Ty);
194 if (MergedSize > MaxOffset) {
198 Inits.push_back(Globals[j]->getInitializer());
200 if (Globals[j]->hasExternalLinkage() && !HasExternal) {
202 TheFirstExternal = Globals[j];
206 // If merged variables doesn't have external linkage, we needn't to expose
207 // the symbol after merging.
208 GlobalValue::LinkageTypes Linkage = HasExternal
209 ? GlobalValue::ExternalLinkage
210 : GlobalValue::InternalLinkage;
212 // If merged variables have external linkage, we use symbol name of the
213 // first variable merged as the suffix of global symbol name. This would
214 // be able to avoid the link-time naming conflict for globalm symbols.
215 Twine MergedGVName = HasExternal
216 ? "_MergedGlobals_" + TheFirstExternal->getName()
219 StructType *MergedTy = StructType::get(M.getContext(), Tys);
220 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
222 GlobalVariable *MergedGV = new GlobalVariable(
223 M, MergedTy, isConst, Linkage, MergedInit, MergedGVName, nullptr,
224 GlobalVariable::NotThreadLocal, AddrSpace);
226 for (size_t k = i; k < j; ++k) {
227 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
228 std::string Name = Globals[k]->getName();
231 ConstantInt::get(Int32Ty, 0),
232 ConstantInt::get(Int32Ty, k-i)
234 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
235 Globals[k]->replaceAllUsesWith(GEP);
236 Globals[k]->eraseFromParent();
238 if (Linkage != GlobalValue::InternalLinkage) {
239 // Generate a new alias...
240 auto *PTy = cast<PointerType>(GEP->getType());
241 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
242 Linkage, Name, GEP, &M);
253 void GlobalMerge::collectUsedGlobalVariables(Module &M) {
254 // Extract global variables from llvm.used array
255 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
256 if (!GV || !GV->hasInitializer()) return;
258 // Should be an array of 'i8*'.
259 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
261 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
262 if (const GlobalVariable *G =
263 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
264 MustKeepGlobalVariables.insert(G);
267 void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
268 collectUsedGlobalVariables(M);
270 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
272 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
273 IBB != IEndBB; ++IBB) {
274 // Follow the invoke link to find the landing pad instruction
275 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
278 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
279 // Look for globals in the clauses of the landing pad instruction
280 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
281 Idx != NumClauses; ++Idx)
282 if (const GlobalVariable *GV =
283 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
284 ->stripPointerCasts()))
285 MustKeepGlobalVariables.insert(GV);
290 bool GlobalMerge::doInitialization(Module &M) {
291 if (!EnableGlobalMerge)
294 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
296 const TargetLowering *TLI = TM->getTargetLowering();
297 const DataLayout *DL = TLI->getDataLayout();
298 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
299 bool Changed = false;
300 setMustKeepGlobalVariables(M);
302 // Grab all non-const globals.
303 for (Module::global_iterator I = M.global_begin(),
304 E = M.global_end(); I != E; ++I) {
305 // Merge is safe for "normal" internal or external globals only
306 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
309 if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
310 !I->hasInternalLinkage())
313 PointerType *PT = dyn_cast<PointerType>(I->getType());
314 assert(PT && "Global variable is not a pointer!");
316 unsigned AddressSpace = PT->getAddressSpace();
318 // Ignore fancy-aligned globals for now.
319 unsigned Alignment = DL->getPreferredAlignment(I);
320 Type *Ty = I->getType()->getElementType();
321 if (Alignment > DL->getABITypeAlignment(Ty))
324 // Ignore all 'special' globals.
325 if (I->getName().startswith("llvm.") ||
326 I->getName().startswith(".llvm."))
329 // Ignore all "required" globals:
330 if (isMustKeepGlobalVariable(I))
333 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
334 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
335 BSSGlobals[AddressSpace].push_back(I);
336 else if (I->isConstant())
337 ConstGlobals[AddressSpace].push_back(I);
339 Globals[AddressSpace].push_back(I);
343 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
344 I = Globals.begin(), E = Globals.end(); I != E; ++I)
345 if (I->second.size() > 1)
346 Changed |= doMerge(I->second, M, false, I->first);
348 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
349 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
350 if (I->second.size() > 1)
351 Changed |= doMerge(I->second, M, false, I->first);
353 if (EnableGlobalMergeOnConst)
354 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
355 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
356 if (I->second.size() > 1)
357 Changed |= doMerge(I->second, M, true, I->first);
362 bool GlobalMerge::runOnFunction(Function &F) {
366 bool GlobalMerge::doFinalization(Module &M) {
367 MustKeepGlobalVariables.clear();
371 Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
372 return new GlobalMerge(TM);