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 
18 #include "llvm/Transforms/IPO/GlobalDCE.h"
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"
26 #include "llvm/Transforms/Utils/CtorUtils.h"
27 #include "llvm/Transforms/Utils/GlobalStatus.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) {
43       initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
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 
63 char GlobalDCELegacyPass::ID = 0;
64 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
65                 "Dead Global Elimination", false, false)
66 
67 // Public interface to the GlobalDCEPass.
68 ModulePass *llvm::createGlobalDCEPass() {
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 
81 PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &) {
82   bool Changed = false;
83 
84   // Remove empty functions from the global ctors list.
85   Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
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 (Function &F : M) {
100     Changed |= RemoveUnusedGlobalValue(F);
101     // Functions with external linkage are needed if they have a body
102     if (!F.isDeclaration() && !F.hasAvailableExternallyLinkage())
103       if (!F.isDiscardableIfUnused())
104         GlobalIsNeeded(&F);
105   }
106 
107   for (GlobalVariable &GV : M.globals()) {
108     Changed |= RemoveUnusedGlobalValue(GV);
109     // Externally visible & appending globals are needed, if they have an
110     // initializer.
111     if (!GV.isDeclaration() && !GV.hasAvailableExternallyLinkage())
112       if (!GV.isDiscardableIfUnused())
113         GlobalIsNeeded(&GV);
114   }
115 
116   for (GlobalAlias &GA : M.aliases()) {
117     Changed |= RemoveUnusedGlobalValue(GA);
118     // Externally visible aliases are needed.
119     if (!GA.isDiscardableIfUnused())
120       GlobalIsNeeded(&GA);
121   }
122 
123   for (GlobalIFunc &GIF : M.ifuncs()) {
124     Changed |= RemoveUnusedGlobalValue(GIF);
125     // Externally visible ifuncs are needed.
126     if (!GIF.isDiscardableIfUnused())
127       GlobalIsNeeded(&GIF);
128   }
129 
130   // Now that all globals which are needed are in the AliveGlobals set, we loop
131   // through the program, deleting those which are not alive.
132   //
133 
134   // The first pass is to drop initializers of global variables which are dead.
135   std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
136   for (GlobalVariable &GV : M.globals())
137     if (!AliveGlobals.count(&GV)) {
138       DeadGlobalVars.push_back(&GV);         // Keep track of dead globals
139       if (GV.hasInitializer()) {
140         Constant *Init = GV.getInitializer();
141         GV.setInitializer(nullptr);
142         if (isSafeToDestroyConstant(Init))
143           Init->destroyConstant();
144       }
145     }
146 
147   // The second pass drops the bodies of functions which are dead...
148   std::vector<Function *> DeadFunctions;
149   for (Function &F : M)
150     if (!AliveGlobals.count(&F)) {
151       DeadFunctions.push_back(&F);         // Keep track of dead globals
152       if (!F.isDeclaration())
153         F.deleteBody();
154     }
155 
156   // The third pass drops targets of aliases which are dead...
157   std::vector<GlobalAlias*> DeadAliases;
158   for (GlobalAlias &GA : M.aliases())
159     if (!AliveGlobals.count(&GA)) {
160       DeadAliases.push_back(&GA);
161       GA.setAliasee(nullptr);
162     }
163 
164   // The third pass drops targets of ifuncs which are dead...
165   std::vector<GlobalIFunc*> DeadIFuncs;
166   for (GlobalIFunc &GIF : M.ifuncs())
167     if (!AliveGlobals.count(&GIF)) {
168       DeadIFuncs.push_back(&GIF);
169       GIF.setResolver(nullptr);
170     }
171 
172   if (!DeadFunctions.empty()) {
173     // Now that all interferences have been dropped, delete the actual objects
174     // themselves.
175     for (Function *F : DeadFunctions) {
176       RemoveUnusedGlobalValue(*F);
177       M.getFunctionList().erase(F);
178     }
179     NumFunctions += DeadFunctions.size();
180     Changed = true;
181   }
182 
183   if (!DeadGlobalVars.empty()) {
184     for (GlobalVariable *GV : DeadGlobalVars) {
185       RemoveUnusedGlobalValue(*GV);
186       M.getGlobalList().erase(GV);
187     }
188     NumVariables += DeadGlobalVars.size();
189     Changed = true;
190   }
191 
192   // Now delete any dead aliases.
193   if (!DeadAliases.empty()) {
194     for (GlobalAlias *GA : DeadAliases) {
195       RemoveUnusedGlobalValue(*GA);
196       M.getAliasList().erase(GA);
197     }
198     NumAliases += DeadAliases.size();
199     Changed = true;
200   }
201 
202   // Now delete any dead aliases.
203   if (!DeadIFuncs.empty()) {
204     for (GlobalIFunc *GIF : DeadIFuncs) {
205       RemoveUnusedGlobalValue(*GIF);
206       M.getIFuncList().erase(GIF);
207     }
208     NumIFuncs += DeadIFuncs.size();
209     Changed = true;
210   }
211 
212   // Make sure that all memory is released
213   AliveGlobals.clear();
214   SeenConstants.clear();
215   ComdatMembers.clear();
216 
217   if (Changed)
218     return PreservedAnalyses::none();
219   return PreservedAnalyses::all();
220 }
221 
222 /// GlobalIsNeeded - the specific global value as needed, and
223 /// recursively mark anything that it uses as also needed.
224 void GlobalDCEPass::GlobalIsNeeded(GlobalValue *G) {
225   // If the global is already in the set, no need to reprocess it.
226   if (!AliveGlobals.insert(G).second)
227     return;
228 
229   if (Comdat *C = G->getComdat()) {
230     for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
231       GlobalIsNeeded(CM.second);
232   }
233 
234   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
235     // If this is a global variable, we must make sure to add any global values
236     // referenced by the initializer to the alive set.
237     if (GV->hasInitializer())
238       MarkUsedGlobalsAsNeeded(GV->getInitializer());
239   } else if (GlobalIndirectSymbol *GIS = dyn_cast<GlobalIndirectSymbol>(G)) {
240     // The target of a global alias or ifunc is needed.
241     MarkUsedGlobalsAsNeeded(GIS->getIndirectSymbol());
242   } else {
243     // Otherwise this must be a function object.  We have to scan the body of
244     // the function looking for constants and global values which are used as
245     // operands.  Any operands of these types must be processed to ensure that
246     // any globals used will be marked as needed.
247     Function *F = cast<Function>(G);
248 
249     for (Use &U : F->operands())
250       MarkUsedGlobalsAsNeeded(cast<Constant>(U.get()));
251 
252     for (BasicBlock &BB : *F)
253       for (Instruction &I : BB)
254         for (Use &U : I.operands())
255           if (GlobalValue *GV = dyn_cast<GlobalValue>(U))
256             GlobalIsNeeded(GV);
257           else if (Constant *C = dyn_cast<Constant>(U))
258             MarkUsedGlobalsAsNeeded(C);
259   }
260 }
261 
262 void GlobalDCEPass::MarkUsedGlobalsAsNeeded(Constant *C) {
263   if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
264     return GlobalIsNeeded(GV);
265 
266   // Loop over all of the operands of the constant, adding any globals they
267   // use to the list of needed globals.
268   for (Use &U : C->operands()) {
269     // If we've already processed this constant there's no need to do it again.
270     Constant *Op = dyn_cast<Constant>(U);
271     if (Op && SeenConstants.insert(Op).second)
272       MarkUsedGlobalsAsNeeded(Op);
273   }
274 }
275 
276 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
277 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
278 // If found, check to see if the constant pointer ref is safe to destroy, and if
279 // so, nuke it.  This will reduce the reference count on the global value, which
280 // might make it deader.
281 //
282 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
283   if (GV.use_empty())
284     return false;
285   GV.removeDeadConstantUsers();
286   return GV.use_empty();
287 }
288