LLVM  4.0.0
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/Constants.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Transforms/IPO.h"
28 #include <unordered_map>
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "globaldce"
32 
33 STATISTIC(NumAliases , "Number of global aliases removed");
34 STATISTIC(NumFunctions, "Number of functions removed");
35 STATISTIC(NumIFuncs, "Number of indirect functions removed");
36 STATISTIC(NumVariables, "Number of global variables removed");
37 
38 namespace {
39  class GlobalDCELegacyPass : public ModulePass {
40  public:
41  static char ID; // Pass identification, replacement for typeid
42  GlobalDCELegacyPass() : ModulePass(ID) {
44  }
45 
46  // run - Do the GlobalDCE pass on the specified module, optionally updating
47  // the specified callgraph to reflect the changes.
48  //
49  bool runOnModule(Module &M) override {
50  if (skipModule(M))
51  return false;
52 
53  ModuleAnalysisManager DummyMAM;
54  auto PA = Impl.run(M, DummyMAM);
55  return !PA.areAllPreserved();
56  }
57 
58  private:
59  GlobalDCEPass Impl;
60  };
61 }
62 
64 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
65  "Dead Global Elimination", false, false)
66 
67 // Public interface to the GlobalDCEPass.
69  return new GlobalDCELegacyPass();
70 }
71 
72 /// Returns true if F contains only a single "ret" instruction.
73 static bool isEmptyFunction(Function *F) {
74  BasicBlock &Entry = F->getEntryBlock();
75  if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
76  return false;
77  ReturnInst &RI = cast<ReturnInst>(Entry.front());
78  return RI.getReturnValue() == nullptr;
79 }
80 
82  bool Changed = false;
83 
84  // Remove empty functions from the global ctors list.
86 
87  // Collect the set of members for each comdat.
88  for (Function &F : M)
89  if (Comdat *C = F.getComdat())
90  ComdatMembers.insert(std::make_pair(C, &F));
91  for (GlobalVariable &GV : M.globals())
92  if (Comdat *C = GV.getComdat())
93  ComdatMembers.insert(std::make_pair(C, &GV));
94  for (GlobalAlias &GA : M.aliases())
95  if (Comdat *C = GA.getComdat())
96  ComdatMembers.insert(std::make_pair(C, &GA));
97 
98  // Loop over the module, adding globals which are obviously necessary.
99  for (GlobalObject &GO : M.global_objects()) {
100  Changed |= RemoveUnusedGlobalValue(GO);
101  // Functions with external linkage are needed if they have a body.
102  // Externally visible & appending globals are needed, if they have an
103  // initializer.
104  if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage())
105  if (!GO.isDiscardableIfUnused())
106  GlobalIsNeeded(&GO);
107  }
108 
109  for (GlobalAlias &GA : M.aliases()) {
110  Changed |= RemoveUnusedGlobalValue(GA);
111  // Externally visible aliases are needed.
112  if (!GA.isDiscardableIfUnused())
113  GlobalIsNeeded(&GA);
114  }
115 
116  for (GlobalIFunc &GIF : M.ifuncs()) {
117  Changed |= RemoveUnusedGlobalValue(GIF);
118  // Externally visible ifuncs are needed.
119  if (!GIF.isDiscardableIfUnused())
120  GlobalIsNeeded(&GIF);
121  }
122 
123  // Now that all globals which are needed are in the AliveGlobals set, we loop
124  // through the program, deleting those which are not alive.
125  //
126 
127  // The first pass is to drop initializers of global variables which are dead.
128  std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
129  for (GlobalVariable &GV : M.globals())
130  if (!AliveGlobals.count(&GV)) {
131  DeadGlobalVars.push_back(&GV); // Keep track of dead globals
132  if (GV.hasInitializer()) {
133  Constant *Init = GV.getInitializer();
134  GV.setInitializer(nullptr);
135  if (isSafeToDestroyConstant(Init))
136  Init->destroyConstant();
137  }
138  }
139 
140  // The second pass drops the bodies of functions which are dead...
141  std::vector<Function *> DeadFunctions;
142  for (Function &F : M)
143  if (!AliveGlobals.count(&F)) {
144  DeadFunctions.push_back(&F); // Keep track of dead globals
145  if (!F.isDeclaration())
146  F.deleteBody();
147  }
148 
149  // The third pass drops targets of aliases which are dead...
150  std::vector<GlobalAlias*> DeadAliases;
151  for (GlobalAlias &GA : M.aliases())
152  if (!AliveGlobals.count(&GA)) {
153  DeadAliases.push_back(&GA);
154  GA.setAliasee(nullptr);
155  }
156 
157  // The third pass drops targets of ifuncs which are dead...
158  std::vector<GlobalIFunc*> DeadIFuncs;
159  for (GlobalIFunc &GIF : M.ifuncs())
160  if (!AliveGlobals.count(&GIF)) {
161  DeadIFuncs.push_back(&GIF);
162  GIF.setResolver(nullptr);
163  }
164 
165  // Now that all interferences have been dropped, delete the actual objects
166  // themselves.
167  auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
168  RemoveUnusedGlobalValue(*GV);
169  GV->eraseFromParent();
170  Changed = true;
171  };
172 
173  NumFunctions += DeadFunctions.size();
174  for (Function *F : DeadFunctions)
175  EraseUnusedGlobalValue(F);
176 
177  NumVariables += DeadGlobalVars.size();
178  for (GlobalVariable *GV : DeadGlobalVars)
179  EraseUnusedGlobalValue(GV);
180 
181  NumAliases += DeadAliases.size();
182  for (GlobalAlias *GA : DeadAliases)
183  EraseUnusedGlobalValue(GA);
184 
185  NumIFuncs += DeadIFuncs.size();
186  for (GlobalIFunc *GIF : DeadIFuncs)
187  EraseUnusedGlobalValue(GIF);
188 
189  // Make sure that all memory is released
190  AliveGlobals.clear();
191  SeenConstants.clear();
192  ComdatMembers.clear();
193 
194  if (Changed)
195  return PreservedAnalyses::none();
196  return PreservedAnalyses::all();
197 }
198 
199 /// GlobalIsNeeded - the specific global value as needed, and
200 /// recursively mark anything that it uses as also needed.
201 void GlobalDCEPass::GlobalIsNeeded(GlobalValue *G) {
202  // If the global is already in the set, no need to reprocess it.
203  if (!AliveGlobals.insert(G).second)
204  return;
205 
206  if (Comdat *C = G->getComdat()) {
207  for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
208  GlobalIsNeeded(CM.second);
209  }
210 
211  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
212  // If this is a global variable, we must make sure to add any global values
213  // referenced by the initializer to the alive set.
214  if (GV->hasInitializer())
215  MarkUsedGlobalsAsNeeded(GV->getInitializer());
216  } else if (GlobalIndirectSymbol *GIS = dyn_cast<GlobalIndirectSymbol>(G)) {
217  // The target of a global alias or ifunc is needed.
218  MarkUsedGlobalsAsNeeded(GIS->getIndirectSymbol());
219  } else {
220  // Otherwise this must be a function object. We have to scan the body of
221  // the function looking for constants and global values which are used as
222  // operands. Any operands of these types must be processed to ensure that
223  // any globals used will be marked as needed.
224  Function *F = cast<Function>(G);
225 
226  for (Use &U : F->operands())
227  MarkUsedGlobalsAsNeeded(cast<Constant>(U.get()));
228 
229  for (BasicBlock &BB : *F)
230  for (Instruction &I : BB)
231  for (Use &U : I.operands())
232  if (GlobalValue *GV = dyn_cast<GlobalValue>(U))
233  GlobalIsNeeded(GV);
234  else if (Constant *C = dyn_cast<Constant>(U))
235  MarkUsedGlobalsAsNeeded(C);
236  }
237 }
238 
239 void GlobalDCEPass::MarkUsedGlobalsAsNeeded(Constant *C) {
240  if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
241  return GlobalIsNeeded(GV);
242 
243  // Loop over all of the operands of the constant, adding any globals they
244  // use to the list of needed globals.
245  for (Use &U : C->operands()) {
246  // If we've already processed this constant there's no need to do it again.
247  Constant *Op = dyn_cast<Constant>(U);
248  if (Op && SeenConstants.insert(Op).second)
249  MarkUsedGlobalsAsNeeded(Op);
250  }
251 }
252 
253 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
254 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
255 // If found, check to see if the constant pointer ref is safe to destroy, and if
256 // so, nuke it. This will reduce the reference count on the global value, which
257 // might make it deader.
258 //
259 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
260  if (GV.use_empty())
261  return false;
263  return GV.use_empty();
264 }
Return a value (possibly void), from a function.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
void initializeGlobalDCELegacyPassPass(PassRegistry &)
const Instruction & front() const
Definition: BasicBlock.h:240
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
#define F(x, y, z)
Definition: MD5.cpp:51
Pass to remove unused function declarations.
Definition: GlobalDCE.h:28
ModulePass * createGlobalDCEPass()
createGlobalDCEPass - This transform is designed to eliminate unreachable internal globals (functions...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:110
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
op_range operands()
Definition: User.h:213
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:113
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Comdat * getComdat()
Definition: Globals.cpp:155
INITIALIZE_PASS(GlobalDCELegacyPass,"globaldce","Dead Global Elimination", false, false) ModulePass *llvm
Definition: GlobalDCE.cpp:64
Module.h This file contains the declarations for the Module class.
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
static bool isEmptyFunction(Function *F)
Returns true if F contains only a single "ret" instruction.
Definition: GlobalDCE.cpp:73
const BasicBlock & getEntryBlock() const
Definition: Function.h:519
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
#define I(x, y, z)
Definition: MD5.cpp:54
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:287
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:288
size_t size() const
Definition: BasicBlock.h:238
bool use_empty() const
Definition: Value.h:299
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:463
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 ret...
Definition: CtorUtils.cpp:120
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
Definition: GlobalDCE.cpp:81