GlobalMerge.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. //===-- GlobalMerge.cpp - Internal globals merging -----------------------===//
  2. //
  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. //
  15. // For example, consider the code which touches several global variables at
  16. // once:
  17. //
  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".
  52. //
  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).
  60. // ===---------------------------------------------------------------------===//
  61. #include "llvm/Transforms/Scalar.h"
  62. #include "llvm/ADT/DenseMap.h"
  63. #include "llvm/ADT/SmallBitVector.h"
  64. #include "llvm/ADT/SmallPtrSet.h"
  65. #include "llvm/ADT/Statistic.h"
  66. #include "llvm/CodeGen/Passes.h"
  67. #include "llvm/IR/Attributes.h"
  68. #include "llvm/IR/Constants.h"
  69. #include "llvm/IR/DataLayout.h"
  70. #include "llvm/IR/DerivedTypes.h"
  71. #include "llvm/IR/Function.h"
  72. #include "llvm/IR/GlobalVariable.h"
  73. #include "llvm/IR/Instructions.h"
  74. #include "llvm/IR/Intrinsics.h"
  75. #include "llvm/IR/Module.h"
  76. #include "llvm/Pass.h"
  77. #include "llvm/Support/CommandLine.h"
  78. #include "llvm/Support/Debug.h"
  79. #include "llvm/Support/raw_ostream.h"
  80. #include "llvm/Target/TargetLowering.h"
  81. #include "llvm/Target/TargetLoweringObjectFile.h"
  82. #include "llvm/Target/TargetSubtargetInfo.h"
  83. #include <algorithm>
  84. using namespace llvm;
  85. #define DEBUG_TYPE "global-merge"
  86. // FIXME: This is only useful as a last-resort way to disable the pass.
  87. static cl::opt<bool>
  88. EnableGlobalMerge("enable-global-merge", cl::Hidden,
  89. cl::desc("Enable the global merge pass"),
  90. cl::init(true));
  91. static cl::opt<bool> GlobalMergeGroupByUse(
  92. "global-merge-group-by-use", cl::Hidden,
  93. cl::desc("Improve global merge pass to look at uses"), cl::init(true));
  94. static cl::opt<bool> GlobalMergeIgnoreSingleUse(
  95. "global-merge-ignore-single-use", cl::Hidden,
  96. cl::desc("Improve global merge pass to ignore globals only used alone"),
  97. cl::init(true));
  98. static cl::opt<bool>
  99. EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
  100. cl::desc("Enable global merge pass on constants"),
  101. cl::init(false));
  102. // FIXME: this could be a transitional option, and we probably need to remove
  103. // it if only we are sure this optimization could always benefit all targets.
  104. static cl::opt<bool>
  105. EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
  106. cl::desc("Enable global merge pass on external linkage"),
  107. cl::init(false));
  108. STATISTIC(NumMerged, "Number of globals merged");
  109. namespace {
  110. class GlobalMerge : public FunctionPass {
  111. const TargetMachine *TM;
  112. // FIXME: Infer the maximum possible offset depending on the actual users
  113. // (these max offsets are different for the users inside Thumb or ARM
  114. // functions), see the code that passes in the offset in the ARM backend
  115. // for more information.
  116. unsigned MaxOffset;
  117. /// Whether we should try to optimize for size only.
  118. /// Currently, this applies a dead simple heuristic: only consider globals
  119. /// used in minsize functions for merging.
  120. /// FIXME: This could learn about optsize, and be used in the cost model.
  121. bool OnlyOptimizeForSize;
  122. bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
  123. Module &M, bool isConst, unsigned AddrSpace) const;
  124. /// \brief Merge everything in \p Globals for which the corresponding bit
  125. /// in \p GlobalSet is set.
  126. bool doMerge(SmallVectorImpl<GlobalVariable *> &Globals,
  127. const BitVector &GlobalSet, Module &M, bool isConst,
  128. unsigned AddrSpace) const;
  129. /// \brief Check if the given variable has been identified as must keep
  130. /// \pre setMustKeepGlobalVariables must have been called on the Module that
  131. /// contains GV
  132. bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
  133. return MustKeepGlobalVariables.count(GV);
  134. }
  135. /// Collect every variables marked as "used" or used in a landing pad
  136. /// instruction for this Module.
  137. void setMustKeepGlobalVariables(Module &M);
  138. /// Collect every variables marked as "used"
  139. void collectUsedGlobalVariables(Module &M);
  140. /// Keep track of the GlobalVariable that must not be merged away
  141. SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
  142. public:
  143. static char ID; // Pass identification, replacement for typeid.
  144. explicit GlobalMerge(const TargetMachine *TM = nullptr,
  145. unsigned MaximalOffset = 0,
  146. bool OnlyOptimizeForSize = false)
  147. : FunctionPass(ID), TM(TM), MaxOffset(MaximalOffset),
  148. OnlyOptimizeForSize(OnlyOptimizeForSize) {
  149. initializeGlobalMergePass(*PassRegistry::getPassRegistry());
  150. }
  151. bool doInitialization(Module &M) override;
  152. bool runOnFunction(Function &F) override;
  153. bool doFinalization(Module &M) override;
  154. const char *getPassName() const override {
  155. return "Merge internal globals";
  156. }
  157. void getAnalysisUsage(AnalysisUsage &AU) const override {
  158. AU.setPreservesCFG();
  159. FunctionPass::getAnalysisUsage(AU);
  160. }
  161. };
  162. } // end anonymous namespace
  163. char GlobalMerge::ID = 0;
  164. INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables",
  165. false, false)
  166. INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables",
  167. false, false)
  168. bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
  169. Module &M, bool isConst, unsigned AddrSpace) const {
  170. auto &DL = M.getDataLayout();
  171. // FIXME: Find better heuristics
  172. std::stable_sort(
  173. Globals.begin(), Globals.end(),
  174. [&DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
  175. Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
  176. Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
  177. return (DL.getTypeAllocSize(Ty1) < DL.getTypeAllocSize(Ty2));
  178. });
  179. // If we want to just blindly group all globals together, do so.
  180. if (!GlobalMergeGroupByUse) {
  181. BitVector AllGlobals(Globals.size());
  182. AllGlobals.set();
  183. return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
  184. }
  185. // If we want to be smarter, look at all uses of each global, to try to
  186. // discover all sets of globals used together, and how many times each of
  187. // these sets occured.
  188. //
  189. // Keep this reasonably efficient, by having an append-only list of all sets
  190. // discovered so far (UsedGlobalSet), and mapping each "together-ness" unit of
  191. // code (currently, a Function) to the set of globals seen so far that are
  192. // used together in that unit (GlobalUsesByFunction).
  193. //
  194. // When we look at the Nth global, we now that any new set is either:
  195. // - the singleton set {N}, containing this global only, or
  196. // - the union of {N} and a previously-discovered set, containing some
  197. // combination of the previous N-1 globals.
  198. // Using that knowledge, when looking at the Nth global, we can keep:
  199. // - a reference to the singleton set {N} (CurGVOnlySetIdx)
  200. // - a list mapping each previous set to its union with {N} (EncounteredUGS),
  201. // if it actually occurs.
  202. // We keep track of the sets of globals used together "close enough".
  203. struct UsedGlobalSet {
  204. UsedGlobalSet(size_t Size) : Globals(Size), UsageCount(1) {}
  205. BitVector Globals;
  206. unsigned UsageCount;
  207. };
  208. // Each set is unique in UsedGlobalSets.
  209. std::vector<UsedGlobalSet> UsedGlobalSets;
  210. // Avoid repeating the create-global-set pattern.
  211. auto CreateGlobalSet = [&]() -> UsedGlobalSet & {
  212. UsedGlobalSets.emplace_back(Globals.size());
  213. return UsedGlobalSets.back();
  214. };
  215. // The first set is the empty set.
  216. CreateGlobalSet().UsageCount = 0;
  217. // We define "close enough" to be "in the same function".
  218. // FIXME: Grouping uses by function is way too aggressive, so we should have
  219. // a better metric for distance between uses.
  220. // The obvious alternative would be to group by BasicBlock, but that's in
  221. // turn too conservative..
  222. // Anything in between wouldn't be trivial to compute, so just stick with
  223. // per-function grouping.
  224. // The value type is an index into UsedGlobalSets.
  225. // The default (0) conveniently points to the empty set.
  226. DenseMap<Function *, size_t /*UsedGlobalSetIdx*/> GlobalUsesByFunction;
  227. // Now, look at each merge-eligible global in turn.
  228. // Keep track of the sets we already encountered to which we added the
  229. // current global.
  230. // Each element matches the same-index element in UsedGlobalSets.
  231. // This lets us efficiently tell whether a set has already been expanded to
  232. // include the current global.
  233. std::vector<size_t> EncounteredUGS;
  234. for (size_t GI = 0, GE = Globals.size(); GI != GE; ++GI) {
  235. GlobalVariable *GV = Globals[GI];
  236. // Reset the encountered sets for this global...
  237. std::fill(EncounteredUGS.begin(), EncounteredUGS.end(), 0);
  238. // ...and grow it in case we created new sets for the previous global.
  239. EncounteredUGS.resize(UsedGlobalSets.size());
  240. // We might need to create a set that only consists of the current global.
  241. // Keep track of its index into UsedGlobalSets.
  242. size_t CurGVOnlySetIdx = 0;
  243. // For each global, look at all its Uses.
  244. for (auto &U : GV->uses()) {
  245. // This Use might be a ConstantExpr. We're interested in Instruction
  246. // users, so look through ConstantExpr...
  247. Use *UI, *UE;
  248. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
  249. if (CE->use_empty())
  250. continue;
  251. UI = &*CE->use_begin();
  252. UE = nullptr;
  253. } else if (isa<Instruction>(U.getUser())) {
  254. UI = &U;
  255. UE = UI->getNext();
  256. } else {
  257. continue;
  258. }
  259. // ...to iterate on all the instruction users of the global.
  260. // Note that we iterate on Uses and not on Users to be able to getNext().
  261. for (; UI != UE; UI = UI->getNext()) {
  262. Instruction *I = dyn_cast<Instruction>(UI->getUser());
  263. if (!I)
  264. continue;
  265. Function *ParentFn = I->getParent()->getParent();
  266. // If we're only optimizing for size, ignore non-minsize functions.
  267. if (OnlyOptimizeForSize &&
  268. !ParentFn->hasFnAttribute(Attribute::MinSize))
  269. continue;
  270. size_t UGSIdx = GlobalUsesByFunction[ParentFn];
  271. // If this is the first global the basic block uses, map it to the set
  272. // consisting of this global only.
  273. if (!UGSIdx) {
  274. // If that set doesn't exist yet, create it.
  275. if (!CurGVOnlySetIdx) {
  276. CurGVOnlySetIdx = UsedGlobalSets.size();
  277. CreateGlobalSet().Globals.set(GI);
  278. } else {
  279. ++UsedGlobalSets[CurGVOnlySetIdx].UsageCount;
  280. }
  281. GlobalUsesByFunction[ParentFn] = CurGVOnlySetIdx;
  282. continue;
  283. }
  284. // If we already encountered this BB, just increment the counter.
  285. if (UsedGlobalSets[UGSIdx].Globals.test(GI)) {
  286. ++UsedGlobalSets[UGSIdx].UsageCount;
  287. continue;
  288. }
  289. // If not, the previous set wasn't actually used in this function.
  290. --UsedGlobalSets[UGSIdx].UsageCount;
  291. // If we already expanded the previous set to include this global, just
  292. // reuse that expanded set.
  293. if (size_t ExpandedIdx = EncounteredUGS[UGSIdx]) {
  294. ++UsedGlobalSets[ExpandedIdx].UsageCount;
  295. GlobalUsesByFunction[ParentFn] = ExpandedIdx;
  296. continue;
  297. }
  298. // If not, create a new set consisting of the union of the previous set
  299. // and this global. Mark it as encountered, so we can reuse it later.
  300. GlobalUsesByFunction[ParentFn] = EncounteredUGS[UGSIdx] =
  301. UsedGlobalSets.size();
  302. UsedGlobalSet &NewUGS = CreateGlobalSet();
  303. NewUGS.Globals.set(GI);
  304. NewUGS.Globals |= UsedGlobalSets[UGSIdx].Globals;
  305. }
  306. }
  307. }
  308. // Now we found a bunch of sets of globals used together. We accumulated
  309. // the number of times we encountered the sets (i.e., the number of blocks
  310. // that use that exact set of globals).
  311. //
  312. // Multiply that by the size of the set to give us a crude profitability
  313. // metric.
  314. std::sort(UsedGlobalSets.begin(), UsedGlobalSets.end(),
  315. [](const UsedGlobalSet &UGS1, const UsedGlobalSet &UGS2) {
  316. return UGS1.Globals.count() * UGS1.UsageCount <
  317. UGS2.Globals.count() * UGS2.UsageCount;
  318. });
  319. // We can choose to merge all globals together, but ignore globals never used
  320. // with another global. This catches the obviously non-profitable cases of
  321. // having a single global, but is aggressive enough for any other case.
  322. if (GlobalMergeIgnoreSingleUse) {
  323. BitVector AllGlobals(Globals.size());
  324. for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
  325. const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
  326. if (UGS.UsageCount == 0)
  327. continue;
  328. if (UGS.Globals.count() > 1)
  329. AllGlobals |= UGS.Globals;
  330. }
  331. return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
  332. }
  333. // Starting from the sets with the best (=biggest) profitability, find a
  334. // good combination.
  335. // The ideal (and expensive) solution can only be found by trying all
  336. // combinations, looking for the one with the best profitability.
  337. // Don't be smart about it, and just pick the first compatible combination,
  338. // starting with the sets with the best profitability.
  339. BitVector PickedGlobals(Globals.size());
  340. bool Changed = false;
  341. for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
  342. const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
  343. if (UGS.UsageCount == 0)
  344. continue;
  345. if (PickedGlobals.anyCommon(UGS.Globals))
  346. continue;
  347. PickedGlobals |= UGS.Globals;
  348. // If the set only contains one global, there's no point in merging.
  349. // Ignore the global for inclusion in other sets though, so keep it in
  350. // PickedGlobals.
  351. if (UGS.Globals.count() < 2)
  352. continue;
  353. Changed |= doMerge(Globals, UGS.Globals, M, isConst, AddrSpace);
  354. }
  355. return Changed;
  356. }
  357. bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable *> &Globals,
  358. const BitVector &GlobalSet, Module &M, bool isConst,
  359. unsigned AddrSpace) const {
  360. Type *Int32Ty = Type::getInt32Ty(M.getContext());
  361. auto &DL = M.getDataLayout();
  362. assert(Globals.size() > 1);
  363. DEBUG(dbgs() << " Trying to merge set, starts with #"
  364. << GlobalSet.find_first() << "\n");
  365. ssize_t i = GlobalSet.find_first();
  366. while (i != -1) {
  367. ssize_t j = 0;
  368. uint64_t MergedSize = 0;
  369. std::vector<Type*> Tys;
  370. std::vector<Constant*> Inits;
  371. bool HasExternal = false;
  372. GlobalVariable *TheFirstExternal = 0;
  373. for (j = i; j != -1; j = GlobalSet.find_next(j)) {
  374. Type *Ty = Globals[j]->getType()->getElementType();
  375. MergedSize += DL.getTypeAllocSize(Ty);
  376. if (MergedSize > MaxOffset) {
  377. break;
  378. }
  379. Tys.push_back(Ty);
  380. Inits.push_back(Globals[j]->getInitializer());
  381. if (Globals[j]->hasExternalLinkage() && !HasExternal) {
  382. HasExternal = true;
  383. TheFirstExternal = Globals[j];
  384. }
  385. }
  386. // If merged variables doesn't have external linkage, we needn't to expose
  387. // the symbol after merging.
  388. GlobalValue::LinkageTypes Linkage = HasExternal
  389. ? GlobalValue::ExternalLinkage
  390. : GlobalValue::InternalLinkage;
  391. StructType *MergedTy = StructType::get(M.getContext(), Tys);
  392. Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
  393. // If merged variables have external linkage, we use symbol name of the
  394. // first variable merged as the suffix of global symbol name. This would
  395. // be able to avoid the link-time naming conflict for globalm symbols.
  396. GlobalVariable *MergedGV = new GlobalVariable(
  397. M, MergedTy, isConst, Linkage, MergedInit,
  398. HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName()
  399. : "_MergedGlobals",
  400. nullptr, GlobalVariable::NotThreadLocal, AddrSpace);
  401. for (ssize_t k = i, idx = 0; k != j; k = GlobalSet.find_next(k)) {
  402. GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
  403. std::string Name = Globals[k]->getName();
  404. Constant *Idx[2] = {
  405. ConstantInt::get(Int32Ty, 0),
  406. ConstantInt::get(Int32Ty, idx++)
  407. };
  408. Constant *GEP =
  409. ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx);
  410. Globals[k]->replaceAllUsesWith(GEP);
  411. Globals[k]->eraseFromParent();
  412. if (Linkage != GlobalValue::InternalLinkage) {
  413. // Generate a new alias...
  414. auto *PTy = cast<PointerType>(GEP->getType());
  415. GlobalAlias::create(PTy, Linkage, Name, GEP, &M);
  416. }
  417. NumMerged++;
  418. }
  419. i = j;
  420. }
  421. return true;
  422. }
  423. void GlobalMerge::collectUsedGlobalVariables(Module &M) {
  424. // Extract global variables from llvm.used array
  425. const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
  426. if (!GV || !GV->hasInitializer()) return;
  427. // Should be an array of 'i8*'.
  428. const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
  429. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  430. if (const GlobalVariable *G =
  431. dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
  432. MustKeepGlobalVariables.insert(G);
  433. }
  434. void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
  435. collectUsedGlobalVariables(M);
  436. for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
  437. ++IFn) {
  438. for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
  439. IBB != IEndBB; ++IBB) {
  440. // Follow the invoke link to find the landing pad instruction
  441. const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
  442. if (!II) continue;
  443. const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
  444. // Look for globals in the clauses of the landing pad instruction
  445. for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
  446. Idx != NumClauses; ++Idx)
  447. if (const GlobalVariable *GV =
  448. dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
  449. ->stripPointerCasts()))
  450. MustKeepGlobalVariables.insert(GV);
  451. }
  452. }
  453. }
  454. bool GlobalMerge::doInitialization(Module &M) {
  455. if (!EnableGlobalMerge)
  456. return false;
  457. auto &DL = M.getDataLayout();
  458. DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
  459. BSSGlobals;
  460. bool Changed = false;
  461. setMustKeepGlobalVariables(M);
  462. // Grab all non-const globals.
  463. for (Module::global_iterator I = M.global_begin(),
  464. E = M.global_end(); I != E; ++I) {
  465. // Merge is safe for "normal" internal or external globals only
  466. if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
  467. continue;
  468. if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
  469. !I->hasInternalLinkage())
  470. continue;
  471. PointerType *PT = dyn_cast<PointerType>(I->getType());
  472. assert(PT && "Global variable is not a pointer!");
  473. unsigned AddressSpace = PT->getAddressSpace();
  474. // Ignore fancy-aligned globals for now.
  475. unsigned Alignment = DL.getPreferredAlignment(I);
  476. Type *Ty = I->getType()->getElementType();
  477. if (Alignment > DL.getABITypeAlignment(Ty))
  478. continue;
  479. // Ignore all 'special' globals.
  480. if (I->getName().startswith("llvm.") ||
  481. I->getName().startswith(".llvm."))
  482. continue;
  483. // Ignore all "required" globals:
  484. if (isMustKeepGlobalVariable(I))
  485. continue;
  486. if (DL.getTypeAllocSize(Ty) < MaxOffset) {
  487. if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
  488. BSSGlobals[AddressSpace].push_back(I);
  489. else if (I->isConstant())
  490. ConstGlobals[AddressSpace].push_back(I);
  491. else
  492. Globals[AddressSpace].push_back(I);
  493. }
  494. }
  495. for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
  496. I = Globals.begin(), E = Globals.end(); I != E; ++I)
  497. if (I->second.size() > 1)
  498. Changed |= doMerge(I->second, M, false, I->first);
  499. for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
  500. I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
  501. if (I->second.size() > 1)
  502. Changed |= doMerge(I->second, M, false, I->first);
  503. if (EnableGlobalMergeOnConst)
  504. for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
  505. I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
  506. if (I->second.size() > 1)
  507. Changed |= doMerge(I->second, M, true, I->first);
  508. return Changed;
  509. }
  510. bool GlobalMerge::runOnFunction(Function &F) {
  511. return false;
  512. }
  513. bool GlobalMerge::doFinalization(Module &M) {
  514. MustKeepGlobalVariables.clear();
  515. return false;
  516. }
  517. Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset,
  518. bool OnlyOptimizeForSize) {
  519. return new GlobalMerge(TM, Offset, OnlyOptimizeForSize);
  520. }