Return Changed. This required setting Changed if dbg metadata
[oota-llvm.git] / lib / Transforms / IPO / StripSymbols.cpp
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/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/TypeSymbolTable.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 using namespace llvm;
35
36 namespace {
37   class StripSymbols : public ModulePass {
38     bool OnlyDebugInfo;
39   public:
40     static char ID; // Pass identification, replacement for typeid
41     explicit StripSymbols(bool ODI = false) 
42       : ModulePass(&ID), OnlyDebugInfo(ODI) {}
43
44     virtual bool runOnModule(Module &M);
45
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.setPreservesAll();
48     }
49   };
50
51   class StripNonDebugSymbols : public ModulePass {
52   public:
53     static char ID; // Pass identification, replacement for typeid
54     explicit StripNonDebugSymbols()
55       : ModulePass(&ID) {}
56
57     virtual bool runOnModule(Module &M);
58
59     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60       AU.setPreservesAll();
61     }
62   };
63
64   class StripDebugDeclare : public ModulePass {
65   public:
66     static char ID; // Pass identification, replacement for typeid
67     explicit StripDebugDeclare()
68       : ModulePass(&ID) {}
69
70     virtual bool runOnModule(Module &M);
71
72     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73       AU.setPreservesAll();
74     }
75   };
76 }
77
78 char StripSymbols::ID = 0;
79 static RegisterPass<StripSymbols>
80 X("strip", "Strip all symbols from a module");
81
82 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
83   return new StripSymbols(OnlyDebugInfo);
84 }
85
86 char StripNonDebugSymbols::ID = 0;
87 static RegisterPass<StripNonDebugSymbols>
88 Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module");
89
90 ModulePass *llvm::createStripNonDebugSymbolsPass() {
91   return new StripNonDebugSymbols();
92 }
93
94 char StripDebugDeclare::ID = 0;
95 static RegisterPass<StripDebugDeclare>
96 Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics");
97
98 ModulePass *llvm::createStripDebugDeclarePass() {
99   return new StripDebugDeclare();
100 }
101
102 /// OnlyUsedBy - Return true if V is only used by Usr.
103 static bool OnlyUsedBy(Value *V, Value *Usr) {
104   for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
105     User *U = *I;
106     if (U != Usr)
107       return false;
108   }
109   return true;
110 }
111
112 static void RemoveDeadConstant(Constant *C) {
113   assert(C->use_empty() && "Constant is not dead!");
114   SmallPtrSet<Constant*, 4> Operands;
115   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
116     if (isa<DerivedType>(C->getOperand(i)->getType()) &&
117         OnlyUsedBy(C->getOperand(i), C)) 
118       Operands.insert(cast<Constant>(C->getOperand(i)));
119   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
120     if (!GV->hasLocalLinkage()) return;   // Don't delete non static globals.
121     GV->eraseFromParent();
122   }
123   else if (!isa<Function>(C))
124     if (isa<CompositeType>(C->getType()))
125       C->destroyConstant();
126
127   // If the constant referenced anything, see if we can delete it as well.
128   for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
129          OE = Operands.end(); OI != OE; ++OI)
130     RemoveDeadConstant(*OI);
131 }
132
133 // Strip the symbol table of its names.
134 //
135 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
136   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
137     Value *V = VI->getValue();
138     ++VI;
139     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
140       if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
141         // Set name to "", removing from symbol table!
142         V->setName("");
143     }
144   }
145 }
146
147 // Strip the symbol table of its names.
148 static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) {
149   for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) {
150     if (PreserveDbgInfo && StringRef(TI->first).startswith("llvm.dbg"))
151       ++TI;
152     else
153       ST.remove(TI++);
154   }
155 }
156
157 /// Find values that are marked as llvm.used.
158 static void findUsedValues(GlobalVariable *LLVMUsed,
159                            SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
160   if (LLVMUsed == 0) return;
161   UsedValues.insert(LLVMUsed);
162   
163   ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
164   if (Inits == 0) return;
165   
166   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
167     if (GlobalValue *GV = 
168           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
169       UsedValues.insert(GV);
170 }
171
172 /// StripSymbolNames - Strip symbol names.
173 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
174
175   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
176   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
177   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
178
179   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
180        I != E; ++I) {
181     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
182       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
183         I->setName("");     // Internal symbols can't participate in linkage
184   }
185   
186   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
187     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
188       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
189         I->setName("");     // Internal symbols can't participate in linkage
190     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
191   }
192   
193   // Remove all names from types.
194   StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
195
196   return true;
197 }
198
199 // StripDebugInfo - Strip debug info in the module if it exists.  
200 // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and 
201 // llvm.dbg.region.end calls, and any globals they point to if now dead.
202 static bool StripDebugInfo(Module &M) {
203
204   bool Changed = false;
205
206   // Remove all of the calls to the debugger intrinsics, and remove them from
207   // the module.
208   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
209     while (!Declare->use_empty()) {
210       CallInst *CI = cast<CallInst>(Declare->use_back());
211       CI->eraseFromParent();
212     }
213     Declare->eraseFromParent();
214     Changed = true;
215   }
216
217   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
218     while (!DbgVal->use_empty()) {
219       CallInst *CI = cast<CallInst>(DbgVal->use_back());
220       CI->eraseFromParent();
221     }
222     DbgVal->eraseFromParent();
223     Changed = true;
224   }
225
226   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
227   if (NMD) {
228     Changed = true;
229     NMD->eraseFromParent();
230   }
231
232   NMD = M.getNamedMetadata("llvm.dbg.lv");
233   if (NMD) {
234     Changed = true;
235     NMD->eraseFromParent();
236   }
237
238   unsigned MDDbgKind = M.getMDKindID("dbg");
239   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
240     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
241          ++FI)
242       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
243            ++BI) {
244         Changed = true; // FIXME: Only set if there was debug metadata.
245         BI->setMetadata(MDDbgKind, 0);
246       }
247
248   return Changed;
249 }
250
251 bool StripSymbols::runOnModule(Module &M) {
252   bool Changed = false;
253   Changed |= StripDebugInfo(M);
254   if (!OnlyDebugInfo)
255     Changed |= StripSymbolNames(M, false);
256   return Changed;
257 }
258
259 bool StripNonDebugSymbols::runOnModule(Module &M) {
260   return StripSymbolNames(M, true);
261 }
262
263 bool StripDebugDeclare::runOnModule(Module &M) {
264
265   Function *Declare = M.getFunction("llvm.dbg.declare");
266   std::vector<Constant*> DeadConstants;
267
268   if (Declare) {
269     while (!Declare->use_empty()) {
270       CallInst *CI = cast<CallInst>(Declare->use_back());
271       Value *Arg1 = CI->getOperand(1);
272       Value *Arg2 = CI->getOperand(2);
273       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
274       CI->eraseFromParent();
275       if (Arg1->use_empty()) {
276         if (Constant *C = dyn_cast<Constant>(Arg1)) 
277           DeadConstants.push_back(C);
278         else 
279           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
280       }
281       if (Arg2->use_empty())
282         if (Constant *C = dyn_cast<Constant>(Arg2)) 
283           DeadConstants.push_back(C);
284     }
285     Declare->eraseFromParent();
286   }
287
288   while (!DeadConstants.empty()) {
289     Constant *C = DeadConstants.back();
290     DeadConstants.pop_back();
291     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
292       if (GV->hasLocalLinkage())
293         RemoveDeadConstant(GV);
294     } else
295       RemoveDeadConstant(C);
296   }
297
298   return true;
299 }