llvm-project/llvm/lib/Transforms/IPO/ConstantMerge.cpp

63 lines
2.1 KiB
C++
Raw Normal View History

//===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
2001-10-19 04:05:37 +08:00
//
// This file defines the interface to a pass that merges duplicate global
// constants together into a single constant that is shared. This is useful
// because some passes (ie TraceValues) insert a lot of string constants into
// the program, regardless of whether or not an existing string is available.
2001-10-19 04:05:37 +08:00
//
// Algorithm: ConstantMerge is designed to build up a map of available constants
// and eliminate duplicates when it is initialized.
2001-10-19 04:05:37 +08:00
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "Support/Statistic.h"
namespace {
Statistic<> NumMerged("constmerge", "Number of global constants merged");
struct ConstantMerge : public Pass {
// run - For this pass, process all of the globals in the module,
// eliminating duplicate constants.
//
bool run(Module &M);
};
RegisterOpt<ConstantMerge> X("constmerge","Merge Duplicate Global Constants");
}
Pass *createConstantMergePass() { return new ConstantMerge(); }
bool ConstantMerge::run(Module &M) {
std::map<Constant*, GlobalVariable*> CMap;
2001-10-19 04:05:37 +08:00
bool MadeChanges = false;
for (Module::giterator GV = M.gbegin(), E = M.gend(); GV != E; ++GV)
// Only process constants with initializers
if (GV->isConstant() && GV->hasInitializer()) {
Constant *Init = GV->getInitializer();
2001-10-19 04:05:37 +08:00
// Check to see if the initializer is already known...
std::map<Constant*, GlobalVariable*>::iterator I = CMap.find(Init);
2001-10-19 04:05:37 +08:00
if (I == CMap.end()) { // Nope, add it to the map
CMap.insert(I, std::make_pair(Init, GV));
2001-10-19 04:05:37 +08:00
} else { // Yup, this is a duplicate!
2003-09-10 13:29:43 +08:00
// Make all uses of the duplicate constant use the canonical version...
GV->replaceAllUsesWith(I->second);
2001-10-19 04:05:37 +08:00
// Delete the global value from the module... and back up iterator to
// not skip the next global...
GV = --M.getGlobalList().erase(GV);
2001-10-19 04:05:37 +08:00
++NumMerged;
2001-10-19 04:05:37 +08:00
MadeChanges = true;
}
}
return MadeChanges;
2001-10-19 04:05:37 +08:00
}