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"
35using namespace llvm;
36
37namespace {
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
100char StripSymbols::ID = 0;
101INITIALIZE_PASS(StripSymbols, "strip",
102                "Strip all symbols from a module", false, false)
103
104ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
105  return new StripSymbols(OnlyDebugInfo);
106}
107
108char StripNonDebugSymbols::ID = 0;
109INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
110                "Strip all symbols, except dbg symbols, from a module",
111                false, false)
112
113ModulePass *llvm::createStripNonDebugSymbolsPass() {
114  return new StripNonDebugSymbols();
115}
116
117char StripDebugDeclare::ID = 0;
118INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
119                "Strip all llvm.dbg.declare intrinsics", false, false)
120
121ModulePass *llvm::createStripDebugDeclarePass() {
122  return new StripDebugDeclare();
123}
124
125char StripDeadDebugInfo::ID = 0;
126INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
127                "Strip debug info for unused symbols", false, false)
128
129ModulePass *llvm::createStripDeadDebugInfoPass() {
130  return new StripDeadDebugInfo();
131}
132
133/// OnlyUsedBy - Return true if V is only used by Usr.
134static 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
142static 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//
164static 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.
177static 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.
193static void findUsedValues(GlobalVariable *LLVMUsed,
194                           SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
195  if (!LLVMUsed) 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.
207static 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
233bool 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
241bool StripNonDebugSymbols::runOnModule(Module &M) {
242  return StripSymbolNames(M, true);
243}
244
245bool 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.
290bool 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 (DICompileUnit DIC : F.compile_units()) {
310    assert(DIC.Verify() && "DIC must verify as a DICompileUnit.");
311
312    // Create our live subprogram list.
313    DIArray SPs = DIC.getSubprograms();
314    bool SubprogramChange = false;
315    for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
316      DISubprogram DISP(SPs.getElement(i));
317      assert(DISP.Verify() && "DISP must verify as a DISubprogram.");
318
319      // Make sure we visit each subprogram only once.
320      if (!VisitedSet.insert(DISP).second)
321        continue;
322
323      // If the function referenced by DISP is not null, the function is live.
324      if (DISP.getFunction())
325        LiveSubprograms.push_back(DISP);
326      else
327        SubprogramChange = true;
328    }
329
330    // Create our live global variable list.
331    DIArray GVs = DIC.getGlobalVariables();
332    bool GlobalVariableChange = false;
333    for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
334      DIGlobalVariable DIG(GVs.getElement(i));
335      assert(DIG.Verify() && "DIG must verify as DIGlobalVariable.");
336
337      // Make sure we only visit each global variable only once.
338      if (!VisitedSet.insert(DIG).second)
339        continue;
340
341      // If the global variable referenced by DIG is not null, the global
342      // variable is live.
343      if (DIG.getGlobal())
344        LiveGlobalVariables.push_back(DIG);
345      else
346        GlobalVariableChange = true;
347    }
348
349    // If we found dead subprograms or global variables, replace the current
350    // subprogram list/global variable list with our new live subprogram/global
351    // variable list.
352    if (SubprogramChange) {
353      // Make sure that 9 is still the index of the subprograms. This is to make
354      // sure that an assert is hit if the location of the subprogram array
355      // changes. This is just to make sure that this is updated if such an
356      // event occurs.
357      assert(DIC->getNumOperands() >= 10 &&
358             SPs == DIC->getOperand(9) &&
359             "DICompileUnits is expected to store Subprograms in operand "
360             "9.");
361      DIC->replaceOperandWith(9, MDNode::get(C, LiveSubprograms));
362      Changed = true;
363    }
364
365    if (GlobalVariableChange) {
366      // Make sure that 10 is still the index of global variables. This is to
367      // make sure that an assert is hit if the location of the subprogram array
368      // changes. This is just to make sure that this index is updated if such
369      // an event occurs.
370      assert(DIC->getNumOperands() >= 11 &&
371             GVs == DIC->getOperand(10) &&
372             "DICompileUnits is expected to store Global Variables in operand "
373             "10.");
374      DIC->replaceOperandWith(10, MDNode::get(C, LiveGlobalVariables));
375      Changed = true;
376    }
377
378    // Reset lists for the next iteration.
379    LiveSubprograms.clear();
380    LiveGlobalVariables.clear();
381  }
382
383  return Changed;
384}
385