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/DebugInfo.h"
27 #include "llvm/IR/Constants.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 virtual bool runOnModule(Module &M);
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 class StripNonDebugSymbols : public ModulePass {
56 static char ID; // Pass identification, replacement for typeid
57 explicit StripNonDebugSymbols()
59 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
62 virtual bool runOnModule(Module &M);
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 class StripDebugDeclare : public ModulePass {
71 static char ID; // Pass identification, replacement for typeid
72 explicit StripDebugDeclare()
74 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
77 virtual bool runOnModule(Module &M);
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 class StripDeadDebugInfo : public ModulePass {
86 static char ID; // Pass identification, replacement for typeid
87 explicit StripDeadDebugInfo()
89 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
92 virtual bool runOnModule(Module &M);
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
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 // StripDebugInfo - Strip debug info in the module if it exists.
235 // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and
236 // llvm.dbg.region.end calls, and any globals they point to if now dead.
237 static bool StripDebugInfo(Module &M) {
239 bool Changed = false;
241 // Remove all of the calls to the debugger intrinsics, and remove them from
243 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
244 while (!Declare->use_empty()) {
245 CallInst *CI = cast<CallInst>(Declare->use_back());
246 CI->eraseFromParent();
248 Declare->eraseFromParent();
252 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
253 while (!DbgVal->use_empty()) {
254 CallInst *CI = cast<CallInst>(DbgVal->use_back());
255 CI->eraseFromParent();
257 DbgVal->eraseFromParent();
261 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
262 NME = M.named_metadata_end(); NMI != NME;) {
263 NamedMDNode *NMD = NMI;
265 if (NMD->getName().startswith("llvm.dbg.")) {
266 NMD->eraseFromParent();
271 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
272 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
274 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
276 if (!BI->getDebugLoc().isUnknown()) {
278 BI->setDebugLoc(DebugLoc());
285 bool StripSymbols::runOnModule(Module &M) {
286 bool Changed = false;
287 Changed |= StripDebugInfo(M);
289 Changed |= StripSymbolNames(M, false);
293 bool StripNonDebugSymbols::runOnModule(Module &M) {
294 return StripSymbolNames(M, true);
297 bool StripDebugDeclare::runOnModule(Module &M) {
299 Function *Declare = M.getFunction("llvm.dbg.declare");
300 std::vector<Constant*> DeadConstants;
303 while (!Declare->use_empty()) {
304 CallInst *CI = cast<CallInst>(Declare->use_back());
305 Value *Arg1 = CI->getArgOperand(0);
306 Value *Arg2 = CI->getArgOperand(1);
307 assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
308 CI->eraseFromParent();
309 if (Arg1->use_empty()) {
310 if (Constant *C = dyn_cast<Constant>(Arg1))
311 DeadConstants.push_back(C);
313 RecursivelyDeleteTriviallyDeadInstructions(Arg1);
315 if (Arg2->use_empty())
316 if (Constant *C = dyn_cast<Constant>(Arg2))
317 DeadConstants.push_back(C);
319 Declare->eraseFromParent();
322 while (!DeadConstants.empty()) {
323 Constant *C = DeadConstants.back();
324 DeadConstants.pop_back();
325 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
326 if (GV->hasLocalLinkage())
327 RemoveDeadConstant(GV);
329 RemoveDeadConstant(C);
335 bool StripDeadDebugInfo::runOnModule(Module &M) {
336 bool Changed = false;
338 // Debugging infomration is encoded in llvm IR using metadata. This is designed
339 // such a way that debug info for symbols preserved even if symbols are
340 // optimized away by the optimizer. This special pass removes debug info for
343 // llvm.dbg.gv keeps track of debug info for global variables.
344 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
345 SmallVector<MDNode *, 8> MDs;
346 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
347 if (NMD->getOperand(i)) {
348 assert(DIGlobalVariable(NMD->getOperand(i)).isGlobalVariable() &&
349 "A MDNode in llvm.dbg.gv should be a DIGlobalVariable.");
350 MDs.push_back(NMD->getOperand(i));
354 NMD->eraseFromParent();
357 for (SmallVectorImpl<MDNode *>::iterator I = MDs.begin(),
358 E = MDs.end(); I != E; ++I) {
359 GlobalVariable *GV = DIGlobalVariable(*I).getGlobal();
360 if (GV && M.getGlobalVariable(GV->getName(), true)) {
362 NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
370 // llvm.dbg.sp keeps track of debug info for subprograms.
371 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp")) {
372 SmallVector<MDNode *, 8> MDs;
373 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
374 if (NMD->getOperand(i)) {
375 assert(DISubprogram(NMD->getOperand(i)).isSubprogram() &&
376 "A MDNode in llvm.dbg.sp should be a DISubprogram.");
377 MDs.push_back(NMD->getOperand(i));
381 NMD->eraseFromParent();
384 for (SmallVectorImpl<MDNode *>::iterator I = MDs.begin(),
385 E = MDs.end(); I != E; ++I) {
386 bool FnIsLive = false;
387 if (Function *F = DISubprogram(*I).getFunction())
388 if (M.getFunction(F->getName()))
392 NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
395 // Remove llvm.dbg.lv.fnname named mdnode which may have been used
396 // to hold debug info for dead function's local variables.
397 StringRef FName = DISubprogram(*I).getLinkageName();
399 FName = DISubprogram(*I).getName();
400 if (NamedMDNode *LVNMD = M.getNamedMetadata(
401 "llvm.dbg.lv." + Function::getRealLinkageName(FName)))
402 LVNMD->eraseFromParent();