LLVM API Documentation

ConstantMerge.cpp
Go to the documentation of this file.
00001 //===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the interface to a pass that merges duplicate global
00011 // constants together into a single constant that is shared.  This is useful
00012 // because some passes (ie TraceValues) insert a lot of string constants into
00013 // the program, regardless of whether or not an existing string is available.
00014 //
00015 // Algorithm: ConstantMerge is designed to build up a map of available constants
00016 // and eliminate duplicates when it is initialized.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #define DEBUG_TYPE "constmerge"
00021 #include "llvm/Transforms/IPO.h"
00022 #include "llvm/ADT/DenseMap.h"
00023 #include "llvm/ADT/PointerIntPair.h"
00024 #include "llvm/ADT/SmallPtrSet.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/IR/Constants.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/DerivedTypes.h"
00029 #include "llvm/IR/Module.h"
00030 #include "llvm/IR/Operator.h"
00031 #include "llvm/Pass.h"
00032 using namespace llvm;
00033 
00034 STATISTIC(NumMerged, "Number of global constants merged");
00035 
00036 namespace {
00037   struct ConstantMerge : public ModulePass {
00038     static char ID; // Pass identification, replacement for typeid
00039     ConstantMerge() : ModulePass(ID) {
00040       initializeConstantMergePass(*PassRegistry::getPassRegistry());
00041     }
00042 
00043     // For this pass, process all of the globals in the module, eliminating
00044     // duplicate constants.
00045     bool runOnModule(Module &M);
00046 
00047     // Return true iff we can determine the alignment of this global variable.
00048     bool hasKnownAlignment(GlobalVariable *GV) const;
00049 
00050     // Return the alignment of the global, including converting the default
00051     // alignment to a concrete value.
00052     unsigned getAlignment(GlobalVariable *GV) const;
00053 
00054     const DataLayout *TD;
00055   };
00056 }
00057 
00058 char ConstantMerge::ID = 0;
00059 INITIALIZE_PASS(ConstantMerge, "constmerge",
00060                 "Merge Duplicate Global Constants", false, false)
00061 
00062 ModulePass *llvm::createConstantMergePass() { return new ConstantMerge(); }
00063 
00064 
00065 
00066 /// Find values that are marked as llvm.used.
00067 static void FindUsedValues(GlobalVariable *LLVMUsed,
00068                            SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
00069   if (LLVMUsed == 0) return;
00070   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
00071 
00072   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
00073     Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
00074     GlobalValue *GV = cast<GlobalValue>(Operand);
00075     UsedValues.insert(GV);
00076   }
00077 }
00078 
00079 // True if A is better than B.
00080 static bool IsBetterCannonical(const GlobalVariable &A,
00081                                const GlobalVariable &B) {
00082   if (!A.hasLocalLinkage() && B.hasLocalLinkage())
00083     return true;
00084 
00085   if (A.hasLocalLinkage() && !B.hasLocalLinkage())
00086     return false;
00087 
00088   return A.hasUnnamedAddr();
00089 }
00090 
00091 bool ConstantMerge::hasKnownAlignment(GlobalVariable *GV) const {
00092   return TD || GV->getAlignment() != 0;
00093 }
00094 
00095 unsigned ConstantMerge::getAlignment(GlobalVariable *GV) const {
00096   if (TD)
00097     return TD->getPreferredAlignment(GV);
00098   return GV->getAlignment();
00099 }
00100 
00101 bool ConstantMerge::runOnModule(Module &M) {
00102   TD = getAnalysisIfAvailable<DataLayout>();
00103 
00104   // Find all the globals that are marked "used".  These cannot be merged.
00105   SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
00106   FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
00107   FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
00108   
00109   // Map unique <constants, has-unknown-alignment> pairs to globals.  We don't
00110   // want to merge globals of unknown alignment with those of explicit
00111   // alignment.  If we have DataLayout, we always know the alignment.
00112   DenseMap<PointerIntPair<Constant*, 1, bool>, GlobalVariable*> CMap;
00113 
00114   // Replacements - This vector contains a list of replacements to perform.
00115   SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
00116 
00117   bool MadeChange = false;
00118 
00119   // Iterate constant merging while we are still making progress.  Merging two
00120   // constants together may allow us to merge other constants together if the
00121   // second level constants have initializers which point to the globals that
00122   // were just merged.
00123   while (1) {
00124 
00125     // First: Find the canonical constants others will be merged with.
00126     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
00127          GVI != E; ) {
00128       GlobalVariable *GV = GVI++;
00129 
00130       // If this GV is dead, remove it.
00131       GV->removeDeadConstantUsers();
00132       if (GV->use_empty() && GV->hasLocalLinkage()) {
00133         GV->eraseFromParent();
00134         continue;
00135       }
00136 
00137       // Only process constants with initializers in the default address space.
00138       if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
00139           GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
00140           // Don't touch values marked with attribute(used).
00141           UsedGlobals.count(GV))
00142         continue;
00143 
00144       // This transformation is legal for weak ODR globals in the sense it
00145       // doesn't change semantics, but we really don't want to perform it
00146       // anyway; it's likely to pessimize code generation, and some tools
00147       // (like the Darwin linker in cases involving CFString) don't expect it.
00148       if (GV->isWeakForLinker())
00149         continue;
00150 
00151       Constant *Init = GV->getInitializer();
00152 
00153       // Check to see if the initializer is already known.
00154       PointerIntPair<Constant*, 1, bool> Pair(Init, hasKnownAlignment(GV));
00155       GlobalVariable *&Slot = CMap[Pair];
00156 
00157       // If this is the first constant we find or if the old one is local,
00158       // replace with the current one. If the current is externally visible
00159       // it cannot be replace, but can be the canonical constant we merge with.
00160       if (Slot == 0 || IsBetterCannonical(*GV, *Slot))
00161         Slot = GV;
00162     }
00163 
00164     // Second: identify all globals that can be merged together, filling in
00165     // the Replacements vector.  We cannot do the replacement in this pass
00166     // because doing so may cause initializers of other globals to be rewritten,
00167     // invalidating the Constant* pointers in CMap.
00168     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
00169          GVI != E; ) {
00170       GlobalVariable *GV = GVI++;
00171 
00172       // Only process constants with initializers in the default address space.
00173       if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
00174           GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
00175           // Don't touch values marked with attribute(used).
00176           UsedGlobals.count(GV))
00177         continue;
00178 
00179       // We can only replace constant with local linkage.
00180       if (!GV->hasLocalLinkage())
00181         continue;
00182 
00183       Constant *Init = GV->getInitializer();
00184 
00185       // Check to see if the initializer is already known.
00186       PointerIntPair<Constant*, 1, bool> Pair(Init, hasKnownAlignment(GV));
00187       GlobalVariable *Slot = CMap[Pair];
00188 
00189       if (!Slot || Slot == GV)
00190         continue;
00191 
00192       if (!Slot->hasUnnamedAddr() && !GV->hasUnnamedAddr())
00193         continue;
00194 
00195       if (!GV->hasUnnamedAddr())
00196         Slot->setUnnamedAddr(false);
00197 
00198       // Make all uses of the duplicate constant use the canonical version.
00199       Replacements.push_back(std::make_pair(GV, Slot));
00200     }
00201 
00202     if (Replacements.empty())
00203       return MadeChange;
00204     CMap.clear();
00205 
00206     // Now that we have figured out which replacements must be made, do them all
00207     // now.  This avoid invalidating the pointers in CMap, which are unneeded
00208     // now.
00209     for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
00210       // Bump the alignment if necessary.
00211       if (Replacements[i].first->getAlignment() ||
00212           Replacements[i].second->getAlignment()) {
00213         Replacements[i].second->setAlignment(std::max(
00214             Replacements[i].first->getAlignment(),
00215             Replacements[i].second->getAlignment()));
00216       }
00217 
00218       // Eliminate any uses of the dead global.
00219       Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
00220 
00221       // Delete the global value from the module.
00222       assert(Replacements[i].first->hasLocalLinkage() &&
00223              "Refusing to delete an externally visible global variable.");
00224       Replacements[i].first->eraseFromParent();
00225     }
00226 
00227     NumMerged += Replacements.size();
00228     Replacements.clear();
00229   }
00230 }