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/ADT/SmallPtrSet.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/TypeFinder.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Transforms/IPO.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 bool runOnModule(Module &M) override;
48 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 class StripNonDebugSymbols : public ModulePass {
55 static char ID; // Pass identification, replacement for typeid
56 explicit StripNonDebugSymbols()
58 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
61 bool runOnModule(Module &M) override;
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
68 class StripDebugDeclare : public ModulePass {
70 static char ID; // Pass identification, replacement for typeid
71 explicit StripDebugDeclare()
73 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
76 bool runOnModule(Module &M) override;
78 void getAnalysisUsage(AnalysisUsage &AU) const override {
83 class StripDeadDebugInfo : public ModulePass {
85 static char ID; // Pass identification, replacement for typeid
86 explicit StripDeadDebugInfo()
88 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
91 bool runOnModule(Module &M) override;
93 void getAnalysisUsage(AnalysisUsage &AU) const override {
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 (User *U : V->users())
141 static void RemoveDeadConstant(Constant *C) {
142 assert(C->use_empty() && "Constant is not dead!");
143 SmallPtrSet<Constant*, 4> Operands;
144 for (Value *Op : C->operands())
145 if (OnlyUsedBy(Op, C))
146 Operands.insert(cast<Constant>(Op));
147 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
148 if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
149 GV->eraseFromParent();
151 else if (!isa<Function>(C))
152 if (isa<CompositeType>(C->getType()))
153 C->destroyConstant();
155 // If the constant referenced anything, see if we can delete it as well.
156 for (Constant *O : Operands)
157 RemoveDeadConstant(O);
160 // Strip the symbol table of its names.
162 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
163 for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
164 Value *V = VI->getValue();
166 if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
167 if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
168 // Set name to "", removing from symbol table!
174 // Strip any named types of their names.
175 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
176 TypeFinder StructTypes;
177 StructTypes.run(M, false);
179 for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
180 StructType *STy = StructTypes[i];
181 if (STy->isLiteral() || STy->getName().empty()) continue;
183 if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
190 /// Find values that are marked as llvm.used.
191 static void findUsedValues(GlobalVariable *LLVMUsed,
192 SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
193 if (!LLVMUsed) return;
194 UsedValues.insert(LLVMUsed);
196 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
198 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
199 if (GlobalValue *GV =
200 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
201 UsedValues.insert(GV);
204 /// StripSymbolNames - Strip symbol names.
205 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
207 SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
208 findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
209 findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
211 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
213 if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
214 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
215 I->setName(""); // Internal symbols can't participate in linkage
218 for (Function &I : M) {
219 if (I.hasLocalLinkage() && llvmUsedValues.count(&I) == 0)
220 if (!PreserveDbgInfo || !I.getName().startswith("llvm.dbg"))
221 I.setName(""); // Internal symbols can't participate in linkage
222 if (auto *Symtab = I.getValueSymbolTable())
223 StripSymtab(*Symtab, PreserveDbgInfo);
226 // Remove all names from types.
227 StripTypeNames(M, PreserveDbgInfo);
232 bool StripSymbols::runOnModule(Module &M) {
236 bool Changed = false;
237 Changed |= StripDebugInfo(M);
239 Changed |= StripSymbolNames(M, false);
243 bool StripNonDebugSymbols::runOnModule(Module &M) {
247 return StripSymbolNames(M, true);
250 bool StripDebugDeclare::runOnModule(Module &M) {
254 Function *Declare = M.getFunction("llvm.dbg.declare");
255 std::vector<Constant*> DeadConstants;
258 while (!Declare->use_empty()) {
259 CallInst *CI = cast<CallInst>(Declare->user_back());
260 Value *Arg1 = CI->getArgOperand(0);
261 Value *Arg2 = CI->getArgOperand(1);
262 assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
263 CI->eraseFromParent();
264 if (Arg1->use_empty()) {
265 if (Constant *C = dyn_cast<Constant>(Arg1))
266 DeadConstants.push_back(C);
268 RecursivelyDeleteTriviallyDeadInstructions(Arg1);
270 if (Arg2->use_empty())
271 if (Constant *C = dyn_cast<Constant>(Arg2))
272 DeadConstants.push_back(C);
274 Declare->eraseFromParent();
277 while (!DeadConstants.empty()) {
278 Constant *C = DeadConstants.back();
279 DeadConstants.pop_back();
280 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
281 if (GV->hasLocalLinkage())
282 RemoveDeadConstant(GV);
284 RemoveDeadConstant(C);
290 /// Remove any debug info for global variables/functions in the given module for
291 /// which said global variable/function no longer exists (i.e. is null).
293 /// Debugging information is encoded in llvm IR using metadata. This is designed
294 /// such a way that debug info for symbols preserved even if symbols are
295 /// optimized away by the optimizer. This special pass removes debug info for
297 bool StripDeadDebugInfo::runOnModule(Module &M) {
301 bool Changed = false;
303 LLVMContext &C = M.getContext();
305 // Find all debug info in F. This is actually overkill in terms of what we
306 // want to do, but we want to try and be as resilient as possible in the face
307 // of potential debug info changes by using the formal interfaces given to us
308 // as much as possible.
312 // For each compile unit, find the live set of global variables/functions and
313 // replace the current list of potentially dead global variables/functions
314 // with the live list.
315 SmallVector<Metadata *, 64> LiveGlobalVariables;
316 DenseSet<DIGlobalVariableExpression *> VisitedSet;
318 std::set<DIGlobalVariableExpression *> LiveGVs;
319 for (GlobalVariable &GV : M.globals()) {
320 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
321 GV.getDebugInfo(GVEs);
322 for (auto *GVE : GVEs)
326 std::set<DICompileUnit *> LiveCUs;
327 // Any CU referenced from a subprogram is live.
328 for (DISubprogram *SP : F.subprograms()) {
330 LiveCUs.insert(SP->getUnit());
333 bool HasDeadCUs = false;
334 for (DICompileUnit *DIC : F.compile_units()) {
335 // Create our live global variable list.
336 bool GlobalVariableChange = false;
337 for (auto *DIG : DIC->getGlobalVariables()) {
338 if (DIG->getExpression() && DIG->getExpression()->isConstant())
341 // Make sure we only visit each global variable only once.
342 if (!VisitedSet.insert(DIG).second)
345 // If a global variable references DIG, the global variable is live.
346 if (LiveGVs.count(DIG))
347 LiveGlobalVariables.push_back(DIG);
349 GlobalVariableChange = true;
352 if (!LiveGlobalVariables.empty())
354 else if (!LiveCUs.count(DIC))
357 // If we found dead global variables, replace the current global
358 // variable list with our new live global variable list.
359 if (GlobalVariableChange) {
360 DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
364 // Reset lists for the next iteration.
365 LiveGlobalVariables.clear();
369 // Delete the old node and replace it with a new one
370 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
371 NMD->clearOperands();
372 if (!LiveCUs.empty()) {
373 for (DICompileUnit *CU : LiveCUs)