[C++11] Add range based accessors for the Use-Def chain of a Value.
[oota-llvm.git] / lib / Transforms / IPO / StripSymbols.cpp
1 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
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 // The StripSymbols transformation implements code stripping. Specifically, it
11 // can delete:
12 //
13 //   * names for virtual registers
14 //   * symbols for internal globals and functions
15 //   * debug information
16 //
17 // Note that this transformation makes code much less readable, so it should
18 // only be used in situations where the 'strip' utility would be used, such as
19 // reducing code size or making it harder to reverse engineer code.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/TypeFinder.h"
32 #include "llvm/IR/ValueSymbolTable.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 using namespace llvm;
36
37 namespace {
38   class StripSymbols : public ModulePass {
39     bool OnlyDebugInfo;
40   public:
41     static char ID; // Pass identification, replacement for typeid
42     explicit StripSymbols(bool ODI = false)
43       : ModulePass(ID), OnlyDebugInfo(ODI) {
44         initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
45       }
46
47     bool runOnModule(Module &M) override;
48
49     void getAnalysisUsage(AnalysisUsage &AU) const override {
50       AU.setPreservesAll();
51     }
52   };
53
54   class StripNonDebugSymbols : public ModulePass {
55   public:
56     static char ID; // Pass identification, replacement for typeid
57     explicit StripNonDebugSymbols()
58       : ModulePass(ID) {
59         initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
60       }
61
62     bool runOnModule(Module &M) override;
63
64     void getAnalysisUsage(AnalysisUsage &AU) const override {
65       AU.setPreservesAll();
66     }
67   };
68
69   class StripDebugDeclare : public ModulePass {
70   public:
71     static char ID; // Pass identification, replacement for typeid
72     explicit StripDebugDeclare()
73       : ModulePass(ID) {
74         initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
75       }
76
77     bool runOnModule(Module &M) override;
78
79     void getAnalysisUsage(AnalysisUsage &AU) const override {
80       AU.setPreservesAll();
81     }
82   };
83
84   class StripDeadDebugInfo : public ModulePass {
85   public:
86     static char ID; // Pass identification, replacement for typeid
87     explicit StripDeadDebugInfo()
88       : ModulePass(ID) {
89         initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
90       }
91
92     bool runOnModule(Module &M) override;
93
94     void getAnalysisUsage(AnalysisUsage &AU) const override {
95       AU.setPreservesAll();
96     }
97   };
98 }
99
100 char StripSymbols::ID = 0;
101 INITIALIZE_PASS(StripSymbols, "strip",
102                 "Strip all symbols from a module", false, false)
103
104 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
105   return new StripSymbols(OnlyDebugInfo);
106 }
107
108 char StripNonDebugSymbols::ID = 0;
109 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
110                 "Strip all symbols, except dbg symbols, from a module",
111                 false, false)
112
113 ModulePass *llvm::createStripNonDebugSymbolsPass() {
114   return new StripNonDebugSymbols();
115 }
116
117 char StripDebugDeclare::ID = 0;
118 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
119                 "Strip all llvm.dbg.declare intrinsics", false, false)
120
121 ModulePass *llvm::createStripDebugDeclarePass() {
122   return new StripDebugDeclare();
123 }
124
125 char StripDeadDebugInfo::ID = 0;
126 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
127                 "Strip debug info for unused symbols", false, false)
128
129 ModulePass *llvm::createStripDeadDebugInfoPass() {
130   return new StripDeadDebugInfo();
131 }
132
133 /// OnlyUsedBy - Return true if V is only used by Usr.
134 static bool OnlyUsedBy(Value *V, Value *Usr) {
135   for (User *U : V->users())
136     if (U != Usr)
137       return false;
138
139   return true;
140 }
141
142 static void RemoveDeadConstant(Constant *C) {
143   assert(C->use_empty() && "Constant is not dead!");
144   SmallPtrSet<Constant*, 4> Operands;
145   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
146     if (OnlyUsedBy(C->getOperand(i), C))
147       Operands.insert(cast<Constant>(C->getOperand(i)));
148   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
149     if (!GV->hasLocalLinkage()) return;   // Don't delete non-static globals.
150     GV->eraseFromParent();
151   }
152   else if (!isa<Function>(C))
153     if (isa<CompositeType>(C->getType()))
154       C->destroyConstant();
155
156   // If the constant referenced anything, see if we can delete it as well.
157   for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
158          OE = Operands.end(); OI != OE; ++OI)
159     RemoveDeadConstant(*OI);
160 }
161
162 // Strip the symbol table of its names.
163 //
164 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
165   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
166     Value *V = VI->getValue();
167     ++VI;
168     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
169       if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
170         // Set name to "", removing from symbol table!
171         V->setName("");
172     }
173   }
174 }
175
176 // Strip any named types of their names.
177 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
178   TypeFinder StructTypes;
179   StructTypes.run(M, false);
180
181   for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
182     StructType *STy = StructTypes[i];
183     if (STy->isLiteral() || STy->getName().empty()) continue;
184
185     if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
186       continue;
187
188     STy->setName("");
189   }
190 }
191
192 /// Find values that are marked as llvm.used.
193 static void findUsedValues(GlobalVariable *LLVMUsed,
194                            SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
195   if (LLVMUsed == 0) return;
196   UsedValues.insert(LLVMUsed);
197
198   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
199
200   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
201     if (GlobalValue *GV =
202           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
203       UsedValues.insert(GV);
204 }
205
206 /// StripSymbolNames - Strip symbol names.
207 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
208
209   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
210   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
211   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
212
213   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
214        I != E; ++I) {
215     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
216       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
217         I->setName("");     // Internal symbols can't participate in linkage
218   }
219
220   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
221     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
222       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
223         I->setName("");     // Internal symbols can't participate in linkage
224     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
225   }
226
227   // Remove all names from types.
228   StripTypeNames(M, PreserveDbgInfo);
229
230   return true;
231 }
232
233 bool StripSymbols::runOnModule(Module &M) {
234   bool Changed = false;
235   Changed |= StripDebugInfo(M);
236   if (!OnlyDebugInfo)
237     Changed |= StripSymbolNames(M, false);
238   return Changed;
239 }
240
241 bool StripNonDebugSymbols::runOnModule(Module &M) {
242   return StripSymbolNames(M, true);
243 }
244
245 bool StripDebugDeclare::runOnModule(Module &M) {
246
247   Function *Declare = M.getFunction("llvm.dbg.declare");
248   std::vector<Constant*> DeadConstants;
249
250   if (Declare) {
251     while (!Declare->use_empty()) {
252       CallInst *CI = cast<CallInst>(Declare->user_back());
253       Value *Arg1 = CI->getArgOperand(0);
254       Value *Arg2 = CI->getArgOperand(1);
255       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
256       CI->eraseFromParent();
257       if (Arg1->use_empty()) {
258         if (Constant *C = dyn_cast<Constant>(Arg1))
259           DeadConstants.push_back(C);
260         else
261           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
262       }
263       if (Arg2->use_empty())
264         if (Constant *C = dyn_cast<Constant>(Arg2))
265           DeadConstants.push_back(C);
266     }
267     Declare->eraseFromParent();
268   }
269
270   while (!DeadConstants.empty()) {
271     Constant *C = DeadConstants.back();
272     DeadConstants.pop_back();
273     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
274       if (GV->hasLocalLinkage())
275         RemoveDeadConstant(GV);
276     } else
277       RemoveDeadConstant(C);
278   }
279
280   return true;
281 }
282
283 /// Remove any debug info for global variables/functions in the given module for
284 /// which said global variable/function no longer exists (i.e. is null).
285 ///
286 /// Debugging information is encoded in llvm IR using metadata. This is designed
287 /// such a way that debug info for symbols preserved even if symbols are
288 /// optimized away by the optimizer. This special pass removes debug info for
289 /// such symbols.
290 bool StripDeadDebugInfo::runOnModule(Module &M) {
291   bool Changed = false;
292
293   LLVMContext &C = M.getContext();
294
295   // Find all debug info in F. This is actually overkill in terms of what we
296   // want to do, but we want to try and be as resilient as possible in the face
297   // of potential debug info changes by using the formal interfaces given to us
298   // as much as possible.
299   DebugInfoFinder F;
300   F.processModule(M);
301
302   // For each compile unit, find the live set of global variables/functions and
303   // replace the current list of potentially dead global variables/functions
304   // with the live list.
305   SmallVector<Value *, 64> LiveGlobalVariables;
306   SmallVector<Value *, 64> LiveSubprograms;
307   DenseSet<const MDNode *> VisitedSet;
308
309   for (DebugInfoFinder::iterator CI = F.compile_unit_begin(),
310          CE = F.compile_unit_end(); CI != CE; ++CI) {
311     // Create our compile unit.
312     DICompileUnit DIC(*CI);
313     assert(DIC.Verify() && "DIC must verify as a DICompileUnit.");
314
315     // Create our live subprogram list.
316     DIArray SPs = DIC.getSubprograms();
317     bool SubprogramChange = false;
318     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
319       DISubprogram DISP(SPs.getElement(i));
320       assert(DISP.Verify() && "DISP must verify as a DISubprogram.");
321
322       // Make sure we visit each subprogram only once.
323       if (!VisitedSet.insert(DISP).second)
324         continue;
325
326       // If the function referenced by DISP is not null, the function is live.
327       if (DISP.getFunction())
328         LiveSubprograms.push_back(DISP);
329       else
330         SubprogramChange = true;
331     }
332
333     // Create our live global variable list.
334     DIArray GVs = DIC.getGlobalVariables();
335     bool GlobalVariableChange = false;
336     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
337       DIGlobalVariable DIG(GVs.getElement(i));
338       assert(DIG.Verify() && "DIG must verify as DIGlobalVariable.");
339
340       // Make sure we only visit each global variable only once.
341       if (!VisitedSet.insert(DIG).second)
342         continue;
343
344       // If the global variable referenced by DIG is not null, the global
345       // variable is live.
346       if (DIG.getGlobal())
347         LiveGlobalVariables.push_back(DIG);
348       else
349         GlobalVariableChange = true;
350     }
351
352     // If we found dead subprograms or global variables, replace the current
353     // subprogram list/global variable list with our new live subprogram/global
354     // variable list.
355     if (SubprogramChange) {
356       // Make sure that 9 is still the index of the subprograms. This is to make
357       // sure that an assert is hit if the location of the subprogram array
358       // changes. This is just to make sure that this is updated if such an
359       // event occurs.
360       assert(DIC->getNumOperands() >= 10 &&
361              SPs == DIC->getOperand(9) &&
362              "DICompileUnits is expected to store Subprograms in operand "
363              "9.");
364       DIC->replaceOperandWith(9, MDNode::get(C, LiveSubprograms));
365       Changed = true;
366     }
367
368     if (GlobalVariableChange) {
369       // Make sure that 10 is still the index of global variables. This is to
370       // make sure that an assert is hit if the location of the subprogram array
371       // changes. This is just to make sure that this index is updated if such
372       // an event occurs.
373       assert(DIC->getNumOperands() >= 11 &&
374              GVs == DIC->getOperand(10) &&
375              "DICompileUnits is expected to store Global Variables in operand "
376              "10.");
377       DIC->replaceOperandWith(10, MDNode::get(C, LiveGlobalVariables));
378       Changed = true;
379     }
380
381     // Reset lists for the next iteration.
382     LiveSubprograms.clear();
383     LiveGlobalVariables.clear();
384   }
385
386   return Changed;
387 }