LLVM  8.0.0svn
GlobalDCE.cpp
Go to the documentation of this file.
1 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transform is designed to eliminate unreachable internal globals from the
11 // program. It uses an aggressive algorithm, searching out globals that are
12 // known to be alive. After it finds all of the globals which are needed, it
13 // deletes whatever is left over. This allows it to delete recursive chunks of
14 // the program which are unreachable.
15 //
16 //===----------------------------------------------------------------------===//
17 
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Transforms/IPO.h"
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "globaldce"
31 
32 STATISTIC(NumAliases , "Number of global aliases removed");
33 STATISTIC(NumFunctions, "Number of functions removed");
34 STATISTIC(NumIFuncs, "Number of indirect functions removed");
35 STATISTIC(NumVariables, "Number of global variables removed");
36 
37 namespace {
38  class GlobalDCELegacyPass : public ModulePass {
39  public:
40  static char ID; // Pass identification, replacement for typeid
41  GlobalDCELegacyPass() : ModulePass(ID) {
43  }
44 
45  // run - Do the GlobalDCE pass on the specified module, optionally updating
46  // the specified callgraph to reflect the changes.
47  //
48  bool runOnModule(Module &M) override {
49  if (skipModule(M))
50  return false;
51 
52  // We need a minimally functional dummy module analysis manager. It needs
53  // to at least know about the possibility of proxying a function analysis
54  // manager.
55  FunctionAnalysisManager DummyFAM;
56  ModuleAnalysisManager DummyMAM;
57  DummyMAM.registerPass(
58  [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); });
59 
60  auto PA = Impl.run(M, DummyMAM);
61  return !PA.areAllPreserved();
62  }
63 
64  private:
65  GlobalDCEPass Impl;
66  };
67 }
68 
70 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
71  "Dead Global Elimination", false, false)
72 
73 // Public interface to the GlobalDCEPass.
75  return new GlobalDCELegacyPass();
76 }
77 
78 /// Returns true if F contains only a single "ret" instruction.
79 static bool isEmptyFunction(Function *F) {
80  BasicBlock &Entry = F->getEntryBlock();
81  if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
82  return false;
83  ReturnInst &RI = cast<ReturnInst>(Entry.front());
84  return RI.getReturnValue() == nullptr;
85 }
86 
87 /// Compute the set of GlobalValue that depends from V.
88 /// The recursion stops as soon as a GlobalValue is met.
89 void GlobalDCEPass::ComputeDependencies(Value *V,
91  if (auto *I = dyn_cast<Instruction>(V)) {
92  Function *Parent = I->getParent()->getParent();
93  Deps.insert(Parent);
94  } else if (auto *GV = dyn_cast<GlobalValue>(V)) {
95  Deps.insert(GV);
96  } else if (auto *CE = dyn_cast<Constant>(V)) {
97  // Avoid walking the whole tree of a big ConstantExprs multiple times.
98  auto Where = ConstantDependenciesCache.find(CE);
99  if (Where != ConstantDependenciesCache.end()) {
100  auto const &K = Where->second;
101  Deps.insert(K.begin(), K.end());
102  } else {
103  SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
104  for (User *CEUser : CE->users())
105  ComputeDependencies(CEUser, LocalDeps);
106  Deps.insert(LocalDeps.begin(), LocalDeps.end());
107  }
108  }
109 }
110 
111 void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
113  for (User *User : GV.users())
114  ComputeDependencies(User, Deps);
115  Deps.erase(&GV); // Remove self-reference.
116  for (GlobalValue *GVU : Deps) {
117  GVDependencies[GVU].insert(&GV);
118  }
119 }
120 
121 /// Mark Global value as Live
122 void GlobalDCEPass::MarkLive(GlobalValue &GV,
124  auto const Ret = AliveGlobals.insert(&GV);
125  if (!Ret.second)
126  return;
127 
128  if (Updates)
129  Updates->push_back(&GV);
130  if (Comdat *C = GV.getComdat()) {
131  for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
132  MarkLive(*CM.second, Updates); // Recursion depth is only two because only
133  // globals in the same comdat are visited.
134  }
135 }
136 
138  bool Changed = false;
139 
140  // The algorithm first computes the set L of global variables that are
141  // trivially live. Then it walks the initialization of these variables to
142  // compute the globals used to initialize them, which effectively builds a
143  // directed graph where nodes are global variables, and an edge from A to B
144  // means B is used to initialize A. Finally, it propagates the liveness
145  // information through the graph starting from the nodes in L. Nodes note
146  // marked as alive are discarded.
147 
148  // Remove empty functions from the global ctors list.
150 
151  // Collect the set of members for each comdat.
152  for (Function &F : M)
153  if (Comdat *C = F.getComdat())
154  ComdatMembers.insert(std::make_pair(C, &F));
155  for (GlobalVariable &GV : M.globals())
156  if (Comdat *C = GV.getComdat())
157  ComdatMembers.insert(std::make_pair(C, &GV));
158  for (GlobalAlias &GA : M.aliases())
159  if (Comdat *C = GA.getComdat())
160  ComdatMembers.insert(std::make_pair(C, &GA));
161 
162  // Loop over the module, adding globals which are obviously necessary.
163  for (GlobalObject &GO : M.global_objects()) {
164  Changed |= RemoveUnusedGlobalValue(GO);
165  // Functions with external linkage are needed if they have a body.
166  // Externally visible & appending globals are needed, if they have an
167  // initializer.
168  if (!GO.isDeclaration())
169  if (!GO.isDiscardableIfUnused())
170  MarkLive(GO);
171 
172  UpdateGVDependencies(GO);
173  }
174 
175  // Compute direct dependencies of aliases.
176  for (GlobalAlias &GA : M.aliases()) {
177  Changed |= RemoveUnusedGlobalValue(GA);
178  // Externally visible aliases are needed.
179  if (!GA.isDiscardableIfUnused())
180  MarkLive(GA);
181 
182  UpdateGVDependencies(GA);
183  }
184 
185  // Compute direct dependencies of ifuncs.
186  for (GlobalIFunc &GIF : M.ifuncs()) {
187  Changed |= RemoveUnusedGlobalValue(GIF);
188  // Externally visible ifuncs are needed.
189  if (!GIF.isDiscardableIfUnused())
190  MarkLive(GIF);
191 
192  UpdateGVDependencies(GIF);
193  }
194 
195  // Propagate liveness from collected Global Values through the computed
196  // dependencies.
197  SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
198  AliveGlobals.end()};
199  while (!NewLiveGVs.empty()) {
200  GlobalValue *LGV = NewLiveGVs.pop_back_val();
201  for (auto *GVD : GVDependencies[LGV])
202  MarkLive(*GVD, &NewLiveGVs);
203  }
204 
205  // Now that all globals which are needed are in the AliveGlobals set, we loop
206  // through the program, deleting those which are not alive.
207  //
208 
209  // The first pass is to drop initializers of global variables which are dead.
210  std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
211  for (GlobalVariable &GV : M.globals())
212  if (!AliveGlobals.count(&GV)) {
213  DeadGlobalVars.push_back(&GV); // Keep track of dead globals
214  if (GV.hasInitializer()) {
215  Constant *Init = GV.getInitializer();
216  GV.setInitializer(nullptr);
217  if (isSafeToDestroyConstant(Init))
218  Init->destroyConstant();
219  }
220  }
221 
222  // The second pass drops the bodies of functions which are dead...
223  std::vector<Function *> DeadFunctions;
224  for (Function &F : M)
225  if (!AliveGlobals.count(&F)) {
226  DeadFunctions.push_back(&F); // Keep track of dead globals
227  if (!F.isDeclaration())
228  F.deleteBody();
229  }
230 
231  // The third pass drops targets of aliases which are dead...
232  std::vector<GlobalAlias*> DeadAliases;
233  for (GlobalAlias &GA : M.aliases())
234  if (!AliveGlobals.count(&GA)) {
235  DeadAliases.push_back(&GA);
236  GA.setAliasee(nullptr);
237  }
238 
239  // The fourth pass drops targets of ifuncs which are dead...
240  std::vector<GlobalIFunc*> DeadIFuncs;
241  for (GlobalIFunc &GIF : M.ifuncs())
242  if (!AliveGlobals.count(&GIF)) {
243  DeadIFuncs.push_back(&GIF);
244  GIF.setResolver(nullptr);
245  }
246 
247  // Now that all interferences have been dropped, delete the actual objects
248  // themselves.
249  auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
250  RemoveUnusedGlobalValue(*GV);
251  GV->eraseFromParent();
252  Changed = true;
253  };
254 
255  NumFunctions += DeadFunctions.size();
256  for (Function *F : DeadFunctions)
257  EraseUnusedGlobalValue(F);
258 
259  NumVariables += DeadGlobalVars.size();
260  for (GlobalVariable *GV : DeadGlobalVars)
261  EraseUnusedGlobalValue(GV);
262 
263  NumAliases += DeadAliases.size();
264  for (GlobalAlias *GA : DeadAliases)
265  EraseUnusedGlobalValue(GA);
266 
267  NumIFuncs += DeadIFuncs.size();
268  for (GlobalIFunc *GIF : DeadIFuncs)
269  EraseUnusedGlobalValue(GIF);
270 
271  // Make sure that all memory is released
272  AliveGlobals.clear();
273  ConstantDependenciesCache.clear();
274  GVDependencies.clear();
275  ComdatMembers.clear();
276 
277  if (Changed)
278  return PreservedAnalyses::none();
279  return PreservedAnalyses::all();
280 }
281 
282 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
283 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
284 // If found, check to see if the constant pointer ref is safe to destroy, and if
285 // so, nuke it. This will reduce the reference count on the global value, which
286 // might make it deader.
287 //
288 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
289  if (GV.use_empty())
290  return false;
292  return GV.use_empty();
293 }
uint64_t CallInst * C
Return a value (possibly void), from a function.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
void initializeGlobalDCELegacyPassPass(PassRegistry &)
STATISTIC(NumFunctions, "Total number of functions")
F(f)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:344
INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", "Dead Global Elimination", false, false) ModulePass *llvm
Definition: GlobalDCE.cpp:70
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:822
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
Definition: PassManager.h:1121
Pass to remove unused function declarations.
Definition: GlobalDCE.h:30
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.
Definition: Constants.cpp:536
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
const BasicBlock & getEntryBlock() const
Definition: Function.h:640
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
const Instruction & front() const
Definition: BasicBlock.h:276
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
size_t size() const
Definition: BasicBlock.h:274
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.
Definition: PassManager.h:160
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...
Definition: SmallPtrSet.h:418
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:378
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
static bool isEmptyFunction(Function *F)
Returns true if F contains only a single "ret" instruction.
Definition: GlobalDCE.cpp:79
const Comdat * getComdat() const
Definition: Globals.cpp:171
iterator_range< user_iterator > users()
Definition: Value.h:400
void eraseFromParent()
This method unlinks &#39;this&#39; from the containing module and deletes it.
Definition: Globals.cpp:85
iterator begin() const
Definition: SmallPtrSet.h:397
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:361
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
iterator end() const
Definition: SmallPtrSet.h:402
LLVM Value Representation.
Definition: Value.h:73
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&#39;s global_ctor list and remove the entries for which it retur...
Definition: CtorUtils.cpp:119
bool use_empty() const
Definition: Value.h:323
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
Definition: GlobalDCE.cpp:137