blob: 62b5a9c9ba26614c0c5d25acb7bc19dccac84bdd [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//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4816d632001-10-18 20:05:37 +00009//
10// This file defines the interface to a pass that merges duplicate global
11// constants together into a single constant that is shared. This is useful
12// because some passes (ie TraceValues) insert a lot of string constants into
Chris Lattner28d10352002-09-23 23:00:46 +000013// the program, regardless of whether or not an existing string is available.
Chris Lattner4816d632001-10-18 20:05:37 +000014//
15// Algorithm: ConstantMerge is designed to build up a map of available constants
Chris Lattner28d10352002-09-23 23:00:46 +000016// and eliminate duplicates when it is initialized.
Chris Lattner4816d632001-10-18 20:05:37 +000017//
18//===----------------------------------------------------------------------===//
19
Davide Italiano164b9bc2016-05-05 00:51:09 +000020#include "llvm/Transforms/IPO/ConstantMerge.h"
Chris Lattner75879be2010-02-12 18:17:23 +000021#include "llvm/ADT/DenseMap.h"
Nick Lewycky8ac9ece2011-07-27 19:47:34 +000022#include "llvm/ADT/PointerIntPair.h"
Chris Lattner67e53452010-09-15 00:30:11 +000023#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000024#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Module.h"
Rafael Espindolac229a4f2013-05-06 01:48:55 +000029#include "llvm/IR/Operator.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Pass.h"
Davide Italiano164b9bc2016-05-05 00:51:09 +000031#include "llvm/Transforms/IPO.h"
Chris Lattnerf52e03c2003-11-21 21:54:22 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chandler Carruth964daaa2014-04-22 02:55:47 +000034#define DEBUG_TYPE "constmerge"
35
Chris Lattner1631bcb2006-12-19 22:09:18 +000036STATISTIC(NumMerged, "Number of global constants merged");
Chris Lattnereac4dcd2002-10-09 23:16:04 +000037
Chris Lattner67e53452010-09-15 00:30:11 +000038/// Find values that are marked as llvm.used.
39static void FindUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +000040 SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
Craig Topperf40110f2014-04-25 05:29:35 +000041 if (!LLVMUsed) return;
Rafael Espindola74f2e462013-04-22 14:58:02 +000042 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
43
Rafael Espindolac229a4f2013-05-06 01:48:55 +000044 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
45 Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
46 GlobalValue *GV = cast<GlobalValue>(Operand);
47 UsedValues.insert(GV);
48 }
Chris Lattner67e53452010-09-15 00:30:11 +000049}
50
Rafael Espindola751677a2011-01-16 17:05:09 +000051// True if A is better than B.
Alp Tokercb402912014-01-24 17:20:08 +000052static bool IsBetterCanonical(const GlobalVariable &A,
53 const GlobalVariable &B) {
Rafael Espindola751677a2011-01-16 17:05:09 +000054 if (!A.hasLocalLinkage() && B.hasLocalLinkage())
55 return true;
56
57 if (A.hasLocalLinkage() && !B.hasLocalLinkage())
58 return false;
59
Peter Collingbourne96efdd62016-06-14 21:01:22 +000060 return A.hasGlobalUnnamedAddr();
Rafael Espindola751677a2011-01-16 17:05:09 +000061}
62
Evgeniy Stepanov8537d992017-03-09 00:03:37 +000063static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV) {
64 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
65 GV->getAllMetadata(MDs);
66 for (const auto &V : MDs)
67 if (V.first != LLVMContext::MD_dbg)
68 return true;
69 return false;
70}
71
72static void copyDebugLocMetadata(const GlobalVariable *From,
73 GlobalVariable *To) {
74 SmallVector<DIGlobalVariableExpression *, 1> MDs;
75 From->getDebugInfo(MDs);
76 for (auto MD : MDs)
77 To->addDebugInfo(MD);
78}
79
Davide Italiano17da1742016-05-04 03:21:20 +000080static unsigned getAlignment(GlobalVariable *GV) {
Rafael Espindoladd8757a2013-11-12 20:21:43 +000081 unsigned Align = GV->getAlignment();
82 if (Align)
83 return Align;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000084 return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
Nick Lewycky8ac9ece2011-07-27 19:47:34 +000085}
86
Davide Italiano164b9bc2016-05-05 00:51:09 +000087static bool mergeConstants(Module &M) {
Chris Lattner67e53452010-09-15 00:30:11 +000088 // Find all the globals that are marked "used". These cannot be merged.
89 SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
90 FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
91 FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
Mehdi Aminia28d91d2015-03-10 02:37:25 +000092
93 // Map unique constants to globals.
94 DenseMap<Constant *, GlobalVariable *> CMap;
Chris Lattnerc2ee0542003-12-22 23:49:36 +000095
96 // Replacements - This vector contains a list of replacements to perform.
Chris Lattner75879be2010-02-12 18:17:23 +000097 SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
Chris Lattnerc2ee0542003-12-22 23:49:36 +000098
Chris Lattner56db5e92003-12-28 07:19:08 +000099 bool MadeChange = false;
Chris Lattner4816d632001-10-18 20:05:37 +0000100
Chris Lattner56db5e92003-12-28 07:19:08 +0000101 // Iterate constant merging while we are still making progress. Merging two
102 // constants together may allow us to merge other constants together if the
103 // second level constants have initializers which point to the globals that
104 // were just merged.
105 while (1) {
Rafael Espindola751677a2011-01-16 17:05:09 +0000106
107 // First: Find the canonical constants others will be merged with.
Chris Lattner6f588392007-04-14 18:06:52 +0000108 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
109 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000110 GlobalVariable *GV = &*GVI++;
Rafael Espindola751677a2011-01-16 17:05:09 +0000111
Chris Lattner02137ee2007-04-14 01:11:54 +0000112 // If this GV is dead, remove it.
113 GV->removeDeadConstantUsers();
Rafael Espindola6de96a12009-01-15 20:18:42 +0000114 if (GV->use_empty() && GV->hasLocalLinkage()) {
Jeff Cohen4bd0fd32007-04-14 17:18:29 +0000115 GV->eraseFromParent();
116 continue;
Chris Lattner02137ee2007-04-14 01:11:54 +0000117 }
Rafael Espindola751677a2011-01-16 17:05:09 +0000118
Nick Lewycky0296a482011-01-15 18:14:21 +0000119 // Only process constants with initializers in the default address space.
Nick Lewycky4a1ff162011-01-15 18:42:52 +0000120 if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Nick Lewycky0296a482011-01-15 18:14:21 +0000121 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
Chris Lattner67e53452010-09-15 00:30:11 +0000122 // Don't touch values marked with attribute(used).
123 UsedGlobals.count(GV))
Chris Lattner75879be2010-02-12 18:17:23 +0000124 continue;
Rafael Espindola751677a2011-01-16 17:05:09 +0000125
Eli Friedmanb31c6272012-01-11 22:06:46 +0000126 // This transformation is legal for weak ODR globals in the sense it
127 // doesn't change semantics, but we really don't want to perform it
128 // anyway; it's likely to pessimize code generation, and some tools
129 // (like the Darwin linker in cases involving CFString) don't expect it.
130 if (GV->isWeakForLinker())
Bill Wendlingc7915512012-01-11 00:13:08 +0000131 continue;
132
Evgeniy Stepanov8537d992017-03-09 00:03:37 +0000133 // Don't touch globals with metadata other then !dbg.
134 if (hasMetadataOtherThanDebugLoc(GV))
135 continue;
136
Chris Lattner75879be2010-02-12 18:17:23 +0000137 Constant *Init = GV->getInitializer();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000138
Chris Lattner75879be2010-02-12 18:17:23 +0000139 // Check to see if the initializer is already known.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 GlobalVariable *&Slot = CMap[Init];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000141
Bill Wendlingc7915512012-01-11 00:13:08 +0000142 // If this is the first constant we find or if the old one is local,
143 // replace with the current one. If the current is externally visible
Rafael Espindola751677a2011-01-16 17:05:09 +0000144 // it cannot be replace, but can be the canonical constant we merge with.
Craig Topperf40110f2014-04-25 05:29:35 +0000145 if (!Slot || IsBetterCanonical(*GV, *Slot))
Chris Lattner75879be2010-02-12 18:17:23 +0000146 Slot = GV;
Nick Lewycky0296a482011-01-15 18:14:21 +0000147 }
148
Rafael Espindola751677a2011-01-16 17:05:09 +0000149 // Second: identify all globals that can be merged together, filling in
150 // the Replacements vector. We cannot do the replacement in this pass
151 // because doing so may cause initializers of other globals to be rewritten,
152 // invalidating the Constant* pointers in CMap.
Nick Lewycky0296a482011-01-15 18:14:21 +0000153 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
154 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000155 GlobalVariable *GV = &*GVI++;
Nick Lewycky0296a482011-01-15 18:14:21 +0000156
157 // Only process constants with initializers in the default address space.
Nick Lewycky4a1ff162011-01-15 18:42:52 +0000158 if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Nick Lewycky0296a482011-01-15 18:14:21 +0000159 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
160 // Don't touch values marked with attribute(used).
161 UsedGlobals.count(GV))
162 continue;
163
Eli Friedmanb31c6272012-01-11 22:06:46 +0000164 // We can only replace constant with local linkage.
165 if (!GV->hasLocalLinkage())
Nick Lewycky0296a482011-01-15 18:14:21 +0000166 continue;
167
168 Constant *Init = GV->getInitializer();
169
170 // Check to see if the initializer is already known.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171 GlobalVariable *Slot = CMap[Init];
Nick Lewycky0296a482011-01-15 18:14:21 +0000172
Rafael Espindola751677a2011-01-16 17:05:09 +0000173 if (!Slot || Slot == GV)
174 continue;
175
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000176 if (!Slot->hasGlobalUnnamedAddr() && !GV->hasGlobalUnnamedAddr())
Rafael Espindola751677a2011-01-16 17:05:09 +0000177 continue;
178
Evgeniy Stepanov8537d992017-03-09 00:03:37 +0000179 if (hasMetadataOtherThanDebugLoc(GV))
180 continue;
181
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000182 if (!GV->hasGlobalUnnamedAddr())
183 Slot->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Rafael Espindola751677a2011-01-16 17:05:09 +0000184
185 // Make all uses of the duplicate constant use the canonical version.
186 Replacements.push_back(std::make_pair(GV, Slot));
Chris Lattner02137ee2007-04-14 01:11:54 +0000187 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000188
Chris Lattner56db5e92003-12-28 07:19:08 +0000189 if (Replacements.empty())
190 return MadeChange;
191 CMap.clear();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000192
Chris Lattner56db5e92003-12-28 07:19:08 +0000193 // Now that we have figured out which replacements must be made, do them all
194 // now. This avoid invalidating the pointers in CMap, which are unneeded
195 // now.
196 for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
Nick Lewycky8ac9ece2011-07-27 19:47:34 +0000197 // Bump the alignment if necessary.
198 if (Replacements[i].first->getAlignment() ||
199 Replacements[i].second->getAlignment()) {
Rafael Espindoladd8757a2013-11-12 20:21:43 +0000200 Replacements[i].second->setAlignment(
201 std::max(getAlignment(Replacements[i].first),
202 getAlignment(Replacements[i].second)));
Nick Lewycky8ac9ece2011-07-27 19:47:34 +0000203 }
204
Evgeniy Stepanov8537d992017-03-09 00:03:37 +0000205 copyDebugLocMetadata(Replacements[i].first, Replacements[i].second);
206
Chris Lattner75879be2010-02-12 18:17:23 +0000207 // Eliminate any uses of the dead global.
Chris Lattner56db5e92003-12-28 07:19:08 +0000208 Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000209
Chris Lattner75879be2010-02-12 18:17:23 +0000210 // Delete the global value from the module.
Nick Lewycky0296a482011-01-15 18:14:21 +0000211 assert(Replacements[i].first->hasLocalLinkage() &&
212 "Refusing to delete an externally visible global variable.");
Chris Lattner75879be2010-02-12 18:17:23 +0000213 Replacements[i].first->eraseFromParent();
Chris Lattner56db5e92003-12-28 07:19:08 +0000214 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000215
Chris Lattner56db5e92003-12-28 07:19:08 +0000216 NumMerged += Replacements.size();
217 Replacements.clear();
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000218 }
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000219}
Davide Italiano164b9bc2016-05-05 00:51:09 +0000220
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000221PreservedAnalyses ConstantMergePass::run(Module &M, ModuleAnalysisManager &) {
Davide Italiano164b9bc2016-05-05 00:51:09 +0000222 if (!mergeConstants(M))
223 return PreservedAnalyses::all();
224 return PreservedAnalyses::none();
225}
226
227namespace {
228struct ConstantMergeLegacyPass : public ModulePass {
229 static char ID; // Pass identification, replacement for typeid
230 ConstantMergeLegacyPass() : ModulePass(ID) {
231 initializeConstantMergeLegacyPassPass(*PassRegistry::getPassRegistry());
232 }
233
234 // For this pass, process all of the globals in the module, eliminating
235 // duplicate constants.
236 bool runOnModule(Module &M) {
237 if (skipModule(M))
238 return false;
239 return mergeConstants(M);
240 }
241};
242}
243
244char ConstantMergeLegacyPass::ID = 0;
245INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
246 "Merge Duplicate Global Constants", false, false)
247
248ModulePass *llvm::createConstantMergePass() {
249 return new ConstantMergeLegacyPass();
250}