StripSymbols.cpp revision 444a08cd6f21c5ef7fbb64eccc7ac6beba33e891
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/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Instructions.h"
27#include "llvm/Module.h"
28#include "llvm/Pass.h"
29#include "llvm/Analysis/DebugInfo.h"
30#include "llvm/ValueSymbolTable.h"
31#include "llvm/TypeSymbolTable.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/ADT/SmallPtrSet.h"
34using namespace llvm;
35
36namespace {
37  class StripSymbols : public ModulePass {
38    bool OnlyDebugInfo;
39  public:
40    static char ID; // Pass identification, replacement for typeid
41    explicit StripSymbols(bool ODI = false)
42      : ModulePass(&ID), OnlyDebugInfo(ODI) {}
43
44    virtual bool runOnModule(Module &M);
45
46    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47      AU.setPreservesAll();
48    }
49  };
50
51  class StripNonDebugSymbols : public ModulePass {
52  public:
53    static char ID; // Pass identification, replacement for typeid
54    explicit StripNonDebugSymbols()
55      : ModulePass(&ID) {}
56
57    virtual bool runOnModule(Module &M);
58
59    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60      AU.setPreservesAll();
61    }
62  };
63
64  class StripDebugDeclare : public ModulePass {
65  public:
66    static char ID; // Pass identification, replacement for typeid
67    explicit StripDebugDeclare()
68      : ModulePass(&ID) {}
69
70    virtual bool runOnModule(Module &M);
71
72    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73      AU.setPreservesAll();
74    }
75  };
76}
77
78char StripSymbols::ID = 0;
79static RegisterPass<StripSymbols>
80X("strip", "Strip all symbols from a module");
81
82ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
83  return new StripSymbols(OnlyDebugInfo);
84}
85
86char StripNonDebugSymbols::ID = 0;
87static RegisterPass<StripNonDebugSymbols>
88Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module");
89
90ModulePass *llvm::createStripNonDebugSymbolsPass() {
91  return new StripNonDebugSymbols();
92}
93
94char StripDebugDeclare::ID = 0;
95static RegisterPass<StripDebugDeclare>
96Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics");
97
98ModulePass *llvm::createStripDebugDeclarePass() {
99  return new StripDebugDeclare();
100}
101
102/// OnlyUsedBy - Return true if V is only used by Usr.
103static bool OnlyUsedBy(Value *V, Value *Usr) {
104  for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
105    User *U = *I;
106    if (U != Usr)
107      return false;
108  }
109  return true;
110}
111
112static void RemoveDeadConstant(Constant *C) {
113  assert(C->use_empty() && "Constant is not dead!");
114  SmallPtrSet<Constant*, 4> Operands;
115  for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
116    if (isa<DerivedType>(C->getOperand(i)->getType()) &&
117        OnlyUsedBy(C->getOperand(i), C))
118      Operands.insert(cast<Constant>(C->getOperand(i)));
119  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
120    if (!GV->hasLocalLinkage()) return;   // Don't delete non static globals.
121    GV->eraseFromParent();
122  }
123  else if (!isa<Function>(C))
124    if (isa<CompositeType>(C->getType()))
125      C->destroyConstant();
126
127  // If the constant referenced anything, see if we can delete it as well.
128  for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
129         OE = Operands.end(); OI != OE; ++OI)
130    RemoveDeadConstant(*OI);
131}
132
133// Strip the symbol table of its names.
134//
135static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
136  for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
137    Value *V = VI->getValue();
138    ++VI;
139    if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
140      if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
141        // Set name to "", removing from symbol table!
142        V->setName("");
143    }
144  }
145}
146
147// Strip the symbol table of its names.
148static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) {
149  for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) {
150    if (PreserveDbgInfo && StringRef(TI->first).startswith("llvm.dbg"))
151      ++TI;
152    else
153      ST.remove(TI++);
154  }
155}
156
157/// Find values that are marked as llvm.used.
158static void findUsedValues(GlobalVariable *LLVMUsed,
159                           SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
160  if (LLVMUsed == 0) return;
161  UsedValues.insert(LLVMUsed);
162
163  ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
164  if (Inits == 0) return;
165
166  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
167    if (GlobalValue *GV =
168          dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
169      UsedValues.insert(GV);
170}
171
172/// StripSymbolNames - Strip symbol names.
173static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
174
175  SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
176  findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
177  findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
178
179  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
180       I != E; ++I) {
181    if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
182      if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
183        I->setName("");     // Internal symbols can't participate in linkage
184  }
185
186  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
187    if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
188      if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
189        I->setName("");     // Internal symbols can't participate in linkage
190    StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
191  }
192
193  // Remove all names from types.
194  StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
195
196  return true;
197}
198
199// StripDebugInfo - Strip debug info in the module if it exists.
200// To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and
201// llvm.dbg.region.end calls, and any globals they point to if now dead.
202static bool StripDebugInfo(Module &M) {
203
204  bool Changed = false;
205
206  // Remove all of the calls to the debugger intrinsics, and remove them from
207  // the module.
208  if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
209    while (!Declare->use_empty()) {
210      CallInst *CI = cast<CallInst>(Declare->use_back());
211      CI->eraseFromParent();
212    }
213    Declare->eraseFromParent();
214    Changed = true;
215  }
216
217  if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
218    while (!DbgVal->use_empty()) {
219      CallInst *CI = cast<CallInst>(DbgVal->use_back());
220      CI->eraseFromParent();
221    }
222    DbgVal->eraseFromParent();
223    Changed = true;
224  }
225
226  for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
227         NME = M.named_metadata_end(); NMI != NME;) {
228    NamedMDNode *NMD = NMI;
229    ++NMI;
230    if (NMD->getName().startswith("llvm.dbg."))
231      NMD->eraseFromParent();
232  }
233
234  unsigned MDDbgKind = M.getMDKindID("dbg");
235  for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
236    for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
237         ++FI)
238      for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
239           ++BI) {
240        Changed = true; // FIXME: Only set if there was debug metadata.
241        BI->setMetadata(MDDbgKind, 0);
242      }
243
244  return Changed;
245}
246
247bool StripSymbols::runOnModule(Module &M) {
248  bool Changed = false;
249  Changed |= StripDebugInfo(M);
250  if (!OnlyDebugInfo)
251    Changed |= StripSymbolNames(M, false);
252  return Changed;
253}
254
255bool StripNonDebugSymbols::runOnModule(Module &M) {
256  return StripSymbolNames(M, true);
257}
258
259bool StripDebugDeclare::runOnModule(Module &M) {
260
261  Function *Declare = M.getFunction("llvm.dbg.declare");
262  std::vector<Constant*> DeadConstants;
263
264  if (Declare) {
265    while (!Declare->use_empty()) {
266      CallInst *CI = cast<CallInst>(Declare->use_back());
267      Value *Arg1 = CI->getArgOperand(0);
268      Value *Arg2 = CI->getArgOperand(1);
269      assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
270      CI->eraseFromParent();
271      if (Arg1->use_empty()) {
272        if (Constant *C = dyn_cast<Constant>(Arg1))
273          DeadConstants.push_back(C);
274        else
275          RecursivelyDeleteTriviallyDeadInstructions(Arg1);
276      }
277      if (Arg2->use_empty())
278        if (Constant *C = dyn_cast<Constant>(Arg2))
279          DeadConstants.push_back(C);
280    }
281    Declare->eraseFromParent();
282  }
283
284  while (!DeadConstants.empty()) {
285    Constant *C = DeadConstants.back();
286    DeadConstants.pop_back();
287    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
288      if (GV->hasLocalLinkage())
289        RemoveDeadConstant(GV);
290    } else
291      RemoveDeadConstant(C);
292  }
293
294  return true;
295}
296