1 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The StripSymbols transformation implements code stripping. Specifically, it
13 // * names for virtual registers
14 // * symbols for internal globals and functions
15 // * debug information
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.
21 //===----------------------------------------------------------------------===//
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"
38 class StripSymbols : public ModulePass {
41 static char ID; // Pass identification, replacement for typeid
42 explicit StripSymbols(bool ODI = false)
43 : ModulePass(ID), OnlyDebugInfo(ODI) {
44 initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
47 bool runOnModule(Module &M) override;
49 void getAnalysisUsage(AnalysisUsage &AU) const override {
54 class StripNonDebugSymbols : public ModulePass {
56 static char ID; // Pass identification, replacement for typeid
57 explicit StripNonDebugSymbols()
59 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
62 bool runOnModule(Module &M) override;
64 void getAnalysisUsage(AnalysisUsage &AU) const override {
69 class StripDebugDeclare : public ModulePass {
71 static char ID; // Pass identification, replacement for typeid
72 explicit StripDebugDeclare()
74 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
77 bool runOnModule(Module &M) override;
79 void getAnalysisUsage(AnalysisUsage &AU) const override {
84 class StripDeadDebugInfo : public ModulePass {
86 static char ID; // Pass identification, replacement for typeid
87 explicit StripDeadDebugInfo()
89 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
92 bool runOnModule(Module &M) override;
94 void getAnalysisUsage(AnalysisUsage &AU) const override {
100 char StripSymbols::ID = 0;
101 INITIALIZE_PASS(StripSymbols, "strip",
102 "Strip all symbols from a module", false, false)
104 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
105 return new StripSymbols(OnlyDebugInfo);
108 char StripNonDebugSymbols::ID = 0;
109 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
110 "Strip all symbols, except dbg symbols, from a module",
113 ModulePass *llvm::createStripNonDebugSymbolsPass() {
114 return new StripNonDebugSymbols();
117 char StripDebugDeclare::ID = 0;
118 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
119 "Strip all llvm.dbg.declare intrinsics", false, false)
121 ModulePass *llvm::createStripDebugDeclarePass() {
122 return new StripDebugDeclare();
125 char StripDeadDebugInfo::ID = 0;
126 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
127 "Strip debug info for unused symbols", false, false)
129 ModulePass *llvm::createStripDeadDebugInfoPass() {
130 return new StripDeadDebugInfo();
133 /// OnlyUsedBy - Return true if V is only used by Usr.
134 static bool OnlyUsedBy(Value *V, Value *Usr) {
135 for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
143 static void RemoveDeadConstant(Constant *C) {
144 assert(C->use_empty() && "Constant is not dead!");
145 SmallPtrSet<Constant*, 4> Operands;
146 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
147 if (OnlyUsedBy(C->getOperand(i), C))
148 Operands.insert(cast<Constant>(C->getOperand(i)));
149 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
150 if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
151 GV->eraseFromParent();
153 else if (!isa<Function>(C))
154 if (isa<CompositeType>(C->getType()))
155 C->destroyConstant();
157 // If the constant referenced anything, see if we can delete it as well.
158 for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
159 OE = Operands.end(); OI != OE; ++OI)
160 RemoveDeadConstant(*OI);
163 // Strip the symbol table of its names.
165 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
166 for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
167 Value *V = VI->getValue();
169 if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
170 if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
171 // Set name to "", removing from symbol table!
177 // Strip any named types of their names.
178 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
179 TypeFinder StructTypes;
180 StructTypes.run(M, false);
182 for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
183 StructType *STy = StructTypes[i];
184 if (STy->isLiteral() || STy->getName().empty()) continue;
186 if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
193 /// Find values that are marked as llvm.used.
194 static void findUsedValues(GlobalVariable *LLVMUsed,
195 SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
196 if (LLVMUsed == 0) return;
197 UsedValues.insert(LLVMUsed);
199 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
201 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
202 if (GlobalValue *GV =
203 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
204 UsedValues.insert(GV);
207 /// StripSymbolNames - Strip symbol names.
208 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
210 SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
211 findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
212 findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
214 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
216 if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
217 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
218 I->setName(""); // Internal symbols can't participate in linkage
221 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
222 if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
223 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
224 I->setName(""); // Internal symbols can't participate in linkage
225 StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
228 // Remove all names from types.
229 StripTypeNames(M, PreserveDbgInfo);
234 bool StripSymbols::runOnModule(Module &M) {
235 bool Changed = false;
236 Changed |= StripDebugInfo(M);
238 Changed |= StripSymbolNames(M, false);
242 bool StripNonDebugSymbols::runOnModule(Module &M) {
243 return StripSymbolNames(M, true);
246 bool StripDebugDeclare::runOnModule(Module &M) {
248 Function *Declare = M.getFunction("llvm.dbg.declare");
249 std::vector<Constant*> DeadConstants;
252 while (!Declare->use_empty()) {
253 CallInst *CI = cast<CallInst>(Declare->use_back());
254 Value *Arg1 = CI->getArgOperand(0);
255 Value *Arg2 = CI->getArgOperand(1);
256 assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
257 CI->eraseFromParent();
258 if (Arg1->use_empty()) {
259 if (Constant *C = dyn_cast<Constant>(Arg1))
260 DeadConstants.push_back(C);
262 RecursivelyDeleteTriviallyDeadInstructions(Arg1);
264 if (Arg2->use_empty())
265 if (Constant *C = dyn_cast<Constant>(Arg2))
266 DeadConstants.push_back(C);
268 Declare->eraseFromParent();
271 while (!DeadConstants.empty()) {
272 Constant *C = DeadConstants.back();
273 DeadConstants.pop_back();
274 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
275 if (GV->hasLocalLinkage())
276 RemoveDeadConstant(GV);
278 RemoveDeadConstant(C);
284 /// Remove any debug info for global variables/functions in the given module for
285 /// which said global variable/function no longer exists (i.e. is null).
287 /// Debugging information is encoded in llvm IR using metadata. This is designed
288 /// such a way that debug info for symbols preserved even if symbols are
289 /// optimized away by the optimizer. This special pass removes debug info for
291 bool StripDeadDebugInfo::runOnModule(Module &M) {
292 bool Changed = false;
294 LLVMContext &C = M.getContext();
296 // Find all debug info in F. This is actually overkill in terms of what we
297 // want to do, but we want to try and be as resilient as possible in the face
298 // of potential debug info changes by using the formal interfaces given to us
299 // as much as possible.
303 // For each compile unit, find the live set of global variables/functions and
304 // replace the current list of potentially dead global variables/functions
305 // with the live list.
306 SmallVector<Value *, 64> LiveGlobalVariables;
307 SmallVector<Value *, 64> LiveSubprograms;
308 DenseSet<const MDNode *> VisitedSet;
310 for (DebugInfoFinder::iterator CI = F.compile_unit_begin(),
311 CE = F.compile_unit_end(); CI != CE; ++CI) {
312 // Create our compile unit.
313 DICompileUnit DIC(*CI);
314 assert(DIC.Verify() && "DIC must verify as a DICompileUnit.");
316 // Create our live subprogram list.
317 DIArray SPs = DIC.getSubprograms();
318 bool SubprogramChange = false;
319 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
320 DISubprogram DISP(SPs.getElement(i));
321 assert(DISP.Verify() && "DISP must verify as a DISubprogram.");
323 // Make sure we visit each subprogram only once.
324 if (!VisitedSet.insert(DISP).second)
327 // If the function referenced by DISP is not null, the function is live.
328 if (DISP.getFunction())
329 LiveSubprograms.push_back(DISP);
331 SubprogramChange = true;
334 // Create our live global variable list.
335 DIArray GVs = DIC.getGlobalVariables();
336 bool GlobalVariableChange = false;
337 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
338 DIGlobalVariable DIG(GVs.getElement(i));
339 assert(DIG.Verify() && "DIG must verify as DIGlobalVariable.");
341 // Make sure we only visit each global variable only once.
342 if (!VisitedSet.insert(DIG).second)
345 // If the global variable referenced by DIG is not null, the global
348 LiveGlobalVariables.push_back(DIG);
350 GlobalVariableChange = true;
353 // If we found dead subprograms or global variables, replace the current
354 // subprogram list/global variable list with our new live subprogram/global
356 if (SubprogramChange) {
357 // Make sure that 9 is still the index of the subprograms. This is to make
358 // sure that an assert is hit if the location of the subprogram array
359 // changes. This is just to make sure that this is updated if such an
361 assert(DIC->getNumOperands() >= 10 &&
362 SPs == DIC->getOperand(9) &&
363 "DICompileUnits is expected to store Subprograms in operand "
365 DIC->replaceOperandWith(9, MDNode::get(C, LiveSubprograms));
369 if (GlobalVariableChange) {
370 // Make sure that 10 is still the index of global variables. This is to
371 // make sure that an assert is hit if the location of the subprogram array
372 // changes. This is just to make sure that this index is updated if such
374 assert(DIC->getNumOperands() >= 11 &&
375 GVs == DIC->getOperand(10) &&
376 "DICompileUnits is expected to store Global Variables in operand "
378 DIC->replaceOperandWith(10, MDNode::get(C, LiveGlobalVariables));
382 // Reset lists for the next iteration.
383 LiveSubprograms.clear();
384 LiveGlobalVariables.clear();