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 STATISTIC(NumMerged , "Number of globals merged");
86 class GlobalMerge : public FunctionPass {
87 const TargetMachine *TM;
89 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
90 Module &M, bool isConst, unsigned AddrSpace) const;
92 /// \brief Check if the given variable has been identified as must keep
93 /// \pre setMustKeepGlobalVariables must have been called on the Module that
95 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
96 return MustKeepGlobalVariables.count(GV);
99 /// Collect every variables marked as "used" or used in a landing pad
100 /// instruction for this Module.
101 void setMustKeepGlobalVariables(Module &M);
103 /// Collect every variables marked as "used"
104 void collectUsedGlobalVariables(Module &M);
106 /// Keep track of the GlobalVariable that must not be merged away
107 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
110 static char ID; // Pass identification, replacement for typeid.
111 explicit GlobalMerge(const TargetMachine *TM = nullptr)
112 : FunctionPass(ID), TM(TM) {
113 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
116 bool doInitialization(Module &M) override;
117 bool runOnFunction(Function &F) override;
118 bool doFinalization(Module &M) override;
120 const char *getPassName() const override {
121 return "Merge internal globals";
124 void getAnalysisUsage(AnalysisUsage &AU) const override {
125 AU.setPreservesCFG();
126 FunctionPass::getAnalysisUsage(AU);
129 } // end anonymous namespace
131 char GlobalMerge::ID = 0;
132 INITIALIZE_PASS(GlobalMerge, "global-merge",
133 "Global Merge", false, false)
136 bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
137 Module &M, bool isConst, unsigned AddrSpace) const {
138 const TargetLowering *TLI = TM->getTargetLowering();
139 const DataLayout *DL = TLI->getDataLayout();
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
144 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
146 // FIXME: Find better heuristics
147 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();
152 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
155 Type *Int32Ty = Type::getInt32Ty(M.getContext());
157 for (size_t i = 0, e = Globals.size(); i != e; ) {
159 uint64_t MergedSize = 0;
160 std::vector<Type*> Tys;
161 std::vector<Constant*> Inits;
162 for (j = i; j != e; ++j) {
163 Type *Ty = Globals[j]->getType()->getElementType();
164 MergedSize += DL->getTypeAllocSize(Ty);
165 if (MergedSize > MaxOffset) {
169 Inits.push_back(Globals[j]->getInitializer());
172 StructType *MergedTy = StructType::get(M.getContext(), Tys);
173 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
174 GlobalVariable *MergedGV = new GlobalVariable(M, MergedTy, isConst,
175 GlobalValue::InternalLinkage,
176 MergedInit, "_MergedGlobals",
178 GlobalVariable::NotThreadLocal,
180 for (size_t k = i; k < j; ++k) {
182 ConstantInt::get(Int32Ty, 0),
183 ConstantInt::get(Int32Ty, k-i)
185 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
186 Globals[k]->replaceAllUsesWith(GEP);
187 Globals[k]->eraseFromParent();
196 void 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;
201 // Should be an array of 'i8*'.
202 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
204 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);
210 void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
211 collectUsedGlobalVariables(M);
213 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
215 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
216 IBB != IEndBB; ++IBB) {
217 // Follow the invoke link to find the landing pad instruction
218 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
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);
233 bool GlobalMerge::doInitialization(Module &M) {
234 if (!EnableGlobalMerge)
237 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
239 const TargetLowering *TLI = TM->getTargetLowering();
240 const DataLayout *DL = TLI->getDataLayout();
241 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
242 bool Changed = false;
243 setMustKeepGlobalVariables(M);
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())
252 PointerType *PT = dyn_cast<PointerType>(I->getType());
253 assert(PT && "Global variable is not a pointer!");
255 unsigned AddressSpace = PT->getAddressSpace();
257 // Ignore fancy-aligned globals for now.
258 unsigned Alignment = DL->getPreferredAlignment(I);
259 Type *Ty = I->getType()->getElementType();
260 if (Alignment > DL->getABITypeAlignment(Ty))
263 // Ignore all 'special' globals.
264 if (I->getName().startswith("llvm.") ||
265 I->getName().startswith(".llvm."))
268 // Ignore all "required" globals:
269 if (isMustKeepGlobalVariable(I))
272 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
273 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
274 BSSGlobals[AddressSpace].push_back(I);
275 else if (I->isConstant())
276 ConstGlobals[AddressSpace].push_back(I);
278 Globals[AddressSpace].push_back(I);
282 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
283 I = Globals.begin(), E = Globals.end(); I != E; ++I)
284 if (I->second.size() > 1)
285 Changed |= doMerge(I->second, M, false, I->first);
287 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
288 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
289 if (I->second.size() > 1)
290 Changed |= doMerge(I->second, M, false, I->first);
292 if (EnableGlobalMergeOnConst)
293 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
294 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
295 if (I->second.size() > 1)
296 Changed |= doMerge(I->second, M, true, I->first);
301 bool GlobalMerge::runOnFunction(Function &F) {
305 bool GlobalMerge::doFinalization(Module &M) {
306 MustKeepGlobalVariables.clear();
310 Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
311 return new GlobalMerge(TM);