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/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/Transforms/Utils/Local.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
37 class StripSymbols
: public ModulePass
{
40 static char ID
; // Pass identification, replacement for typeid
41 explicit StripSymbols(bool ODI
= false)
42 : ModulePass(ID
), OnlyDebugInfo(ODI
) {
43 initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
46 virtual bool runOnModule(Module
&M
);
48 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
53 class StripNonDebugSymbols
: public ModulePass
{
55 static char ID
; // Pass identification, replacement for typeid
56 explicit StripNonDebugSymbols()
58 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
61 virtual bool runOnModule(Module
&M
);
63 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
68 class StripDebugDeclare
: public ModulePass
{
70 static char ID
; // Pass identification, replacement for typeid
71 explicit StripDebugDeclare()
73 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
76 virtual bool runOnModule(Module
&M
);
78 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
83 class StripDeadDebugInfo
: public ModulePass
{
85 static char ID
; // Pass identification, replacement for typeid
86 explicit StripDeadDebugInfo()
88 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
91 virtual bool runOnModule(Module
&M
);
93 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
99 char StripSymbols::ID
= 0;
100 INITIALIZE_PASS(StripSymbols
, "strip",
101 "Strip all symbols from a module", false, false)
103 ModulePass
*llvm::createStripSymbolsPass(bool OnlyDebugInfo
) {
104 return new StripSymbols(OnlyDebugInfo
);
107 char StripNonDebugSymbols::ID
= 0;
108 INITIALIZE_PASS(StripNonDebugSymbols
, "strip-nondebug",
109 "Strip all symbols, except dbg symbols, from a module",
112 ModulePass
*llvm::createStripNonDebugSymbolsPass() {
113 return new StripNonDebugSymbols();
116 char StripDebugDeclare::ID
= 0;
117 INITIALIZE_PASS(StripDebugDeclare
, "strip-debug-declare",
118 "Strip all llvm.dbg.declare intrinsics", false, false)
120 ModulePass
*llvm::createStripDebugDeclarePass() {
121 return new StripDebugDeclare();
124 char StripDeadDebugInfo::ID
= 0;
125 INITIALIZE_PASS(StripDeadDebugInfo
, "strip-dead-debug-info",
126 "Strip debug info for unused symbols", false, false)
128 ModulePass
*llvm::createStripDeadDebugInfoPass() {
129 return new StripDeadDebugInfo();
132 /// OnlyUsedBy - Return true if V is only used by Usr.
133 static bool OnlyUsedBy(Value
*V
, Value
*Usr
) {
134 for(Value::use_iterator I
= V
->use_begin(), E
= V
->use_end(); I
!= E
; ++I
) {
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();
152 else if (!isa
<Function
>(C
))
153 if (isa
<CompositeType
>(C
->getType()))
154 C
->destroyConstant();
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
);
162 // Strip the symbol table of its names.
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();
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!
176 // Strip any named types of their names.
177 static void StripTypeNames(Module
&M
, bool PreserveDbgInfo
) {
178 std::vector
<StructType
*> StructTypes
;
179 M
.findUsedStructTypes(StructTypes
);
181 for (unsigned i
= 0, e
= StructTypes
.size(); i
!= e
; ++i
) {
182 StructType
*STy
= StructTypes
[i
];
183 if (STy
->isAnonymous() || STy
->getName().empty()) continue;
185 if (PreserveDbgInfo
&& STy
->getName().startswith("llvm.dbg"))
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
);
198 ConstantArray
*Inits
= dyn_cast
<ConstantArray
>(LLVMUsed
->getInitializer());
199 if (Inits
== 0) return;
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 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
336 /// printer to not emit usual symbol prefix before the symbol name is used then
337 /// return linkage name after skipping this special LLVM prefix.
338 static StringRef
getRealLinkageName(StringRef LinkageName
) {
340 if (LinkageName
.startswith(StringRef(&One
, 1)))
341 return LinkageName
.substr(1);
345 bool StripDeadDebugInfo::runOnModule(Module
&M
) {
346 bool Changed
= false;
348 // Debugging infomration is encoded in llvm IR using metadata. This is designed
349 // such a way that debug info for symbols preserved even if symbols are
350 // optimized away by the optimizer. This special pass removes debug info for
353 // llvm.dbg.gv keeps track of debug info for global variables.
354 if (NamedMDNode
*NMD
= M
.getNamedMetadata("llvm.dbg.gv")) {
355 SmallVector
<MDNode
*, 8> MDs
;
356 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
)
357 if (DIGlobalVariable(NMD
->getOperand(i
)).Verify())
358 MDs
.push_back(NMD
->getOperand(i
));
361 NMD
->eraseFromParent();
364 for (SmallVector
<MDNode
*, 8>::iterator I
= MDs
.begin(),
365 E
= MDs
.end(); I
!= E
; ++I
) {
366 GlobalVariable
*GV
= DIGlobalVariable(*I
).getGlobal();
367 if (GV
&& M
.getGlobalVariable(GV
->getName(), true)) {
369 NMD
= M
.getOrInsertNamedMetadata("llvm.dbg.gv");
377 // llvm.dbg.sp keeps track of debug info for subprograms.
378 if (NamedMDNode
*NMD
= M
.getNamedMetadata("llvm.dbg.sp")) {
379 SmallVector
<MDNode
*, 8> MDs
;
380 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
)
381 if (DISubprogram(NMD
->getOperand(i
)).Verify())
382 MDs
.push_back(NMD
->getOperand(i
));
385 NMD
->eraseFromParent();
388 for (SmallVector
<MDNode
*, 8>::iterator I
= MDs
.begin(),
389 E
= MDs
.end(); I
!= E
; ++I
) {
390 bool FnIsLive
= false;
391 if (Function
*F
= DISubprogram(*I
).getFunction())
392 if (M
.getFunction(F
->getName()))
396 NMD
= M
.getOrInsertNamedMetadata("llvm.dbg.sp");
399 // Remove llvm.dbg.lv.fnname named mdnode which may have been used
400 // to hold debug info for dead function's local variables.
401 StringRef FName
= DISubprogram(*I
).getLinkageName();
403 FName
= DISubprogram(*I
).getName();
404 if (NamedMDNode
*LVNMD
=
405 M
.getNamedMetadata(Twine("llvm.dbg.lv.",
406 getRealLinkageName(FName
))))
407 LVNMD
->eraseFromParent();