34 #define DEBUG_TYPE "globaldce" 38 cl::desc(
"Enable virtual function elimination"));
40 STATISTIC(NumAliases ,
"Number of global aliases removed");
41 STATISTIC(NumFunctions,
"Number of functions removed");
42 STATISTIC(NumIFuncs,
"Number of indirect functions removed");
43 STATISTIC(NumVariables,
"Number of global variables removed");
44 STATISTIC(NumVFuncs,
"Number of virtual functions removed");
47 class GlobalDCELegacyPass :
public ModulePass {
57 bool runOnModule(
Module &M)
override {
69 auto PA = Impl.run(M, DummyMAM);
70 return !PA.areAllPreserved();
80 "Dead Global Elimination",
false,
false)
84 return new GlobalDCELegacyPass();
90 for (
auto &
I : Entry) {
91 if (isa<DbgInfoIntrinsic>(
I))
93 if (
auto *RI = dyn_cast<ReturnInst>(&
I))
94 return !RI->getReturnValue();
102 void GlobalDCEPass::ComputeDependencies(
Value *V,
104 if (
auto *
I = dyn_cast<Instruction>(V)) {
105 Function *Parent =
I->getParent()->getParent();
107 }
else if (
auto *GV = dyn_cast<GlobalValue>(V)) {
109 }
else if (
auto *CE = dyn_cast<Constant>(V)) {
111 auto Where = ConstantDependenciesCache.find(CE);
112 if (Where != ConstantDependenciesCache.end()) {
113 auto const &K = Where->second;
114 Deps.
insert(K.begin(), K.end());
117 for (
User *CEUser : CE->users())
118 ComputeDependencies(CEUser, LocalDeps);
124 void GlobalDCEPass::UpdateGVDependencies(
GlobalValue &GV) {
127 ComputeDependencies(
User, Deps);
134 if (VFESafeVTables.count(GVU) && isa<Function>(&GV)) {
139 GVDependencies[GVU].insert(&GV);
146 auto const Ret = AliveGlobals.insert(&GV);
153 for (
auto &&CM :
make_range(ComdatMembers.equal_range(
C))) {
154 MarkLive(*CM.second, Updates);
160 void GlobalDCEPass::ScanVTables(
Module &M) {
164 auto *LTOPostLinkMD =
165 cast_or_null<ConstantAsMetadata>(M.
getModuleFlag(
"LTOPostLink"));
168 (cast<ConstantInt>(LTOPostLinkMD->getValue())->getZExtValue() != 0);
172 GV.getMetadata(LLVMContext::MD_type, Types);
184 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
187 TypeIdMap[
TypeID].insert(std::make_pair(&GV, Offset));
193 if (
auto GO = dyn_cast<GlobalObject>(&GV)) {
199 VFESafeVTables.insert(&GV);
206 uint64_t CallOffset) {
207 for (
auto &VTableInfo : TypeIdMap[TypeId]) {
209 uint64_t VTableOffset = VTableInfo.second;
216 VFESafeVTables.erase(VTable);
223 VFESafeVTables.erase(VTable);
228 <<
Callee->getName() <<
"\n");
229 GVDependencies[Caller].insert(
Callee);
233 void GlobalDCEPass::ScanTypeCheckedLoadIntrinsics(
Module &M) {
238 if (!TypeCheckedLoadFunc)
241 for (
auto U : TypeCheckedLoadFunc->
users()) {
247 Value *TypeIdValue = CI->getArgOperand(2);
248 auto *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
251 ScanVTableLoad(CI->getFunction(), TypeId,
Offset->getZExtValue());
255 for (
auto &VTableInfo : TypeIdMap[TypeId]) {
256 VFESafeVTables.erase(VTableInfo.first);
262 void GlobalDCEPass::AddVirtualFunctionDependencies(
Module &M) {
268 if (VFESafeVTables.empty())
271 ScanTypeCheckedLoadIntrinsics(M);
274 dbgs() <<
"VFE safe vtables:\n";
275 for (
auto *VTable : VFESafeVTables)
276 dbgs() <<
" " << VTable->getName() <<
"\n";
281 bool Changed =
false;
297 ComdatMembers.insert(std::make_pair(
C, &
F));
300 ComdatMembers.insert(std::make_pair(
C, &GV));
302 if (
Comdat *
C = GA.getComdat())
303 ComdatMembers.insert(std::make_pair(
C, &GA));
307 AddVirtualFunctionDependencies(M);
311 Changed |= RemoveUnusedGlobalValue(GO);
315 if (!GO.isDeclaration())
316 if (!GO.isDiscardableIfUnused())
319 UpdateGVDependencies(GO);
324 Changed |= RemoveUnusedGlobalValue(GA);
326 if (!GA.isDiscardableIfUnused())
329 UpdateGVDependencies(GA);
334 Changed |= RemoveUnusedGlobalValue(GIF);
336 if (!GIF.isDiscardableIfUnused())
339 UpdateGVDependencies(GIF);
346 while (!NewLiveGVs.empty()) {
348 for (
auto *GVD : GVDependencies[LGV])
349 MarkLive(*GVD, &NewLiveGVs);
357 std::vector<GlobalVariable *> DeadGlobalVars;
359 if (!AliveGlobals.count(&GV)) {
360 DeadGlobalVars.push_back(&GV);
361 if (GV.hasInitializer()) {
363 GV.setInitializer(
nullptr);
370 std::vector<Function *> DeadFunctions;
372 if (!AliveGlobals.count(&
F)) {
373 DeadFunctions.push_back(&
F);
374 if (!
F.isDeclaration())
379 std::vector<GlobalAlias*> DeadAliases;
381 if (!AliveGlobals.count(&GA)) {
382 DeadAliases.push_back(&GA);
383 GA.setAliasee(
nullptr);
387 std::vector<GlobalIFunc*> DeadIFuncs;
389 if (!AliveGlobals.count(&GIF)) {
390 DeadIFuncs.push_back(&GIF);
391 GIF.setResolver(
nullptr);
396 auto EraseUnusedGlobalValue = [&](
GlobalValue *GV) {
397 RemoveUnusedGlobalValue(*GV);
402 NumFunctions += DeadFunctions.size();
404 if (!
F->use_empty()) {
412 EraseUnusedGlobalValue(
F);
415 NumVariables += DeadGlobalVars.size();
417 EraseUnusedGlobalValue(GV);
419 NumAliases += DeadAliases.size();
421 EraseUnusedGlobalValue(GA);
423 NumIFuncs += DeadIFuncs.size();
425 EraseUnusedGlobalValue(GIF);
428 AliveGlobals.clear();
429 ConstantDependenciesCache.clear();
430 GVDependencies.clear();
431 ComdatMembers.clear();
433 VFESafeVTables.clear();
446 bool GlobalDCEPass::RemoveUnusedGlobalValue(
GlobalValue &GV) {
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
void push_back(const T &Elt)
static cl::opt< bool > ClEnableVFE("enable-vfe", cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::desc("Enable virtual function elimination"))
This class represents a function call, abstracting a target machine's calling convention.
void initializeGlobalDCELegacyPassPass(PassRegistry &)
STATISTIC(NumFunctions, "Total number of functions")
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", "Dead Global Elimination", false, false) ModulePass *llvm
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
TypeID
Definitions of all of the base types for the Type system.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
Pass to remove unused function declarations.
ModulePass * createGlobalDCEPass()
createGlobalDCEPass - This transform is designed to eliminate unreachable internal globals (functions...
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
const BasicBlock & getEntryBlock() const
initializer< Ty > init(const Ty &Val)
A set of analyses that are preserved following a run of a transformation pass.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
This is an important base class in LLVM.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const Constant * stripPointerCasts() const
bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static bool isEmptyFunction(Function *F)
Returns true if F is effectively empty.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
const Comdat * getComdat() const
amdgpu Simplify well known AMD library false FunctionCallee Callee
iterator_range< user_iterator > users()
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void destroyConstant()
Called if some element of this constant is no longer valid.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
iterator_range< global_iterator > globals()
A container for analyses that lazily runs them and caches their results.
bool optimizeGlobalCtorsList(Module &M, function_ref< bool(Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M's global_ctor list and remove the entries for which it retur...
Constant * getPointerAtOffset(Constant *I, uint64_t Offset, Module &M)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)