blob: 65b042534f39a91849dd62a999242cfcfb7e2c3f [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
Davide Italiano17da1742016-05-04 03:21:20 +000063static unsigned getAlignment(GlobalVariable *GV) {
Rafael Espindoladd8757a2013-11-12 20:21:43 +000064 unsigned Align = GV->getAlignment();
65 if (Align)
66 return Align;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000067 return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
Nick Lewycky8ac9ece2011-07-27 19:47:34 +000068}
69
Davide Italiano164b9bc2016-05-05 00:51:09 +000070static bool mergeConstants(Module &M) {
Chris Lattner67e53452010-09-15 00:30:11 +000071 // Find all the globals that are marked "used". These cannot be merged.
72 SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
73 FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
74 FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
Mehdi Aminia28d91d2015-03-10 02:37:25 +000075
76 // Map unique constants to globals.
77 DenseMap<Constant *, GlobalVariable *> CMap;
Chris Lattnerc2ee0542003-12-22 23:49:36 +000078
79 // Replacements - This vector contains a list of replacements to perform.
Chris Lattner75879be2010-02-12 18:17:23 +000080 SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
Chris Lattnerc2ee0542003-12-22 23:49:36 +000081
Chris Lattner56db5e92003-12-28 07:19:08 +000082 bool MadeChange = false;
Chris Lattner4816d632001-10-18 20:05:37 +000083
Chris Lattner56db5e92003-12-28 07:19:08 +000084 // Iterate constant merging while we are still making progress. Merging two
85 // constants together may allow us to merge other constants together if the
86 // second level constants have initializers which point to the globals that
87 // were just merged.
88 while (1) {
Rafael Espindola751677a2011-01-16 17:05:09 +000089
90 // First: Find the canonical constants others will be merged with.
Chris Lattner6f588392007-04-14 18:06:52 +000091 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
92 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +000093 GlobalVariable *GV = &*GVI++;
Rafael Espindola751677a2011-01-16 17:05:09 +000094
Chris Lattner02137ee2007-04-14 01:11:54 +000095 // If this GV is dead, remove it.
96 GV->removeDeadConstantUsers();
Rafael Espindola6de96a12009-01-15 20:18:42 +000097 if (GV->use_empty() && GV->hasLocalLinkage()) {
Jeff Cohen4bd0fd32007-04-14 17:18:29 +000098 GV->eraseFromParent();
99 continue;
Chris Lattner02137ee2007-04-14 01:11:54 +0000100 }
Rafael Espindola751677a2011-01-16 17:05:09 +0000101
Nick Lewycky0296a482011-01-15 18:14:21 +0000102 // Only process constants with initializers in the default address space.
Nick Lewycky4a1ff162011-01-15 18:42:52 +0000103 if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Nick Lewycky0296a482011-01-15 18:14:21 +0000104 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
Chris Lattner67e53452010-09-15 00:30:11 +0000105 // Don't touch values marked with attribute(used).
106 UsedGlobals.count(GV))
Chris Lattner75879be2010-02-12 18:17:23 +0000107 continue;
Rafael Espindola751677a2011-01-16 17:05:09 +0000108
Eli Friedmanb31c6272012-01-11 22:06:46 +0000109 // This transformation is legal for weak ODR globals in the sense it
110 // doesn't change semantics, but we really don't want to perform it
111 // anyway; it's likely to pessimize code generation, and some tools
112 // (like the Darwin linker in cases involving CFString) don't expect it.
113 if (GV->isWeakForLinker())
Bill Wendlingc7915512012-01-11 00:13:08 +0000114 continue;
115
Chris Lattner75879be2010-02-12 18:17:23 +0000116 Constant *Init = GV->getInitializer();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000117
Chris Lattner75879be2010-02-12 18:17:23 +0000118 // Check to see if the initializer is already known.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000119 GlobalVariable *&Slot = CMap[Init];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000120
Bill Wendlingc7915512012-01-11 00:13:08 +0000121 // If this is the first constant we find or if the old one is local,
122 // replace with the current one. If the current is externally visible
Rafael Espindola751677a2011-01-16 17:05:09 +0000123 // it cannot be replace, but can be the canonical constant we merge with.
Craig Topperf40110f2014-04-25 05:29:35 +0000124 if (!Slot || IsBetterCanonical(*GV, *Slot))
Chris Lattner75879be2010-02-12 18:17:23 +0000125 Slot = GV;
Nick Lewycky0296a482011-01-15 18:14:21 +0000126 }
127
Rafael Espindola751677a2011-01-16 17:05:09 +0000128 // Second: identify all globals that can be merged together, filling in
129 // the Replacements vector. We cannot do the replacement in this pass
130 // because doing so may cause initializers of other globals to be rewritten,
131 // invalidating the Constant* pointers in CMap.
Nick Lewycky0296a482011-01-15 18:14:21 +0000132 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
133 GVI != E; ) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000134 GlobalVariable *GV = &*GVI++;
Nick Lewycky0296a482011-01-15 18:14:21 +0000135
136 // Only process constants with initializers in the default address space.
Nick Lewycky4a1ff162011-01-15 18:42:52 +0000137 if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Nick Lewycky0296a482011-01-15 18:14:21 +0000138 GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
139 // Don't touch values marked with attribute(used).
140 UsedGlobals.count(GV))
141 continue;
142
Eli Friedmanb31c6272012-01-11 22:06:46 +0000143 // We can only replace constant with local linkage.
144 if (!GV->hasLocalLinkage())
Nick Lewycky0296a482011-01-15 18:14:21 +0000145 continue;
146
147 Constant *Init = GV->getInitializer();
148
149 // Check to see if the initializer is already known.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000150 GlobalVariable *Slot = CMap[Init];
Nick Lewycky0296a482011-01-15 18:14:21 +0000151
Rafael Espindola751677a2011-01-16 17:05:09 +0000152 if (!Slot || Slot == GV)
153 continue;
154
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000155 if (!Slot->hasGlobalUnnamedAddr() && !GV->hasGlobalUnnamedAddr())
Rafael Espindola751677a2011-01-16 17:05:09 +0000156 continue;
157
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000158 if (!GV->hasGlobalUnnamedAddr())
159 Slot->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Rafael Espindola751677a2011-01-16 17:05:09 +0000160
161 // Make all uses of the duplicate constant use the canonical version.
162 Replacements.push_back(std::make_pair(GV, Slot));
Chris Lattner02137ee2007-04-14 01:11:54 +0000163 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000164
Chris Lattner56db5e92003-12-28 07:19:08 +0000165 if (Replacements.empty())
166 return MadeChange;
167 CMap.clear();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000168
Chris Lattner56db5e92003-12-28 07:19:08 +0000169 // Now that we have figured out which replacements must be made, do them all
170 // now. This avoid invalidating the pointers in CMap, which are unneeded
171 // now.
172 for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
Nick Lewycky8ac9ece2011-07-27 19:47:34 +0000173 // Bump the alignment if necessary.
174 if (Replacements[i].first->getAlignment() ||
175 Replacements[i].second->getAlignment()) {
Rafael Espindoladd8757a2013-11-12 20:21:43 +0000176 Replacements[i].second->setAlignment(
177 std::max(getAlignment(Replacements[i].first),
178 getAlignment(Replacements[i].second)));
Nick Lewycky8ac9ece2011-07-27 19:47:34 +0000179 }
180
Chris Lattner75879be2010-02-12 18:17:23 +0000181 // Eliminate any uses of the dead global.
Chris Lattner56db5e92003-12-28 07:19:08 +0000182 Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000183
Chris Lattner75879be2010-02-12 18:17:23 +0000184 // Delete the global value from the module.
Nick Lewycky0296a482011-01-15 18:14:21 +0000185 assert(Replacements[i].first->hasLocalLinkage() &&
186 "Refusing to delete an externally visible global variable.");
Chris Lattner75879be2010-02-12 18:17:23 +0000187 Replacements[i].first->eraseFromParent();
Chris Lattner56db5e92003-12-28 07:19:08 +0000188 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000189
Chris Lattner56db5e92003-12-28 07:19:08 +0000190 NumMerged += Replacements.size();
191 Replacements.clear();
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000192 }
Chris Lattnerc2ee0542003-12-22 23:49:36 +0000193}
Davide Italiano164b9bc2016-05-05 00:51:09 +0000194
195PreservedAnalyses ConstantMergePass::run(Module &M) {
196 if (!mergeConstants(M))
197 return PreservedAnalyses::all();
198 return PreservedAnalyses::none();
199}
200
201namespace {
202struct ConstantMergeLegacyPass : public ModulePass {
203 static char ID; // Pass identification, replacement for typeid
204 ConstantMergeLegacyPass() : ModulePass(ID) {
205 initializeConstantMergeLegacyPassPass(*PassRegistry::getPassRegistry());
206 }
207
208 // For this pass, process all of the globals in the module, eliminating
209 // duplicate constants.
210 bool runOnModule(Module &M) {
211 if (skipModule(M))
212 return false;
213 return mergeConstants(M);
214 }
215};
216}
217
218char ConstantMergeLegacyPass::ID = 0;
219INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
220 "Merge Duplicate Global Constants", false, false)
221
222ModulePass *llvm::createConstantMergePass() {
223 return new ConstantMergeLegacyPass();
224}