blob: ad877ae1786c9cf890d21da444848ce62fbac791 [file] [log] [blame]
Chris Lattner424132a2003-04-18 04:34:29 +00001//===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner4816d632001-10-18 20:05:37 +00008//
9// This file defines the interface to a pass that merges duplicate global
10// constants together into a single constant that is shared. This is useful
11// because some passes (ie TraceValues) insert a lot of string constants into
Chris Lattner28d10352002-09-23 23:00:46 +000012// the program, regardless of whether or not an existing string is available.
Chris Lattner4816d632001-10-18 20:05:37 +000013//
14// Algorithm: ConstantMerge is designed to build up a map of available constants
Chris Lattner28d10352002-09-23 23:00:46 +000015// and eliminate duplicates when it is initialized.
Chris Lattner4816d632001-10-18 20:05:37 +000016//
17//===----------------------------------------------------------------------===//
18
Davide Italiano164b9bc2016-05-05 00:51:09 +000019#include "llvm/Transforms/IPO/ConstantMerge.h"
Chris Lattner75879be2010-02-12 18:17:23 +000020#include "llvm/ADT/DenseMap.h"
Chris Lattner67e53452010-09-15 00:30:11 +000021#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000022#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000023#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000027#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Pass.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000032#include "llvm/Support/Casting.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000033#include "llvm/Transforms/IPO.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000034#include <algorithm>
35#include <cassert>
36#include <utility>
37
Chris Lattnerf52e03c2003-11-21 21:54:22 +000038using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000039
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "constmerge"
41
JF Bastienfe258d92018-08-10 22:41:09 +000042STATISTIC(NumIdenticalMerged, "Number of identical global constants merged");
Chris Lattnereac4dcd2002-10-09 23:16:04 +000043
Chris Lattner67e53452010-09-15 00:30:11 +000044/// Find values that are marked as llvm.used.
45static void FindUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +000046 SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
Craig Topperf40110f2014-04-25 05:29:35 +000047 if (!LLVMUsed) return;
Rafael Espindola74f2e462013-04-22 14:58:02 +000048 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
49
Rafael Espindolac229a4f2013-05-06 01:48:55 +000050 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
51 Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
52 GlobalValue *GV = cast<GlobalValue>(Operand);
53 UsedValues.insert(GV);
54 }
Chris Lattner67e53452010-09-15 00:30:11 +000055}
56
Rafael Espindola751677a2011-01-16 17:05:09 +000057// True if A is better than B.
Alp Tokercb402912014-01-24 17:20:08 +000058static bool IsBetterCanonical(const GlobalVariable &A,
59 const GlobalVariable &B) {
Rafael Espindola751677a2011-01-16 17:05:09 +000060 if (!A.hasLocalLinkage() && B.hasLocalLinkage())
61 return true;
62
63 if (A.hasLocalLinkage() && !B.hasLocalLinkage())
64 return false;
65
Peter Collingbourne96efdd62016-06-14 21:01:22 +000066 return A.hasGlobalUnnamedAddr();
Rafael Espindola751677a2011-01-16 17:05:09 +000067}
68
Evgeniy Stepanov8537d992017-03-09 00:03:37 +000069static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV) {
70 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
71 GV->getAllMetadata(MDs);
72 for (const auto &V : MDs)
73 if (V.first != LLVMContext::MD_dbg)
74 return true;
75 return false;
76}
77
78static void copyDebugLocMetadata(const GlobalVariable *From,
79 GlobalVariable *To) {
80 SmallVector<DIGlobalVariableExpression *, 1> MDs;
81 From->getDebugInfo(MDs);
82 for (auto MD : MDs)
83 To->addDebugInfo(MD);
84}
85
Davide Italiano17da1742016-05-04 03:21:20 +000086static unsigned getAlignment(GlobalVariable *GV) {
Rafael Espindoladd8757a2013-11-12 20:21:43 +000087 unsigned Align = GV->getAlignment();
88 if (Align)
89 return Align;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000090 return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
Nick Lewycky8ac9ece2011-07-27 19:47:34 +000091}
92
Vedant Kumar857cacd2019-01-20 02:44:43 +000093static bool
94isUnmergeableGlobal(GlobalVariable *GV,
95 const SmallPtrSetImpl<const GlobalValue *> &UsedGlobals) {
96 // Only process constants with initializers in the default address space.
97 return !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
98 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
99 // Don't touch values marked with attribute(used).
100 UsedGlobals.count(GV);
101}
102
JF Bastien42ca9cc2018-08-09 21:56:09 +0000103enum class CanMerge { No, Yes };
104static CanMerge makeMergeable(GlobalVariable *Old, GlobalVariable *New) {
105 if (!Old->hasGlobalUnnamedAddr() && !New->hasGlobalUnnamedAddr())
106 return CanMerge::No;
107 if (hasMetadataOtherThanDebugLoc(Old))
108 return CanMerge::No;
109 assert(!hasMetadataOtherThanDebugLoc(New));
110 if (!Old->hasGlobalUnnamedAddr())
111 New->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
112 return CanMerge::Yes;
113}
114
115static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New) {
116 Constant *NewConstant = New;
117
118 LLVM_DEBUG(dbgs() << "Replacing global: @" << Old->getName() << " -> @"
119 << New->getName() << "\n");
120
121 // Bump the alignment if necessary.
122 if (Old->getAlignment() || New->getAlignment())
123 New->setAlignment(std::max(getAlignment(Old), getAlignment(New)));
124
125 copyDebugLocMetadata(Old, New);
126 Old->replaceAllUsesWith(NewConstant);
127
128 // Delete the global value from the module.
129 assert(Old->hasLocalLinkage() &&
130 "Refusing to delete an externally visible global variable.");
131 Old->eraseFromParent();
132}
133
Davide Italiano164b9bc2016-05-05 00:51:09 +0000134static bool mergeConstants(Module &M) {
Chris Lattner67e53452010-09-15 00:30:11 +0000135 // Find all the globals that are marked "used". These cannot be merged.
136 SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
137 FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
138 FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000139
140 // Map unique constants to globals.
141 DenseMap<Constant *, GlobalVariable *> CMap;
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000142
JF Bastienfe258d92018-08-10 22:41:09 +0000143 SmallVector<std::pair<GlobalVariable *, GlobalVariable *>, 32>
144 SameContentReplacements;
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000145
JF Bastienfe258d92018-08-10 22:41:09 +0000146 size_t ChangesMade = 0;
147 size_t OldChangesMade = 0;
Chris Lattner4816d632001-10-18 20:05:37 +0000148
Chris Lattner56db5e92003-12-28 07:19:08 +0000149 // Iterate constant merging while we are still making progress. Merging two
150 // constants together may allow us to merge other constants together if the
151 // second level constants have initializers which point to the globals that
152 // were just merged.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000153 while (true) {
JF Bastienfe258d92018-08-10 22:41:09 +0000154 // Find the canonical constants others will be merged with.
Chris Lattner6f588392007-04-14 18:06:52 +0000155 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
156 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000157 GlobalVariable *GV = &*GVI++;
Rafael Espindola751677a2011-01-16 17:05:09 +0000158
Chris Lattner02137ee2007-04-14 01:11:54 +0000159 // If this GV is dead, remove it.
160 GV->removeDeadConstantUsers();
Rafael Espindola6de96a12009-01-15 20:18:42 +0000161 if (GV->use_empty() && GV->hasLocalLinkage()) {
Jeff Cohen4bd0fd32007-04-14 17:18:29 +0000162 GV->eraseFromParent();
JF Bastienfe258d92018-08-10 22:41:09 +0000163 ++ChangesMade;
Jeff Cohen4bd0fd32007-04-14 17:18:29 +0000164 continue;
Chris Lattner02137ee2007-04-14 01:11:54 +0000165 }
Rafael Espindola751677a2011-01-16 17:05:09 +0000166
Vedant Kumar857cacd2019-01-20 02:44:43 +0000167 if (isUnmergeableGlobal(GV, UsedGlobals))
Chris Lattner75879be2010-02-12 18:17:23 +0000168 continue;
Rafael Espindola751677a2011-01-16 17:05:09 +0000169
Eli Friedmanb31c6272012-01-11 22:06:46 +0000170 // This transformation is legal for weak ODR globals in the sense it
171 // doesn't change semantics, but we really don't want to perform it
172 // anyway; it's likely to pessimize code generation, and some tools
173 // (like the Darwin linker in cases involving CFString) don't expect it.
174 if (GV->isWeakForLinker())
Bill Wendlingc7915512012-01-11 00:13:08 +0000175 continue;
176
Evgeniy Stepanov8537d992017-03-09 00:03:37 +0000177 // Don't touch globals with metadata other then !dbg.
178 if (hasMetadataOtherThanDebugLoc(GV))
179 continue;
180
JF Bastienb99f1312018-08-10 22:10:20 +0000181 Constant *Init = GV->getInitializer();
182
Chris Lattner75879be2010-02-12 18:17:23 +0000183 // Check to see if the initializer is already known.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000184 GlobalVariable *&Slot = CMap[Init];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000185
Bill Wendlingc7915512012-01-11 00:13:08 +0000186 // If this is the first constant we find or if the old one is local,
187 // replace with the current one. If the current is externally visible
Rafael Espindola751677a2011-01-16 17:05:09 +0000188 // it cannot be replace, but can be the canonical constant we merge with.
JF Bastien42ca9cc2018-08-09 21:56:09 +0000189 bool FirstConstantFound = !Slot;
190 if (FirstConstantFound || IsBetterCanonical(*GV, *Slot)) {
Chris Lattner75879be2010-02-12 18:17:23 +0000191 Slot = GV;
JF Bastien42ca9cc2018-08-09 21:56:09 +0000192 LLVM_DEBUG(dbgs() << "Cmap[" << *Init << "] = " << GV->getName()
193 << (FirstConstantFound ? "\n" : " (updated)\n"));
194 }
Nick Lewycky0296a482011-01-15 18:14:21 +0000195 }
196
JF Bastienfe258d92018-08-10 22:41:09 +0000197 // Identify all globals that can be merged together, filling in the
198 // SameContentReplacements vector. We cannot do the replacement in this pass
Rafael Espindola751677a2011-01-16 17:05:09 +0000199 // because doing so may cause initializers of other globals to be rewritten,
200 // invalidating the Constant* pointers in CMap.
Nick Lewycky0296a482011-01-15 18:14:21 +0000201 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
202 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000203 GlobalVariable *GV = &*GVI++;
Nick Lewycky0296a482011-01-15 18:14:21 +0000204
Vedant Kumar857cacd2019-01-20 02:44:43 +0000205 if (isUnmergeableGlobal(GV, UsedGlobals))
Nick Lewycky0296a482011-01-15 18:14:21 +0000206 continue;
207
Eli Friedmanb31c6272012-01-11 22:06:46 +0000208 // We can only replace constant with local linkage.
209 if (!GV->hasLocalLinkage())
Nick Lewycky0296a482011-01-15 18:14:21 +0000210 continue;
211
JF Bastienb99f1312018-08-10 22:10:20 +0000212 Constant *Init = GV->getInitializer();
213
Nick Lewycky0296a482011-01-15 18:14:21 +0000214 // Check to see if the initializer is already known.
JF Bastien3f270332018-08-09 04:17:48 +0000215 auto Found = CMap.find(Init);
216 if (Found == CMap.end())
217 continue;
Nick Lewycky0296a482011-01-15 18:14:21 +0000218
JF Bastien3f270332018-08-09 04:17:48 +0000219 GlobalVariable *Slot = Found->second;
220 if (Slot == GV)
Rafael Espindola751677a2011-01-16 17:05:09 +0000221 continue;
222
JF Bastien42ca9cc2018-08-09 21:56:09 +0000223 if (makeMergeable(GV, Slot) == CanMerge::No)
Rafael Espindola751677a2011-01-16 17:05:09 +0000224 continue;
225
Rafael Espindola751677a2011-01-16 17:05:09 +0000226 // Make all uses of the duplicate constant use the canonical version.
JF Bastien42ca9cc2018-08-09 21:56:09 +0000227 LLVM_DEBUG(dbgs() << "Will replace: @" << GV->getName() << " -> @"
228 << Slot->getName() << "\n");
JF Bastienfe258d92018-08-10 22:41:09 +0000229 SameContentReplacements.push_back(std::make_pair(GV, Slot));
Chris Lattner02137ee2007-04-14 01:11:54 +0000230 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000231
Chris Lattner56db5e92003-12-28 07:19:08 +0000232 // Now that we have figured out which replacements must be made, do them all
233 // now. This avoid invalidating the pointers in CMap, which are unneeded
234 // now.
JF Bastienfe258d92018-08-10 22:41:09 +0000235 for (unsigned i = 0, e = SameContentReplacements.size(); i != e; ++i) {
236 GlobalVariable *Old = SameContentReplacements[i].first;
237 GlobalVariable *New = SameContentReplacements[i].second;
JF Bastien42ca9cc2018-08-09 21:56:09 +0000238 replace(M, Old, New);
JF Bastienfe258d92018-08-10 22:41:09 +0000239 ++ChangesMade;
240 ++NumIdenticalMerged;
Chris Lattner56db5e92003-12-28 07:19:08 +0000241 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000242
JF Bastienfe258d92018-08-10 22:41:09 +0000243 if (ChangesMade == OldChangesMade)
244 break;
245 OldChangesMade = ChangesMade;
246
247 SameContentReplacements.clear();
248 CMap.clear();
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000249 }
JF Bastienfe258d92018-08-10 22:41:09 +0000250
251 return ChangesMade;
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000252}
Davide Italiano164b9bc2016-05-05 00:51:09 +0000253
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000254PreservedAnalyses ConstantMergePass::run(Module &M, ModuleAnalysisManager &) {
Davide Italiano164b9bc2016-05-05 00:51:09 +0000255 if (!mergeConstants(M))
256 return PreservedAnalyses::all();
257 return PreservedAnalyses::none();
258}
259
260namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000261
Davide Italiano164b9bc2016-05-05 00:51:09 +0000262struct ConstantMergeLegacyPass : public ModulePass {
263 static char ID; // Pass identification, replacement for typeid
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000264
Davide Italiano164b9bc2016-05-05 00:51:09 +0000265 ConstantMergeLegacyPass() : ModulePass(ID) {
266 initializeConstantMergeLegacyPassPass(*PassRegistry::getPassRegistry());
267 }
268
269 // For this pass, process all of the globals in the module, eliminating
270 // duplicate constants.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000271 bool runOnModule(Module &M) override {
Davide Italiano164b9bc2016-05-05 00:51:09 +0000272 if (skipModule(M))
273 return false;
274 return mergeConstants(M);
275 }
276};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000277
278} // end anonymous namespace
Davide Italiano164b9bc2016-05-05 00:51:09 +0000279
280char ConstantMergeLegacyPass::ID = 0;
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000281
Davide Italiano164b9bc2016-05-05 00:51:09 +0000282INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
283 "Merge Duplicate Global Constants", false, false)
284
285ModulePass *llvm::createConstantMergePass() {
286 return new ConstantMergeLegacyPass();
287}