GlobalMerge.cpp 22 KB

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