blob: 73543cb3de3471bde9e553b651a26093dd1060d9 [file] [log] [blame]
Devang Patel76c85632011-10-17 17:17:43 +00001//===-- GlobalMerge.cpp - Internal globals merging -----------------------===//
Anton Korobeynikov19edda02010-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 Rotem465834c2012-07-24 10:51:42 +000015// For example, consider the code which touches several global variables at
Eric Christopherbf86fd32010-09-28 04:18:29 +000016// once:
Anton Korobeynikov19edda02010-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".
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000052//
53// However, merging globals can have tradeoffs:
54// - it confuses debuggers, tools, and users
55// - it makes linker optimizations less useful (order files, LOHs, ...)
56// - it forces usage of indexed addressing (which isn't necessarily "free")
57// - it can increase register pressure when the uses are disparate enough.
58//
59// We use heuristics to discover the best global grouping we can (cf cl::opts).
Eric Christopherbf86fd32010-09-28 04:18:29 +000060// ===---------------------------------------------------------------------===//
Anton Korobeynikov19edda02010-07-24 21:52:08 +000061
Devang Patel76c85632011-10-17 17:17:43 +000062#include "llvm/Transforms/Scalar.h"
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000063#include "llvm/ADT/DenseMap.h"
64#include "llvm/ADT/SmallBitVector.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000065#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/ADT/Statistic.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000067#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000068#include "llvm/IR/Attributes.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DerivedTypes.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/GlobalVariable.h"
74#include "llvm/IR/Instructions.h"
75#include "llvm/IR/Intrinsics.h"
76#include "llvm/IR/Module.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000077#include "llvm/Pass.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000078#include "llvm/Support/CommandLine.h"
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000079#include "llvm/Support/Debug.h"
80#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000081#include "llvm/Target/TargetLowering.h"
Bob Wilson881b45c2010-11-17 21:25:39 +000082#include "llvm/Target/TargetLoweringObjectFile.h"
Eric Christopherd9134482014-08-04 21:25:23 +000083#include "llvm/Target/TargetSubtargetInfo.h"
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000084#include <algorithm>
Anton Korobeynikov19edda02010-07-24 21:52:08 +000085using namespace llvm;
86
Chandler Carruth964daaa2014-04-22 02:55:47 +000087#define DEBUG_TYPE "global-merge"
88
Ahmed Bougachab96444e2015-04-11 00:06:36 +000089// FIXME: This is only useful as a last-resort way to disable the pass.
Quentin Colombet8fc34092013-03-18 22:30:07 +000090static cl::opt<bool>
Jiangning Liu3e5b8552014-06-11 06:35:26 +000091EnableGlobalMerge("enable-global-merge", cl::Hidden,
Ahmed Bougachab96444e2015-04-11 00:06:36 +000092 cl::desc("Enable the global merge pass"),
Tim Northoverf804c172014-02-18 11:17:29 +000093 cl::init(true));
94
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000095static cl::opt<bool> GlobalMergeGroupByUse(
96 "global-merge-group-by-use", cl::Hidden,
97 cl::desc("Improve global merge pass to look at uses"), cl::init(true));
98
99static cl::opt<bool> GlobalMergeIgnoreSingleUse(
100 "global-merge-ignore-single-use", cl::Hidden,
101 cl::desc("Improve global merge pass to ignore globals only used alone"),
102 cl::init(true));
103
Tim Northoverf804c172014-02-18 11:17:29 +0000104static cl::opt<bool>
Quentin Colombet8fc34092013-03-18 22:30:07 +0000105EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
Jakub Staszak6b36db02013-07-22 21:11:30 +0000106 cl::desc("Enable global merge pass on constants"),
107 cl::init(false));
Quentin Colombet8fc34092013-03-18 22:30:07 +0000108
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000109// FIXME: this could be a transitional option, and we probably need to remove
110// it if only we are sure this optimization could always benefit all targets.
John Brawn8b954242015-08-03 12:08:41 +0000111static cl::opt<cl::boolOrDefault>
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000112EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
John Brawn8b954242015-08-03 12:08:41 +0000113 cl::desc("Enable global merge pass on external linkage"));
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000114
Eric Christophered47b222015-02-23 19:28:45 +0000115STATISTIC(NumMerged, "Number of globals merged");
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000116namespace {
Devang Patel76c85632011-10-17 17:17:43 +0000117 class GlobalMerge : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000118 const TargetMachine *TM;
Eric Christophered47b222015-02-23 19:28:45 +0000119 // FIXME: Infer the maximum possible offset depending on the actual users
120 // (these max offsets are different for the users inside Thumb or ARM
121 // functions), see the code that passes in the offset in the ARM backend
122 // for more information.
123 unsigned MaxOffset;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000124
Ahmed Bougacha82076412015-06-04 20:39:23 +0000125 /// Whether we should try to optimize for size only.
126 /// Currently, this applies a dead simple heuristic: only consider globals
127 /// used in minsize functions for merging.
128 /// FIXME: This could learn about optsize, and be used in the cost model.
129 bool OnlyOptimizeForSize;
130
John Brawn8b954242015-08-03 12:08:41 +0000131 /// Whether we should merge global variables that have external linkage.
132 bool MergeExternalGlobals;
133
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000134 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000135 Module &M, bool isConst, unsigned AddrSpace) const;
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000136 /// \brief Merge everything in \p Globals for which the corresponding bit
137 /// in \p GlobalSet is set.
David Blaikie47bf5c02015-08-21 22:19:06 +0000138 bool doMerge(const SmallVectorImpl<GlobalVariable *> &Globals,
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000139 const BitVector &GlobalSet, Module &M, bool isConst,
140 unsigned AddrSpace) const;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000141
Quentin Colombet8fc34092013-03-18 22:30:07 +0000142 /// \brief Check if the given variable has been identified as must keep
143 /// \pre setMustKeepGlobalVariables must have been called on the Module that
144 /// contains GV
145 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
146 return MustKeepGlobalVariables.count(GV);
147 }
148
149 /// Collect every variables marked as "used" or used in a landing pad
150 /// instruction for this Module.
151 void setMustKeepGlobalVariables(Module &M);
152
153 /// Collect every variables marked as "used"
154 void collectUsedGlobalVariables(Module &M);
155
Quentin Colombet2393cb92013-03-19 21:46:49 +0000156 /// Keep track of the GlobalVariable that must not be merged away
Quentin Colombet8fc34092013-03-18 22:30:07 +0000157 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
158
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000159 public:
160 static char ID; // Pass identification, replacement for typeid.
Eric Christophered47b222015-02-23 19:28:45 +0000161 explicit GlobalMerge(const TargetMachine *TM = nullptr,
Ahmed Bougacha82076412015-06-04 20:39:23 +0000162 unsigned MaximalOffset = 0,
John Brawn8b954242015-08-03 12:08:41 +0000163 bool OnlyOptimizeForSize = false,
164 bool MergeExternalGlobals = false)
Mehdi Aminif6727b02015-07-07 18:49:25 +0000165 : FunctionPass(ID), TM(TM), MaxOffset(MaximalOffset),
John Brawn8b954242015-08-03 12:08:41 +0000166 OnlyOptimizeForSize(OnlyOptimizeForSize),
167 MergeExternalGlobals(MergeExternalGlobals) {
Devang Patel76c85632011-10-17 17:17:43 +0000168 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
169 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000170
Craig Topper3e4c6972014-03-05 09:10:37 +0000171 bool doInitialization(Module &M) override;
172 bool runOnFunction(Function &F) override;
173 bool doFinalization(Module &M) override;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000174
Craig Topper3e4c6972014-03-05 09:10:37 +0000175 const char *getPassName() const override {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000176 return "Merge internal globals";
177 }
178
Craig Topper3e4c6972014-03-05 09:10:37 +0000179 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000180 AU.setPreservesCFG();
181 FunctionPass::getAnalysisUsage(AU);
182 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000183 };
184} // end anonymous namespace
185
Devang Patel76c85632011-10-17 17:17:43 +0000186char GlobalMerge::ID = 0;
Eric Christophered47b222015-02-23 19:28:45 +0000187INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables",
188 false, false)
189INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables",
190 false, false)
Devang Patel76c85632011-10-17 17:17:43 +0000191
192bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000193 Module &M, bool isConst, unsigned AddrSpace) const {
Mehdi Aminif6727b02015-07-07 18:49:25 +0000194 auto &DL = M.getDataLayout();
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000195 // FIXME: Find better heuristics
David Blaikie9ed57a92015-08-21 22:00:44 +0000196 std::stable_sort(Globals.begin(), Globals.end(),
197 [&DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
198 return DL.getTypeAllocSize(GV1->getValueType()) <
199 DL.getTypeAllocSize(GV2->getValueType());
200 });
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000201
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000202 // If we want to just blindly group all globals together, do so.
203 if (!GlobalMergeGroupByUse) {
204 BitVector AllGlobals(Globals.size());
205 AllGlobals.set();
206 return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
207 }
208
209 // If we want to be smarter, look at all uses of each global, to try to
210 // discover all sets of globals used together, and how many times each of
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000211 // these sets occurred.
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000212 //
213 // Keep this reasonably efficient, by having an append-only list of all sets
214 // discovered so far (UsedGlobalSet), and mapping each "together-ness" unit of
215 // code (currently, a Function) to the set of globals seen so far that are
216 // used together in that unit (GlobalUsesByFunction).
217 //
218 // When we look at the Nth global, we now that any new set is either:
219 // - the singleton set {N}, containing this global only, or
220 // - the union of {N} and a previously-discovered set, containing some
221 // combination of the previous N-1 globals.
222 // Using that knowledge, when looking at the Nth global, we can keep:
223 // - a reference to the singleton set {N} (CurGVOnlySetIdx)
224 // - a list mapping each previous set to its union with {N} (EncounteredUGS),
225 // if it actually occurs.
226
227 // We keep track of the sets of globals used together "close enough".
228 struct UsedGlobalSet {
229 UsedGlobalSet(size_t Size) : Globals(Size), UsageCount(1) {}
230 BitVector Globals;
231 unsigned UsageCount;
232 };
233
234 // Each set is unique in UsedGlobalSets.
235 std::vector<UsedGlobalSet> UsedGlobalSets;
236
237 // Avoid repeating the create-global-set pattern.
238 auto CreateGlobalSet = [&]() -> UsedGlobalSet & {
239 UsedGlobalSets.emplace_back(Globals.size());
240 return UsedGlobalSets.back();
241 };
242
243 // The first set is the empty set.
244 CreateGlobalSet().UsageCount = 0;
245
246 // We define "close enough" to be "in the same function".
247 // FIXME: Grouping uses by function is way too aggressive, so we should have
248 // a better metric for distance between uses.
249 // The obvious alternative would be to group by BasicBlock, but that's in
250 // turn too conservative..
251 // Anything in between wouldn't be trivial to compute, so just stick with
252 // per-function grouping.
253
254 // The value type is an index into UsedGlobalSets.
255 // The default (0) conveniently points to the empty set.
256 DenseMap<Function *, size_t /*UsedGlobalSetIdx*/> GlobalUsesByFunction;
257
258 // Now, look at each merge-eligible global in turn.
259
260 // Keep track of the sets we already encountered to which we added the
261 // current global.
262 // Each element matches the same-index element in UsedGlobalSets.
263 // This lets us efficiently tell whether a set has already been expanded to
264 // include the current global.
265 std::vector<size_t> EncounteredUGS;
266
267 for (size_t GI = 0, GE = Globals.size(); GI != GE; ++GI) {
268 GlobalVariable *GV = Globals[GI];
269
270 // Reset the encountered sets for this global...
271 std::fill(EncounteredUGS.begin(), EncounteredUGS.end(), 0);
272 // ...and grow it in case we created new sets for the previous global.
273 EncounteredUGS.resize(UsedGlobalSets.size());
274
275 // We might need to create a set that only consists of the current global.
276 // Keep track of its index into UsedGlobalSets.
277 size_t CurGVOnlySetIdx = 0;
278
279 // For each global, look at all its Uses.
280 for (auto &U : GV->uses()) {
281 // This Use might be a ConstantExpr. We're interested in Instruction
282 // users, so look through ConstantExpr...
283 Use *UI, *UE;
284 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
Oliver Stannard8379e292015-06-08 16:55:31 +0000285 if (CE->use_empty())
286 continue;
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000287 UI = &*CE->use_begin();
288 UE = nullptr;
289 } else if (isa<Instruction>(U.getUser())) {
290 UI = &U;
291 UE = UI->getNext();
292 } else {
293 continue;
294 }
295
296 // ...to iterate on all the instruction users of the global.
297 // Note that we iterate on Uses and not on Users to be able to getNext().
298 for (; UI != UE; UI = UI->getNext()) {
299 Instruction *I = dyn_cast<Instruction>(UI->getUser());
300 if (!I)
301 continue;
302
303 Function *ParentFn = I->getParent()->getParent();
Ahmed Bougacha82076412015-06-04 20:39:23 +0000304
305 // If we're only optimizing for size, ignore non-minsize functions.
Sanjay Patel1cd6d882015-08-18 16:44:23 +0000306 if (OnlyOptimizeForSize && !ParentFn->optForMinSize())
Ahmed Bougacha82076412015-06-04 20:39:23 +0000307 continue;
308
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000309 size_t UGSIdx = GlobalUsesByFunction[ParentFn];
310
311 // If this is the first global the basic block uses, map it to the set
312 // consisting of this global only.
313 if (!UGSIdx) {
314 // If that set doesn't exist yet, create it.
315 if (!CurGVOnlySetIdx) {
316 CurGVOnlySetIdx = UsedGlobalSets.size();
317 CreateGlobalSet().Globals.set(GI);
318 } else {
319 ++UsedGlobalSets[CurGVOnlySetIdx].UsageCount;
320 }
321
322 GlobalUsesByFunction[ParentFn] = CurGVOnlySetIdx;
323 continue;
324 }
325
326 // If we already encountered this BB, just increment the counter.
327 if (UsedGlobalSets[UGSIdx].Globals.test(GI)) {
328 ++UsedGlobalSets[UGSIdx].UsageCount;
329 continue;
330 }
331
332 // If not, the previous set wasn't actually used in this function.
333 --UsedGlobalSets[UGSIdx].UsageCount;
334
335 // If we already expanded the previous set to include this global, just
336 // reuse that expanded set.
337 if (size_t ExpandedIdx = EncounteredUGS[UGSIdx]) {
338 ++UsedGlobalSets[ExpandedIdx].UsageCount;
339 GlobalUsesByFunction[ParentFn] = ExpandedIdx;
340 continue;
341 }
342
343 // If not, create a new set consisting of the union of the previous set
344 // and this global. Mark it as encountered, so we can reuse it later.
345 GlobalUsesByFunction[ParentFn] = EncounteredUGS[UGSIdx] =
346 UsedGlobalSets.size();
347
348 UsedGlobalSet &NewUGS = CreateGlobalSet();
349 NewUGS.Globals.set(GI);
350 NewUGS.Globals |= UsedGlobalSets[UGSIdx].Globals;
351 }
352 }
353 }
354
355 // Now we found a bunch of sets of globals used together. We accumulated
356 // the number of times we encountered the sets (i.e., the number of blocks
357 // that use that exact set of globals).
358 //
359 // Multiply that by the size of the set to give us a crude profitability
360 // metric.
361 std::sort(UsedGlobalSets.begin(), UsedGlobalSets.end(),
362 [](const UsedGlobalSet &UGS1, const UsedGlobalSet &UGS2) {
363 return UGS1.Globals.count() * UGS1.UsageCount <
364 UGS2.Globals.count() * UGS2.UsageCount;
365 });
366
367 // We can choose to merge all globals together, but ignore globals never used
368 // with another global. This catches the obviously non-profitable cases of
369 // having a single global, but is aggressive enough for any other case.
370 if (GlobalMergeIgnoreSingleUse) {
371 BitVector AllGlobals(Globals.size());
372 for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
373 const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
374 if (UGS.UsageCount == 0)
375 continue;
376 if (UGS.Globals.count() > 1)
377 AllGlobals |= UGS.Globals;
378 }
379 return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
380 }
381
382 // Starting from the sets with the best (=biggest) profitability, find a
383 // good combination.
384 // The ideal (and expensive) solution can only be found by trying all
385 // combinations, looking for the one with the best profitability.
386 // Don't be smart about it, and just pick the first compatible combination,
387 // starting with the sets with the best profitability.
388 BitVector PickedGlobals(Globals.size());
389 bool Changed = false;
390
391 for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
392 const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
393 if (UGS.UsageCount == 0)
394 continue;
395 if (PickedGlobals.anyCommon(UGS.Globals))
396 continue;
397 PickedGlobals |= UGS.Globals;
398 // If the set only contains one global, there's no point in merging.
399 // Ignore the global for inclusion in other sets though, so keep it in
400 // PickedGlobals.
401 if (UGS.Globals.count() < 2)
402 continue;
403 Changed |= doMerge(Globals, UGS.Globals, M, isConst, AddrSpace);
404 }
405
406 return Changed;
407}
408
David Blaikie47bf5c02015-08-21 22:19:06 +0000409bool GlobalMerge::doMerge(const SmallVectorImpl<GlobalVariable *> &Globals,
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000410 const BitVector &GlobalSet, Module &M, bool isConst,
411 unsigned AddrSpace) const {
David Blaikie47bf5c02015-08-21 22:19:06 +0000412 assert(Globals.size() > 1);
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000413
Chris Lattner229907c2011-07-18 04:54:35 +0000414 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Mehdi Aminif6727b02015-07-07 18:49:25 +0000415 auto &DL = M.getDataLayout();
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000416
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000417 DEBUG(dbgs() << " Trying to merge set, starts with #"
418 << GlobalSet.find_first() << "\n");
419
420 ssize_t i = GlobalSet.find_first();
421 while (i != -1) {
422 ssize_t j = 0;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000423 uint64_t MergedSize = 0;
Jay Foadb804a2b2011-07-12 14:06:48 +0000424 std::vector<Type*> Tys;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000425 std::vector<Constant*> Inits;
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000426
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000427 for (j = i; j != -1; j = GlobalSet.find_next(j)) {
David Blaikie9ed57a92015-08-21 22:00:44 +0000428 Type *Ty = Globals[j]->getValueType();
Mehdi Aminif6727b02015-07-07 18:49:25 +0000429 MergedSize += DL.getTypeAllocSize(Ty);
Bob Wilson4c8ab192010-11-17 21:25:36 +0000430 if (MergedSize > MaxOffset) {
431 break;
432 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000433 Tys.push_back(Ty);
434 Inits.push_back(Globals[j]->getInitializer());
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000435 }
436
Chris Lattnere40007a2010-09-05 21:18:45 +0000437 StructType *MergedTy = StructType::get(M.getContext(), Tys);
438 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000439
440 GlobalVariable *MergedGV = new GlobalVariable(
John Brawn863bfdb2015-08-11 15:48:04 +0000441 M, MergedTy, isConst, GlobalValue::PrivateLinkage, MergedInit,
442 "_MergedGlobals", nullptr, GlobalVariable::NotThreadLocal, AddrSpace);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000443
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000444 for (ssize_t k = i, idx = 0; k != j; k = GlobalSet.find_next(k)) {
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000445 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
446 std::string Name = Globals[k]->getName();
447
Chris Lattnere40007a2010-09-05 21:18:45 +0000448 Constant *Idx[2] = {
449 ConstantInt::get(Int32Ty, 0),
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000450 ConstantInt::get(Int32Ty, idx++)
Chris Lattnere40007a2010-09-05 21:18:45 +0000451 };
David Blaikie4a2e73b2015-04-02 18:55:32 +0000452 Constant *GEP =
453 ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000454 Globals[k]->replaceAllUsesWith(GEP);
455 Globals[k]->eraseFromParent();
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000456
John Brawn0bef27d2015-08-12 13:36:48 +0000457 // When the linkage is not internal we must emit an alias for the original
458 // variable name as it may be accessed from another object. On non-Mach-O
459 // we can also emit an alias for internal linkage as it's safe to do so.
460 // It's not safe on Mach-O as the alias (and thus the portion of the
461 // MergedGlobals variable) may be dead stripped at link time.
462 if (Linkage != GlobalValue::InternalLinkage ||
463 !TM->getTargetTriple().isOSBinFormatMachO()) {
464 auto *PTy = cast<PointerType>(GEP->getType());
465 GlobalAlias::create(PTy, Linkage, Name, GEP, &M);
466 }
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000467
Devang Patel76c85632011-10-17 17:17:43 +0000468 NumMerged++;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000469 }
470 i = j;
471 }
472
473 return true;
474}
475
Quentin Colombet8fc34092013-03-18 22:30:07 +0000476void GlobalMerge::collectUsedGlobalVariables(Module &M) {
477 // Extract global variables from llvm.used array
478 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
479 if (!GV || !GV->hasInitializer()) return;
480
481 // Should be an array of 'i8*'.
Rafael Espindola74f2e462013-04-22 14:58:02 +0000482 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
483
Quentin Colombet8fc34092013-03-18 22:30:07 +0000484 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
485 if (const GlobalVariable *G =
486 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
487 MustKeepGlobalVariables.insert(G);
488}
489
490void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
Quentin Colombet8fc34092013-03-18 22:30:07 +0000491 collectUsedGlobalVariables(M);
492
493 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
494 ++IFn) {
495 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
496 IBB != IEndBB; ++IBB) {
Mark Seaborn07e74862014-03-13 00:04:17 +0000497 // Follow the invoke link to find the landing pad instruction
Quentin Colombet8fc34092013-03-18 22:30:07 +0000498 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
499 if (!II) continue;
500
501 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
502 // Look for globals in the clauses of the landing pad instruction
503 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
504 Idx != NumClauses; ++Idx)
505 if (const GlobalVariable *GV =
506 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
507 ->stripPointerCasts()))
508 MustKeepGlobalVariables.insert(GV);
509 }
510 }
511}
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000512
Devang Patel76c85632011-10-17 17:17:43 +0000513bool GlobalMerge::doInitialization(Module &M) {
Tim Northoverf804c172014-02-18 11:17:29 +0000514 if (!EnableGlobalMerge)
515 return false;
516
Mehdi Aminif6727b02015-07-07 18:49:25 +0000517 auto &DL = M.getDataLayout();
Silviu Barangaa055aab2013-01-07 12:31:25 +0000518 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
519 BSSGlobals;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000520 bool Changed = false;
Quentin Colombet8fc34092013-03-18 22:30:07 +0000521 setMustKeepGlobalVariables(M);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000522
523 // Grab all non-const globals.
524 for (Module::global_iterator I = M.global_begin(),
525 E = M.global_end(); I != E; ++I) {
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000526 // Merge is safe for "normal" internal or external globals only
527 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
528 continue;
529
John Brawn8b954242015-08-03 12:08:41 +0000530 if (!(MergeExternalGlobals && I->hasExternalLinkage()) &&
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000531 !I->hasInternalLinkage())
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000532 continue;
533
Silviu Barangaa055aab2013-01-07 12:31:25 +0000534 PointerType *PT = dyn_cast<PointerType>(I->getType());
535 assert(PT && "Global variable is not a pointer!");
536
537 unsigned AddressSpace = PT->getAddressSpace();
538
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000539 // Ignore fancy-aligned globals for now.
Mehdi Aminif6727b02015-07-07 18:49:25 +0000540 unsigned Alignment = DL.getPreferredAlignment(I);
David Blaikie9ed57a92015-08-21 22:00:44 +0000541 Type *Ty = I->getValueType();
Mehdi Aminif6727b02015-07-07 18:49:25 +0000542 if (Alignment > DL.getABITypeAlignment(Ty))
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000543 continue;
544
Anton Korobeynikov6bcea062010-07-26 18:45:39 +0000545 // Ignore all 'special' globals.
546 if (I->getName().startswith("llvm.") ||
547 I->getName().startswith(".llvm."))
548 continue;
549
Quentin Colombet8fc34092013-03-18 22:30:07 +0000550 // Ignore all "required" globals:
Quentin Colombet8fc34092013-03-18 22:30:07 +0000551 if (isMustKeepGlobalVariable(I))
552 continue;
553
Mehdi Aminif6727b02015-07-07 18:49:25 +0000554 if (DL.getTypeAllocSize(Ty) < MaxOffset) {
Eric Christopher2af33752014-06-10 20:39:39 +0000555 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000556 BSSGlobals[AddressSpace].push_back(I);
Bob Wilson881b45c2010-11-17 21:25:39 +0000557 else if (I->isConstant())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000558 ConstGlobals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000559 else
Silviu Barangaa055aab2013-01-07 12:31:25 +0000560 Globals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000561 }
562 }
563
David Blaikie47bf5c02015-08-21 22:19:06 +0000564 for (auto &P : Globals)
565 if (P.second.size() > 1)
566 Changed |= doMerge(P.second, M, false, P.first);
Silviu Barangaa055aab2013-01-07 12:31:25 +0000567
David Blaikie47bf5c02015-08-21 22:19:06 +0000568 for (auto &P : BSSGlobals)
569 if (P.second.size() > 1)
570 Changed |= doMerge(P.second, M, false, P.first);
Bob Wilson881b45c2010-11-17 21:25:39 +0000571
David Blaikied4860002015-08-25 17:01:36 +0000572 if (EnableGlobalMergeOnConst)
573 for (auto &P : ConstGlobals)
574 if (P.second.size() > 1)
575 Changed |= doMerge(P.second, M, true, P.first);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000576
577 return Changed;
578}
579
Devang Patel76c85632011-10-17 17:17:43 +0000580bool GlobalMerge::runOnFunction(Function &F) {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000581 return false;
582}
583
Quentin Colombet2393cb92013-03-19 21:46:49 +0000584bool GlobalMerge::doFinalization(Module &M) {
585 MustKeepGlobalVariables.clear();
586 return false;
587}
588
Ahmed Bougacha82076412015-06-04 20:39:23 +0000589Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset,
John Brawn8b954242015-08-03 12:08:41 +0000590 bool OnlyOptimizeForSize,
591 bool MergeExternalByDefault) {
592 bool MergeExternal = (EnableGlobalMergeOnExternal == cl::BOU_UNSET) ?
593 MergeExternalByDefault : (EnableGlobalMergeOnExternal == cl::BOU_TRUE);
594 return new GlobalMerge(TM, Offset, OnlyOptimizeForSize, MergeExternal);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000595}