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 54 #include "llvm/Transforms/Scalar.h" 55 #include "llvm/ADT/SmallPtrSet.h" 56 #include "llvm/ADT/Statistic.h" 57 #include "llvm/CodeGen/Passes.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/Function.h" 63 #include "llvm/IR/GlobalVariable.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/Pass.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Target/TargetLowering.h" 70 #include "llvm/Target/TargetLoweringObjectFile.h" 71 #include "llvm/Target/TargetSubtargetInfo.h" 72 using namespace llvm; 73 74 #define DEBUG_TYPE "global-merge" 75 76 static cl::opt<bool> 77 EnableGlobalMerge("enable-global-merge", cl::Hidden, 78 cl::desc("Enable global merge pass"), 79 cl::init(true)); 80 81 static cl::opt<bool> 82 EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden, 83 cl::desc("Enable global merge pass on constants"), 84 cl::init(false)); 85 86 // FIXME: this could be a transitional option, and we probably need to remove 87 // it if only we are sure this optimization could always benefit all targets. 88 static cl::opt<bool> 89 EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden, 90 cl::desc("Enable global merge pass on external linkage"), 91 cl::init(false)); 92 93 STATISTIC(NumMerged, "Number of globals merged"); 94 namespace { 95 class GlobalMerge : public FunctionPass { 96 const TargetMachine *TM; 97 const DataLayout *DL; 98 // FIXME: Infer the maximum possible offset depending on the actual users 99 // (these max offsets are different for the users inside Thumb or ARM 100 // functions), see the code that passes in the offset in the ARM backend 101 // for more information. 102 unsigned MaxOffset; 103 104 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals, 105 Module &M, bool isConst, unsigned AddrSpace) const; 106 107 /// \brief Check if the given variable has been identified as must keep 108 /// \pre setMustKeepGlobalVariables must have been called on the Module that 109 /// contains GV 110 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const { 111 return MustKeepGlobalVariables.count(GV); 112 } 113 114 /// Collect every variables marked as "used" or used in a landing pad 115 /// instruction for this Module. 116 void setMustKeepGlobalVariables(Module &M); 117 118 /// Collect every variables marked as "used" 119 void collectUsedGlobalVariables(Module &M); 120 121 /// Keep track of the GlobalVariable that must not be merged away 122 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables; 123 124 public: 125 static char ID; // Pass identification, replacement for typeid. 126 explicit GlobalMerge(const TargetMachine *TM = nullptr, 127 unsigned MaximalOffset = 0) 128 : FunctionPass(ID), TM(TM), DL(TM->getDataLayout()), 129 MaxOffset(MaximalOffset) { 130 initializeGlobalMergePass(*PassRegistry::getPassRegistry()); 131 } 132 133 bool doInitialization(Module &M) override; 134 bool runOnFunction(Function &F) override; 135 bool doFinalization(Module &M) override; 136 137 const char *getPassName() const override { 138 return "Merge internal globals"; 139 } 140 141 void getAnalysisUsage(AnalysisUsage &AU) const override { 142 AU.setPreservesCFG(); 143 FunctionPass::getAnalysisUsage(AU); 144 } 145 }; 146 } // end anonymous namespace 147 148 char GlobalMerge::ID = 0; 149 INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables", 150 false, false) 151 INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables", 152 false, false) 153 154 bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals, 155 Module &M, bool isConst, unsigned AddrSpace) const { 156 // FIXME: Find better heuristics 157 std::stable_sort(Globals.begin(), Globals.end(), 158 [this](const GlobalVariable *GV1, const GlobalVariable *GV2) { 159 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType(); 160 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType(); 161 162 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2)); 163 }); 164 165 Type *Int32Ty = Type::getInt32Ty(M.getContext()); 166 167 assert(Globals.size() > 1); 168 169 // FIXME: This simple solution merges globals all together as maximum as 170 // possible. However, with this solution it would be hard to remove dead 171 // global symbols at link-time. An alternative solution could be checking 172 // global symbols references function by function, and make the symbols 173 // being referred in the same function merged and we would probably need 174 // to introduce heuristic algorithm to solve the merge conflict from 175 // different functions. 176 for (size_t i = 0, e = Globals.size(); i != e; ) { 177 size_t j = 0; 178 uint64_t MergedSize = 0; 179 std::vector<Type*> Tys; 180 std::vector<Constant*> Inits; 181 182 bool HasExternal = false; 183 GlobalVariable *TheFirstExternal = 0; 184 for (j = i; j != e; ++j) { 185 Type *Ty = Globals[j]->getType()->getElementType(); 186 MergedSize += DL->getTypeAllocSize(Ty); 187 if (MergedSize > MaxOffset) { 188 break; 189 } 190 Tys.push_back(Ty); 191 Inits.push_back(Globals[j]->getInitializer()); 192 193 if (Globals[j]->hasExternalLinkage() && !HasExternal) { 194 HasExternal = true; 195 TheFirstExternal = Globals[j]; 196 } 197 } 198 199 // If merged variables doesn't have external linkage, we needn't to expose 200 // the symbol after merging. 201 GlobalValue::LinkageTypes Linkage = HasExternal 202 ? GlobalValue::ExternalLinkage 203 : GlobalValue::InternalLinkage; 204 205 StructType *MergedTy = StructType::get(M.getContext(), Tys); 206 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits); 207 208 // If merged variables have external linkage, we use symbol name of the 209 // first variable merged as the suffix of global symbol name. This would 210 // be able to avoid the link-time naming conflict for globalm symbols. 211 GlobalVariable *MergedGV = new GlobalVariable( 212 M, MergedTy, isConst, Linkage, MergedInit, 213 HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName() 214 : "_MergedGlobals", 215 nullptr, GlobalVariable::NotThreadLocal, AddrSpace); 216 217 for (size_t k = i; k < j; ++k) { 218 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage(); 219 std::string Name = Globals[k]->getName(); 220 221 Constant *Idx[2] = { 222 ConstantInt::get(Int32Ty, 0), 223 ConstantInt::get(Int32Ty, k-i) 224 }; 225 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx); 226 Globals[k]->replaceAllUsesWith(GEP); 227 Globals[k]->eraseFromParent(); 228 229 if (Linkage != GlobalValue::InternalLinkage) { 230 // Generate a new alias... 231 auto *PTy = cast<PointerType>(GEP->getType()); 232 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 233 Linkage, Name, GEP, &M); 234 } 235 236 NumMerged++; 237 } 238 i = j; 239 } 240 241 return true; 242 } 243 244 void GlobalMerge::collectUsedGlobalVariables(Module &M) { 245 // Extract global variables from llvm.used array 246 const GlobalVariable *GV = M.getGlobalVariable("llvm.used"); 247 if (!GV || !GV->hasInitializer()) return; 248 249 // Should be an array of 'i8*'. 250 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer()); 251 252 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 253 if (const GlobalVariable *G = 254 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts())) 255 MustKeepGlobalVariables.insert(G); 256 } 257 258 void GlobalMerge::setMustKeepGlobalVariables(Module &M) { 259 collectUsedGlobalVariables(M); 260 261 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn; 262 ++IFn) { 263 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end(); 264 IBB != IEndBB; ++IBB) { 265 // Follow the invoke link to find the landing pad instruction 266 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator()); 267 if (!II) continue; 268 269 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst(); 270 // Look for globals in the clauses of the landing pad instruction 271 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses(); 272 Idx != NumClauses; ++Idx) 273 if (const GlobalVariable *GV = 274 dyn_cast<GlobalVariable>(LPInst->getClause(Idx) 275 ->stripPointerCasts())) 276 MustKeepGlobalVariables.insert(GV); 277 } 278 } 279 } 280 281 bool GlobalMerge::doInitialization(Module &M) { 282 if (!EnableGlobalMerge) 283 return false; 284 285 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals, 286 BSSGlobals; 287 bool Changed = false; 288 setMustKeepGlobalVariables(M); 289 290 // Grab all non-const globals. 291 for (Module::global_iterator I = M.global_begin(), 292 E = M.global_end(); I != E; ++I) { 293 // Merge is safe for "normal" internal or external globals only 294 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection()) 295 continue; 296 297 if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) && 298 !I->hasInternalLinkage()) 299 continue; 300 301 PointerType *PT = dyn_cast<PointerType>(I->getType()); 302 assert(PT && "Global variable is not a pointer!"); 303 304 unsigned AddressSpace = PT->getAddressSpace(); 305 306 // Ignore fancy-aligned globals for now. 307 unsigned Alignment = DL->getPreferredAlignment(I); 308 Type *Ty = I->getType()->getElementType(); 309 if (Alignment > DL->getABITypeAlignment(Ty)) 310 continue; 311 312 // Ignore all 'special' globals. 313 if (I->getName().startswith("llvm.") || 314 I->getName().startswith(".llvm.")) 315 continue; 316 317 // Ignore all "required" globals: 318 if (isMustKeepGlobalVariable(I)) 319 continue; 320 321 if (DL->getTypeAllocSize(Ty) < MaxOffset) { 322 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal()) 323 BSSGlobals[AddressSpace].push_back(I); 324 else if (I->isConstant()) 325 ConstGlobals[AddressSpace].push_back(I); 326 else 327 Globals[AddressSpace].push_back(I); 328 } 329 } 330 331 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator 332 I = Globals.begin(), E = Globals.end(); I != E; ++I) 333 if (I->second.size() > 1) 334 Changed |= doMerge(I->second, M, false, I->first); 335 336 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator 337 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I) 338 if (I->second.size() > 1) 339 Changed |= doMerge(I->second, M, false, I->first); 340 341 if (EnableGlobalMergeOnConst) 342 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator 343 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I) 344 if (I->second.size() > 1) 345 Changed |= doMerge(I->second, M, true, I->first); 346 347 return Changed; 348 } 349 350 bool GlobalMerge::runOnFunction(Function &F) { 351 return false; 352 } 353 354 bool GlobalMerge::doFinalization(Module &M) { 355 MustKeepGlobalVariables.clear(); 356 return false; 357 } 358 359 Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset) { 360 return new GlobalMerge(TM, Offset); 361 } 362