Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 1 | //===-- GlobalMerge.cpp - Internal globals merging -----------------------===// |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 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 | // |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 15 | // For example, consider the code which touches several global variables at |
Eric Christopher | bf86fd3 | 2010-09-28 04:18:29 +0000 | [diff] [blame] | 16 | // once: |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 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". |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 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). |
Eric Christopher | bf86fd3 | 2010-09-28 04:18:29 +0000 | [diff] [blame] | 60 | // ===---------------------------------------------------------------------===// |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 61 | |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 62 | #include "llvm/Transforms/Scalar.h" |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 63 | #include "llvm/ADT/DenseMap.h" |
| 64 | #include "llvm/ADT/SmallBitVector.h" |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 65 | #include "llvm/ADT/SmallPtrSet.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 66 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | d990388 | 2015-01-14 11:23:27 +0000 | [diff] [blame] | 67 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 68 | #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 Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 77 | #include "llvm/Pass.h" |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 78 | #include "llvm/Support/CommandLine.h" |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 79 | #include "llvm/Support/Debug.h" |
| 80 | #include "llvm/Support/raw_ostream.h" |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 81 | #include "llvm/Target/TargetLowering.h" |
Bob Wilson | 881b45c | 2010-11-17 21:25:39 +0000 | [diff] [blame] | 82 | #include "llvm/Target/TargetLoweringObjectFile.h" |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 83 | #include "llvm/Target/TargetSubtargetInfo.h" |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 84 | #include <algorithm> |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 85 | using namespace llvm; |
| 86 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 87 | #define DEBUG_TYPE "global-merge" |
| 88 | |
Ahmed Bougacha | b96444e | 2015-04-11 00:06:36 +0000 | [diff] [blame] | 89 | // FIXME: This is only useful as a last-resort way to disable the pass. |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 90 | static cl::opt<bool> |
Jiangning Liu | 3e5b855 | 2014-06-11 06:35:26 +0000 | [diff] [blame] | 91 | EnableGlobalMerge("enable-global-merge", cl::Hidden, |
Ahmed Bougacha | b96444e | 2015-04-11 00:06:36 +0000 | [diff] [blame] | 92 | cl::desc("Enable the global merge pass"), |
Tim Northover | f804c17 | 2014-02-18 11:17:29 +0000 | [diff] [blame] | 93 | cl::init(true)); |
| 94 | |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 95 | static 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 | |
| 99 | static 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 Northover | f804c17 | 2014-02-18 11:17:29 +0000 | [diff] [blame] | 104 | static cl::opt<bool> |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 105 | EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden, |
Jakub Staszak | 6b36db0 | 2013-07-22 21:11:30 +0000 | [diff] [blame] | 106 | cl::desc("Enable global merge pass on constants"), |
| 107 | cl::init(false)); |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 108 | |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 109 | // 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 Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 111 | static cl::opt<cl::boolOrDefault> |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 112 | EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden, |
John Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 113 | cl::desc("Enable global merge pass on external linkage")); |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 114 | |
Eric Christopher | ed47b22 | 2015-02-23 19:28:45 +0000 | [diff] [blame] | 115 | STATISTIC(NumMerged, "Number of globals merged"); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 116 | namespace { |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 117 | class GlobalMerge : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 118 | const TargetMachine *TM; |
Eric Christopher | ed47b22 | 2015-02-23 19:28:45 +0000 | [diff] [blame] | 119 | // 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 Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 124 | |
Ahmed Bougacha | 8207641 | 2015-06-04 20:39:23 +0000 | [diff] [blame] | 125 | /// 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 Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 131 | /// Whether we should merge global variables that have external linkage. |
| 132 | bool MergeExternalGlobals; |
| 133 | |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 134 | bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals, |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 135 | Module &M, bool isConst, unsigned AddrSpace) const; |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 136 | /// \brief Merge everything in \p Globals for which the corresponding bit |
| 137 | /// in \p GlobalSet is set. |
| 138 | bool doMerge(SmallVectorImpl<GlobalVariable *> &Globals, |
| 139 | const BitVector &GlobalSet, Module &M, bool isConst, |
| 140 | unsigned AddrSpace) const; |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 141 | |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 142 | /// \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 Colombet | 2393cb9 | 2013-03-19 21:46:49 +0000 | [diff] [blame] | 156 | /// Keep track of the GlobalVariable that must not be merged away |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 157 | SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables; |
| 158 | |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 159 | public: |
| 160 | static char ID; // Pass identification, replacement for typeid. |
Eric Christopher | ed47b22 | 2015-02-23 19:28:45 +0000 | [diff] [blame] | 161 | explicit GlobalMerge(const TargetMachine *TM = nullptr, |
Ahmed Bougacha | 8207641 | 2015-06-04 20:39:23 +0000 | [diff] [blame] | 162 | unsigned MaximalOffset = 0, |
John Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 163 | bool OnlyOptimizeForSize = false, |
| 164 | bool MergeExternalGlobals = false) |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 165 | : FunctionPass(ID), TM(TM), MaxOffset(MaximalOffset), |
John Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 166 | OnlyOptimizeForSize(OnlyOptimizeForSize), |
| 167 | MergeExternalGlobals(MergeExternalGlobals) { |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 168 | initializeGlobalMergePass(*PassRegistry::getPassRegistry()); |
| 169 | } |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 170 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 171 | bool doInitialization(Module &M) override; |
| 172 | bool runOnFunction(Function &F) override; |
| 173 | bool doFinalization(Module &M) override; |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 174 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 175 | const char *getPassName() const override { |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 176 | return "Merge internal globals"; |
| 177 | } |
| 178 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 179 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 180 | AU.setPreservesCFG(); |
| 181 | FunctionPass::getAnalysisUsage(AU); |
| 182 | } |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 183 | }; |
| 184 | } // end anonymous namespace |
| 185 | |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 186 | char GlobalMerge::ID = 0; |
Eric Christopher | ed47b22 | 2015-02-23 19:28:45 +0000 | [diff] [blame] | 187 | INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables", |
| 188 | false, false) |
| 189 | INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables", |
| 190 | false, false) |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 191 | |
| 192 | bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals, |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 193 | Module &M, bool isConst, unsigned AddrSpace) const { |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 194 | auto &DL = M.getDataLayout(); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 195 | // FIXME: Find better heuristics |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 196 | std::stable_sort( |
| 197 | Globals.begin(), Globals.end(), |
| 198 | [&DL](const GlobalVariable *GV1, const GlobalVariable *GV2) { |
| 199 | Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType(); |
| 200 | Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType(); |
Benjamin Kramer | 3a377bc | 2014-03-01 11:47:00 +0000 | [diff] [blame] | 201 | |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 202 | return (DL.getTypeAllocSize(Ty1) < DL.getTypeAllocSize(Ty2)); |
| 203 | }); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 204 | |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 205 | // If we want to just blindly group all globals together, do so. |
| 206 | if (!GlobalMergeGroupByUse) { |
| 207 | BitVector AllGlobals(Globals.size()); |
| 208 | AllGlobals.set(); |
| 209 | return doMerge(Globals, AllGlobals, M, isConst, AddrSpace); |
| 210 | } |
| 211 | |
| 212 | // If we want to be smarter, look at all uses of each global, to try to |
| 213 | // discover all sets of globals used together, and how many times each of |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 214 | // these sets occurred. |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 215 | // |
| 216 | // Keep this reasonably efficient, by having an append-only list of all sets |
| 217 | // discovered so far (UsedGlobalSet), and mapping each "together-ness" unit of |
| 218 | // code (currently, a Function) to the set of globals seen so far that are |
| 219 | // used together in that unit (GlobalUsesByFunction). |
| 220 | // |
| 221 | // When we look at the Nth global, we now that any new set is either: |
| 222 | // - the singleton set {N}, containing this global only, or |
| 223 | // - the union of {N} and a previously-discovered set, containing some |
| 224 | // combination of the previous N-1 globals. |
| 225 | // Using that knowledge, when looking at the Nth global, we can keep: |
| 226 | // - a reference to the singleton set {N} (CurGVOnlySetIdx) |
| 227 | // - a list mapping each previous set to its union with {N} (EncounteredUGS), |
| 228 | // if it actually occurs. |
| 229 | |
| 230 | // We keep track of the sets of globals used together "close enough". |
| 231 | struct UsedGlobalSet { |
| 232 | UsedGlobalSet(size_t Size) : Globals(Size), UsageCount(1) {} |
| 233 | BitVector Globals; |
| 234 | unsigned UsageCount; |
| 235 | }; |
| 236 | |
| 237 | // Each set is unique in UsedGlobalSets. |
| 238 | std::vector<UsedGlobalSet> UsedGlobalSets; |
| 239 | |
| 240 | // Avoid repeating the create-global-set pattern. |
| 241 | auto CreateGlobalSet = [&]() -> UsedGlobalSet & { |
| 242 | UsedGlobalSets.emplace_back(Globals.size()); |
| 243 | return UsedGlobalSets.back(); |
| 244 | }; |
| 245 | |
| 246 | // The first set is the empty set. |
| 247 | CreateGlobalSet().UsageCount = 0; |
| 248 | |
| 249 | // We define "close enough" to be "in the same function". |
| 250 | // FIXME: Grouping uses by function is way too aggressive, so we should have |
| 251 | // a better metric for distance between uses. |
| 252 | // The obvious alternative would be to group by BasicBlock, but that's in |
| 253 | // turn too conservative.. |
| 254 | // Anything in between wouldn't be trivial to compute, so just stick with |
| 255 | // per-function grouping. |
| 256 | |
| 257 | // The value type is an index into UsedGlobalSets. |
| 258 | // The default (0) conveniently points to the empty set. |
| 259 | DenseMap<Function *, size_t /*UsedGlobalSetIdx*/> GlobalUsesByFunction; |
| 260 | |
| 261 | // Now, look at each merge-eligible global in turn. |
| 262 | |
| 263 | // Keep track of the sets we already encountered to which we added the |
| 264 | // current global. |
| 265 | // Each element matches the same-index element in UsedGlobalSets. |
| 266 | // This lets us efficiently tell whether a set has already been expanded to |
| 267 | // include the current global. |
| 268 | std::vector<size_t> EncounteredUGS; |
| 269 | |
| 270 | for (size_t GI = 0, GE = Globals.size(); GI != GE; ++GI) { |
| 271 | GlobalVariable *GV = Globals[GI]; |
| 272 | |
| 273 | // Reset the encountered sets for this global... |
| 274 | std::fill(EncounteredUGS.begin(), EncounteredUGS.end(), 0); |
| 275 | // ...and grow it in case we created new sets for the previous global. |
| 276 | EncounteredUGS.resize(UsedGlobalSets.size()); |
| 277 | |
| 278 | // We might need to create a set that only consists of the current global. |
| 279 | // Keep track of its index into UsedGlobalSets. |
| 280 | size_t CurGVOnlySetIdx = 0; |
| 281 | |
| 282 | // For each global, look at all its Uses. |
| 283 | for (auto &U : GV->uses()) { |
| 284 | // This Use might be a ConstantExpr. We're interested in Instruction |
| 285 | // users, so look through ConstantExpr... |
| 286 | Use *UI, *UE; |
| 287 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) { |
Oliver Stannard | 8379e29 | 2015-06-08 16:55:31 +0000 | [diff] [blame] | 288 | if (CE->use_empty()) |
| 289 | continue; |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 290 | UI = &*CE->use_begin(); |
| 291 | UE = nullptr; |
| 292 | } else if (isa<Instruction>(U.getUser())) { |
| 293 | UI = &U; |
| 294 | UE = UI->getNext(); |
| 295 | } else { |
| 296 | continue; |
| 297 | } |
| 298 | |
| 299 | // ...to iterate on all the instruction users of the global. |
| 300 | // Note that we iterate on Uses and not on Users to be able to getNext(). |
| 301 | for (; UI != UE; UI = UI->getNext()) { |
| 302 | Instruction *I = dyn_cast<Instruction>(UI->getUser()); |
| 303 | if (!I) |
| 304 | continue; |
| 305 | |
| 306 | Function *ParentFn = I->getParent()->getParent(); |
Ahmed Bougacha | 8207641 | 2015-06-04 20:39:23 +0000 | [diff] [blame] | 307 | |
| 308 | // If we're only optimizing for size, ignore non-minsize functions. |
Sanjay Patel | 1cd6d88 | 2015-08-18 16:44:23 +0000 | [diff] [blame] | 309 | if (OnlyOptimizeForSize && !ParentFn->optForMinSize()) |
Ahmed Bougacha | 8207641 | 2015-06-04 20:39:23 +0000 | [diff] [blame] | 310 | continue; |
| 311 | |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 312 | size_t UGSIdx = GlobalUsesByFunction[ParentFn]; |
| 313 | |
| 314 | // If this is the first global the basic block uses, map it to the set |
| 315 | // consisting of this global only. |
| 316 | if (!UGSIdx) { |
| 317 | // If that set doesn't exist yet, create it. |
| 318 | if (!CurGVOnlySetIdx) { |
| 319 | CurGVOnlySetIdx = UsedGlobalSets.size(); |
| 320 | CreateGlobalSet().Globals.set(GI); |
| 321 | } else { |
| 322 | ++UsedGlobalSets[CurGVOnlySetIdx].UsageCount; |
| 323 | } |
| 324 | |
| 325 | GlobalUsesByFunction[ParentFn] = CurGVOnlySetIdx; |
| 326 | continue; |
| 327 | } |
| 328 | |
| 329 | // If we already encountered this BB, just increment the counter. |
| 330 | if (UsedGlobalSets[UGSIdx].Globals.test(GI)) { |
| 331 | ++UsedGlobalSets[UGSIdx].UsageCount; |
| 332 | continue; |
| 333 | } |
| 334 | |
| 335 | // If not, the previous set wasn't actually used in this function. |
| 336 | --UsedGlobalSets[UGSIdx].UsageCount; |
| 337 | |
| 338 | // If we already expanded the previous set to include this global, just |
| 339 | // reuse that expanded set. |
| 340 | if (size_t ExpandedIdx = EncounteredUGS[UGSIdx]) { |
| 341 | ++UsedGlobalSets[ExpandedIdx].UsageCount; |
| 342 | GlobalUsesByFunction[ParentFn] = ExpandedIdx; |
| 343 | continue; |
| 344 | } |
| 345 | |
| 346 | // If not, create a new set consisting of the union of the previous set |
| 347 | // and this global. Mark it as encountered, so we can reuse it later. |
| 348 | GlobalUsesByFunction[ParentFn] = EncounteredUGS[UGSIdx] = |
| 349 | UsedGlobalSets.size(); |
| 350 | |
| 351 | UsedGlobalSet &NewUGS = CreateGlobalSet(); |
| 352 | NewUGS.Globals.set(GI); |
| 353 | NewUGS.Globals |= UsedGlobalSets[UGSIdx].Globals; |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // Now we found a bunch of sets of globals used together. We accumulated |
| 359 | // the number of times we encountered the sets (i.e., the number of blocks |
| 360 | // that use that exact set of globals). |
| 361 | // |
| 362 | // Multiply that by the size of the set to give us a crude profitability |
| 363 | // metric. |
| 364 | std::sort(UsedGlobalSets.begin(), UsedGlobalSets.end(), |
| 365 | [](const UsedGlobalSet &UGS1, const UsedGlobalSet &UGS2) { |
| 366 | return UGS1.Globals.count() * UGS1.UsageCount < |
| 367 | UGS2.Globals.count() * UGS2.UsageCount; |
| 368 | }); |
| 369 | |
| 370 | // We can choose to merge all globals together, but ignore globals never used |
| 371 | // with another global. This catches the obviously non-profitable cases of |
| 372 | // having a single global, but is aggressive enough for any other case. |
| 373 | if (GlobalMergeIgnoreSingleUse) { |
| 374 | BitVector AllGlobals(Globals.size()); |
| 375 | for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) { |
| 376 | const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1]; |
| 377 | if (UGS.UsageCount == 0) |
| 378 | continue; |
| 379 | if (UGS.Globals.count() > 1) |
| 380 | AllGlobals |= UGS.Globals; |
| 381 | } |
| 382 | return doMerge(Globals, AllGlobals, M, isConst, AddrSpace); |
| 383 | } |
| 384 | |
| 385 | // Starting from the sets with the best (=biggest) profitability, find a |
| 386 | // good combination. |
| 387 | // The ideal (and expensive) solution can only be found by trying all |
| 388 | // combinations, looking for the one with the best profitability. |
| 389 | // Don't be smart about it, and just pick the first compatible combination, |
| 390 | // starting with the sets with the best profitability. |
| 391 | BitVector PickedGlobals(Globals.size()); |
| 392 | bool Changed = false; |
| 393 | |
| 394 | for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) { |
| 395 | const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1]; |
| 396 | if (UGS.UsageCount == 0) |
| 397 | continue; |
| 398 | if (PickedGlobals.anyCommon(UGS.Globals)) |
| 399 | continue; |
| 400 | PickedGlobals |= UGS.Globals; |
| 401 | // If the set only contains one global, there's no point in merging. |
| 402 | // Ignore the global for inclusion in other sets though, so keep it in |
| 403 | // PickedGlobals. |
| 404 | if (UGS.Globals.count() < 2) |
| 405 | continue; |
| 406 | Changed |= doMerge(Globals, UGS.Globals, M, isConst, AddrSpace); |
| 407 | } |
| 408 | |
| 409 | return Changed; |
| 410 | } |
| 411 | |
| 412 | bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable *> &Globals, |
| 413 | const BitVector &GlobalSet, Module &M, bool isConst, |
| 414 | unsigned AddrSpace) const { |
| 415 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 416 | Type *Int32Ty = Type::getInt32Ty(M.getContext()); |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 417 | auto &DL = M.getDataLayout(); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 418 | |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 419 | assert(Globals.size() > 1); |
| 420 | |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 421 | DEBUG(dbgs() << " Trying to merge set, starts with #" |
| 422 | << GlobalSet.find_first() << "\n"); |
| 423 | |
| 424 | ssize_t i = GlobalSet.find_first(); |
| 425 | while (i != -1) { |
| 426 | ssize_t j = 0; |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 427 | uint64_t MergedSize = 0; |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 428 | std::vector<Type*> Tys; |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 429 | std::vector<Constant*> Inits; |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 430 | |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 431 | for (j = i; j != -1; j = GlobalSet.find_next(j)) { |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 432 | Type *Ty = Globals[j]->getType()->getElementType(); |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 433 | MergedSize += DL.getTypeAllocSize(Ty); |
Bob Wilson | 4c8ab19 | 2010-11-17 21:25:36 +0000 | [diff] [blame] | 434 | if (MergedSize > MaxOffset) { |
| 435 | break; |
| 436 | } |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 437 | Tys.push_back(Ty); |
| 438 | Inits.push_back(Globals[j]->getInitializer()); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 439 | } |
| 440 | |
Chris Lattner | e40007a | 2010-09-05 21:18:45 +0000 | [diff] [blame] | 441 | StructType *MergedTy = StructType::get(M.getContext(), Tys); |
| 442 | Constant *MergedInit = ConstantStruct::get(MergedTy, Inits); |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 443 | |
| 444 | GlobalVariable *MergedGV = new GlobalVariable( |
John Brawn | 863bfdb | 2015-08-11 15:48:04 +0000 | [diff] [blame] | 445 | M, MergedTy, isConst, GlobalValue::PrivateLinkage, MergedInit, |
| 446 | "_MergedGlobals", nullptr, GlobalVariable::NotThreadLocal, AddrSpace); |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 447 | |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 448 | for (ssize_t k = i, idx = 0; k != j; k = GlobalSet.find_next(k)) { |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 449 | GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage(); |
| 450 | std::string Name = Globals[k]->getName(); |
| 451 | |
Chris Lattner | e40007a | 2010-09-05 21:18:45 +0000 | [diff] [blame] | 452 | Constant *Idx[2] = { |
| 453 | ConstantInt::get(Int32Ty, 0), |
Ahmed Bougacha | 279e3ee | 2015-04-18 01:21:58 +0000 | [diff] [blame] | 454 | ConstantInt::get(Int32Ty, idx++) |
Chris Lattner | e40007a | 2010-09-05 21:18:45 +0000 | [diff] [blame] | 455 | }; |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 456 | Constant *GEP = |
| 457 | ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 458 | Globals[k]->replaceAllUsesWith(GEP); |
| 459 | Globals[k]->eraseFromParent(); |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 460 | |
John Brawn | 0bef27d | 2015-08-12 13:36:48 +0000 | [diff] [blame] | 461 | // When the linkage is not internal we must emit an alias for the original |
| 462 | // variable name as it may be accessed from another object. On non-Mach-O |
| 463 | // we can also emit an alias for internal linkage as it's safe to do so. |
| 464 | // It's not safe on Mach-O as the alias (and thus the portion of the |
| 465 | // MergedGlobals variable) may be dead stripped at link time. |
| 466 | if (Linkage != GlobalValue::InternalLinkage || |
| 467 | !TM->getTargetTriple().isOSBinFormatMachO()) { |
| 468 | auto *PTy = cast<PointerType>(GEP->getType()); |
| 469 | GlobalAlias::create(PTy, Linkage, Name, GEP, &M); |
| 470 | } |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 471 | |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 472 | NumMerged++; |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 473 | } |
| 474 | i = j; |
| 475 | } |
| 476 | |
| 477 | return true; |
| 478 | } |
| 479 | |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 480 | void GlobalMerge::collectUsedGlobalVariables(Module &M) { |
| 481 | // Extract global variables from llvm.used array |
| 482 | const GlobalVariable *GV = M.getGlobalVariable("llvm.used"); |
| 483 | if (!GV || !GV->hasInitializer()) return; |
| 484 | |
| 485 | // Should be an array of 'i8*'. |
Rafael Espindola | 74f2e46 | 2013-04-22 14:58:02 +0000 | [diff] [blame] | 486 | const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer()); |
| 487 | |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 488 | for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) |
| 489 | if (const GlobalVariable *G = |
| 490 | dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts())) |
| 491 | MustKeepGlobalVariables.insert(G); |
| 492 | } |
| 493 | |
| 494 | void GlobalMerge::setMustKeepGlobalVariables(Module &M) { |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 495 | collectUsedGlobalVariables(M); |
| 496 | |
| 497 | for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn; |
| 498 | ++IFn) { |
| 499 | for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end(); |
| 500 | IBB != IEndBB; ++IBB) { |
Mark Seaborn | 07e7486 | 2014-03-13 00:04:17 +0000 | [diff] [blame] | 501 | // Follow the invoke link to find the landing pad instruction |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 502 | const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator()); |
| 503 | if (!II) continue; |
| 504 | |
| 505 | const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst(); |
| 506 | // Look for globals in the clauses of the landing pad instruction |
| 507 | for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses(); |
| 508 | Idx != NumClauses; ++Idx) |
| 509 | if (const GlobalVariable *GV = |
| 510 | dyn_cast<GlobalVariable>(LPInst->getClause(Idx) |
| 511 | ->stripPointerCasts())) |
| 512 | MustKeepGlobalVariables.insert(GV); |
| 513 | } |
| 514 | } |
| 515 | } |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 516 | |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 517 | bool GlobalMerge::doInitialization(Module &M) { |
Tim Northover | f804c17 | 2014-02-18 11:17:29 +0000 | [diff] [blame] | 518 | if (!EnableGlobalMerge) |
| 519 | return false; |
| 520 | |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 521 | auto &DL = M.getDataLayout(); |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 522 | DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals, |
| 523 | BSSGlobals; |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 524 | bool Changed = false; |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 525 | setMustKeepGlobalVariables(M); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 526 | |
| 527 | // Grab all non-const globals. |
| 528 | for (Module::global_iterator I = M.global_begin(), |
| 529 | E = M.global_end(); I != E; ++I) { |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 530 | // Merge is safe for "normal" internal or external globals only |
| 531 | if (I->isDeclaration() || I->isThreadLocal() || I->hasSection()) |
| 532 | continue; |
| 533 | |
John Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 534 | if (!(MergeExternalGlobals && I->hasExternalLinkage()) && |
Jiangning Liu | b2ae37f | 2014-06-11 06:44:53 +0000 | [diff] [blame] | 535 | !I->hasInternalLinkage()) |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 536 | continue; |
| 537 | |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 538 | PointerType *PT = dyn_cast<PointerType>(I->getType()); |
| 539 | assert(PT && "Global variable is not a pointer!"); |
| 540 | |
| 541 | unsigned AddressSpace = PT->getAddressSpace(); |
| 542 | |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 543 | // Ignore fancy-aligned globals for now. |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 544 | unsigned Alignment = DL.getPreferredAlignment(I); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 545 | Type *Ty = I->getType()->getElementType(); |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 546 | if (Alignment > DL.getABITypeAlignment(Ty)) |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 547 | continue; |
| 548 | |
Anton Korobeynikov | 6bcea06 | 2010-07-26 18:45:39 +0000 | [diff] [blame] | 549 | // Ignore all 'special' globals. |
| 550 | if (I->getName().startswith("llvm.") || |
| 551 | I->getName().startswith(".llvm.")) |
| 552 | continue; |
| 553 | |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 554 | // Ignore all "required" globals: |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 555 | if (isMustKeepGlobalVariable(I)) |
| 556 | continue; |
| 557 | |
Mehdi Amini | f6727b0 | 2015-07-07 18:49:25 +0000 | [diff] [blame] | 558 | if (DL.getTypeAllocSize(Ty) < MaxOffset) { |
Eric Christopher | 2af3375 | 2014-06-10 20:39:39 +0000 | [diff] [blame] | 559 | if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal()) |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 560 | BSSGlobals[AddressSpace].push_back(I); |
Bob Wilson | 881b45c | 2010-11-17 21:25:39 +0000 | [diff] [blame] | 561 | else if (I->isConstant()) |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 562 | ConstGlobals[AddressSpace].push_back(I); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 563 | else |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 564 | Globals[AddressSpace].push_back(I); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 565 | } |
| 566 | } |
| 567 | |
Silviu Baranga | a055aab | 2013-01-07 12:31:25 +0000 | [diff] [blame] | 568 | for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator |
| 569 | I = Globals.begin(), E = Globals.end(); I != E; ++I) |
| 570 | if (I->second.size() > 1) |
| 571 | Changed |= doMerge(I->second, M, false, I->first); |
| 572 | |
| 573 | for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator |
| 574 | I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I) |
| 575 | if (I->second.size() > 1) |
| 576 | Changed |= doMerge(I->second, M, false, I->first); |
Bob Wilson | 881b45c | 2010-11-17 21:25:39 +0000 | [diff] [blame] | 577 | |
Quentin Colombet | 8fc3409 | 2013-03-18 22:30:07 +0000 | [diff] [blame] | 578 | if (EnableGlobalMergeOnConst) |
| 579 | for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator |
| 580 | I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I) |
| 581 | if (I->second.size() > 1) |
| 582 | Changed |= doMerge(I->second, M, true, I->first); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 583 | |
| 584 | return Changed; |
| 585 | } |
| 586 | |
Devang Patel | 76c8563 | 2011-10-17 17:17:43 +0000 | [diff] [blame] | 587 | bool GlobalMerge::runOnFunction(Function &F) { |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 588 | return false; |
| 589 | } |
| 590 | |
Quentin Colombet | 2393cb9 | 2013-03-19 21:46:49 +0000 | [diff] [blame] | 591 | bool GlobalMerge::doFinalization(Module &M) { |
| 592 | MustKeepGlobalVariables.clear(); |
| 593 | return false; |
| 594 | } |
| 595 | |
Ahmed Bougacha | 8207641 | 2015-06-04 20:39:23 +0000 | [diff] [blame] | 596 | Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset, |
John Brawn | 8b95424 | 2015-08-03 12:08:41 +0000 | [diff] [blame] | 597 | bool OnlyOptimizeForSize, |
| 598 | bool MergeExternalByDefault) { |
| 599 | bool MergeExternal = (EnableGlobalMergeOnExternal == cl::BOU_UNSET) ? |
| 600 | MergeExternalByDefault : (EnableGlobalMergeOnExternal == cl::BOU_TRUE); |
| 601 | return new GlobalMerge(TM, Offset, OnlyOptimizeForSize, MergeExternal); |
Anton Korobeynikov | 19edda0 | 2010-07-24 21:52:08 +0000 | [diff] [blame] | 602 | } |