1 //===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
13 // the program, regardless of whether or not an existing string is available.
15 // Algorithm: ConstantMerge is designed to build up a map of available constants
16 // and eliminate duplicates when it is initialized.
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Transforms/IPO/ConstantMerge.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/PointerIntPair.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Transforms/IPO.h"
34 #define DEBUG_TYPE "constmerge"
36 STATISTIC(NumMerged, "Number of global constants merged");
38 /// Find values that are marked as llvm.used.
39 static void FindUsedValues(GlobalVariable *LLVMUsed,
40 SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
41 if (!LLVMUsed) return;
42 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
44 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);
51 // True if A is better than B.
52 static bool IsBetterCanonical(const GlobalVariable &A,
53 const GlobalVariable &B) {
54 if (!A.hasLocalLinkage() && B.hasLocalLinkage())
57 if (A.hasLocalLinkage() && !B.hasLocalLinkage())
60 return A.hasGlobalUnnamedAddr();
63 static 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)
72 static void copyDebugLocMetadata(const GlobalVariable *From,
74 SmallVector<DIGlobalVariableExpression *, 1> MDs;
75 From->getDebugInfo(MDs);
80 static unsigned getAlignment(GlobalVariable *GV) {
81 unsigned Align = GV->getAlignment();
84 return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
87 static bool mergeConstants(Module &M) {
88 // 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);
93 // Map unique constants to globals.
94 DenseMap<Constant *, GlobalVariable *> CMap;
96 // Replacements - This vector contains a list of replacements to perform.
97 SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
99 bool MadeChange = false;
101 // 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
107 // First: Find the canonical constants others will be merged with.
108 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
110 GlobalVariable *GV = &*GVI++;
112 // If this GV is dead, remove it.
113 GV->removeDeadConstantUsers();
114 if (GV->use_empty() && GV->hasLocalLinkage()) {
115 GV->eraseFromParent();
119 // Only process constants with initializers in the default address space.
120 if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
121 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
122 // Don't touch values marked with attribute(used).
123 UsedGlobals.count(GV))
126 // 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())
133 // Don't touch globals with metadata other then !dbg.
134 if (hasMetadataOtherThanDebugLoc(GV))
137 Constant *Init = GV->getInitializer();
139 // Check to see if the initializer is already known.
140 GlobalVariable *&Slot = CMap[Init];
142 // 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
144 // it cannot be replace, but can be the canonical constant we merge with.
145 if (!Slot || IsBetterCanonical(*GV, *Slot))
149 // 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.
153 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
155 GlobalVariable *GV = &*GVI++;
157 // Only process constants with initializers in the default address space.
158 if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
159 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
160 // Don't touch values marked with attribute(used).
161 UsedGlobals.count(GV))
164 // We can only replace constant with local linkage.
165 if (!GV->hasLocalLinkage())
168 Constant *Init = GV->getInitializer();
170 // Check to see if the initializer is already known.
171 GlobalVariable *Slot = CMap[Init];
173 if (!Slot || Slot == GV)
176 if (!Slot->hasGlobalUnnamedAddr() && !GV->hasGlobalUnnamedAddr())
179 if (hasMetadataOtherThanDebugLoc(GV))
182 if (!GV->hasGlobalUnnamedAddr())
183 Slot->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
185 // Make all uses of the duplicate constant use the canonical version.
186 Replacements.push_back(std::make_pair(GV, Slot));
189 if (Replacements.empty())
193 // 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
196 for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
197 // Bump the alignment if necessary.
198 if (Replacements[i].first->getAlignment() ||
199 Replacements[i].second->getAlignment()) {
200 Replacements[i].second->setAlignment(
201 std::max(getAlignment(Replacements[i].first),
202 getAlignment(Replacements[i].second)));
205 copyDebugLocMetadata(Replacements[i].first, Replacements[i].second);
207 // Eliminate any uses of the dead global.
208 Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
210 // Delete the global value from the module.
211 assert(Replacements[i].first->hasLocalLinkage() &&
212 "Refusing to delete an externally visible global variable.");
213 Replacements[i].first->eraseFromParent();
216 NumMerged += Replacements.size();
217 Replacements.clear();
221 PreservedAnalyses ConstantMergePass::run(Module &M, ModuleAnalysisManager &) {
222 if (!mergeConstants(M))
223 return PreservedAnalyses::all();
224 return PreservedAnalyses::none();
228 struct ConstantMergeLegacyPass : public ModulePass {
229 static char ID; // Pass identification, replacement for typeid
230 ConstantMergeLegacyPass() : ModulePass(ID) {
231 initializeConstantMergeLegacyPassPass(*PassRegistry::getPassRegistry());
234 // For this pass, process all of the globals in the module, eliminating
235 // duplicate constants.
236 bool runOnModule(Module &M) {
239 return mergeConstants(M);
244 char ConstantMergeLegacyPass::ID = 0;
245 INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
246 "Merge Duplicate Global Constants", false, false)
248 ModulePass *llvm::createConstantMergePass() {
249 return new ConstantMergeLegacyPass();