]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/Transforms/IPO/StripSymbols.cpp
ArgumentPromotion: Propagate debug locations on calls for which arguments are promoted.
[opencl/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 //===----------------------------------------------------------------------===//
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"
35 using namespace llvm;
37 namespace {
38   class StripSymbols : public ModulePass {
39     bool OnlyDebugInfo;
40   public:
41     static char ID; // Pass identification, replacement for typeid
42     explicit StripSymbols(bool ODI = false)
43       : ModulePass(ID), OnlyDebugInfo(ODI) {
44         initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
45       }
47     bool runOnModule(Module &M) override;
49     void getAnalysisUsage(AnalysisUsage &AU) const override {
50       AU.setPreservesAll();
51     }
52   };
54   class StripNonDebugSymbols : public ModulePass {
55   public:
56     static char ID; // Pass identification, replacement for typeid
57     explicit StripNonDebugSymbols()
58       : ModulePass(ID) {
59         initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
60       }
62     bool runOnModule(Module &M) override;
64     void getAnalysisUsage(AnalysisUsage &AU) const override {
65       AU.setPreservesAll();
66     }
67   };
69   class StripDebugDeclare : public ModulePass {
70   public:
71     static char ID; // Pass identification, replacement for typeid
72     explicit StripDebugDeclare()
73       : ModulePass(ID) {
74         initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
75       }
77     bool runOnModule(Module &M) override;
79     void getAnalysisUsage(AnalysisUsage &AU) const override {
80       AU.setPreservesAll();
81     }
82   };
84   class StripDeadDebugInfo : public ModulePass {
85   public:
86     static char ID; // Pass identification, replacement for typeid
87     explicit StripDeadDebugInfo()
88       : ModulePass(ID) {
89         initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
90       }
92     bool runOnModule(Module &M) override;
94     void getAnalysisUsage(AnalysisUsage &AU) const override {
95       AU.setPreservesAll();
96     }
97   };
98 }
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",
111                 false, false)
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 (User *U : V->users())
136     if (U != Usr)
137       return false;
139   return true;
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();
151   }
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.
163 //
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();
167     ++VI;
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!
171         V->setName("");
172     }
173   }
176 // Strip any named types of their names.
177 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
178   TypeFinder StructTypes;
179   StructTypes.run(M, false);
181   for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
182     StructType *STy = StructTypes[i];
183     if (STy->isLiteral() || STy->getName().empty()) continue;
185     if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
186       continue;
188     STy->setName("");
189   }
192 /// Find values that are marked as llvm.used.
193 static void findUsedValues(GlobalVariable *LLVMUsed,
194                            SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
195   if (!LLVMUsed) return;
196   UsedValues.insert(LLVMUsed);
198   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
200   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
201     if (GlobalValue *GV =
202           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
203       UsedValues.insert(GV);
206 /// StripSymbolNames - Strip symbol names.
207 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
209   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
210   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
211   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
213   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
214        I != E; ++I) {
215     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
216       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
217         I->setName("");     // Internal symbols can't participate in linkage
218   }
220   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
221     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
222       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
223         I->setName("");     // Internal symbols can't participate in linkage
224     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
225   }
227   // Remove all names from types.
228   StripTypeNames(M, PreserveDbgInfo);
230   return true;
233 bool StripSymbols::runOnModule(Module &M) {
234   bool Changed = false;
235   Changed |= StripDebugInfo(M);
236   if (!OnlyDebugInfo)
237     Changed |= StripSymbolNames(M, false);
238   return Changed;
241 bool StripNonDebugSymbols::runOnModule(Module &M) {
242   return StripSymbolNames(M, true);
245 bool StripDebugDeclare::runOnModule(Module &M) {
247   Function *Declare = M.getFunction("llvm.dbg.declare");
248   std::vector<Constant*> DeadConstants;
250   if (Declare) {
251     while (!Declare->use_empty()) {
252       CallInst *CI = cast<CallInst>(Declare->user_back());
253       Value *Arg1 = CI->getArgOperand(0);
254       Value *Arg2 = CI->getArgOperand(1);
255       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
256       CI->eraseFromParent();
257       if (Arg1->use_empty()) {
258         if (Constant *C = dyn_cast<Constant>(Arg1))
259           DeadConstants.push_back(C);
260         else
261           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
262       }
263       if (Arg2->use_empty())
264         if (Constant *C = dyn_cast<Constant>(Arg2))
265           DeadConstants.push_back(C);
266     }
267     Declare->eraseFromParent();
268   }
270   while (!DeadConstants.empty()) {
271     Constant *C = DeadConstants.back();
272     DeadConstants.pop_back();
273     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
274       if (GV->hasLocalLinkage())
275         RemoveDeadConstant(GV);
276     } else
277       RemoveDeadConstant(C);
278   }
280   return true;
283 /// Remove any debug info for global variables/functions in the given module for
284 /// which said global variable/function no longer exists (i.e. is null).
285 ///
286 /// Debugging information is encoded in llvm IR using metadata. This is designed
287 /// such a way that debug info for symbols preserved even if symbols are
288 /// optimized away by the optimizer. This special pass removes debug info for
289 /// such symbols.
290 bool StripDeadDebugInfo::runOnModule(Module &M) {
291   bool Changed = false;
293   LLVMContext &C = M.getContext();
295   // Find all debug info in F. This is actually overkill in terms of what we
296   // want to do, but we want to try and be as resilient as possible in the face
297   // of potential debug info changes by using the formal interfaces given to us
298   // as much as possible.
299   DebugInfoFinder F;
300   F.processModule(M);
302   // For each compile unit, find the live set of global variables/functions and
303   // replace the current list of potentially dead global variables/functions
304   // with the live list.
305   SmallVector<Value *, 64> LiveGlobalVariables;
306   SmallVector<Value *, 64> LiveSubprograms;
307   DenseSet<const MDNode *> VisitedSet;
309   for (DICompileUnit DIC : F.compile_units()) {
310     assert(DIC.Verify() && "DIC must verify as a DICompileUnit.");
312     // Create our live subprogram list.
313     DIArray SPs = DIC.getSubprograms();
314     bool SubprogramChange = false;
315     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
316       DISubprogram DISP(SPs.getElement(i));
317       assert(DISP.Verify() && "DISP must verify as a DISubprogram.");
319       // Make sure we visit each subprogram only once.
320       if (!VisitedSet.insert(DISP).second)
321         continue;
323       // If the function referenced by DISP is not null, the function is live.
324       if (DISP.getFunction())
325         LiveSubprograms.push_back(DISP);
326       else
327         SubprogramChange = true;
328     }
330     // Create our live global variable list.
331     DIArray GVs = DIC.getGlobalVariables();
332     bool GlobalVariableChange = false;
333     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
334       DIGlobalVariable DIG(GVs.getElement(i));
335       assert(DIG.Verify() && "DIG must verify as DIGlobalVariable.");
337       // Make sure we only visit each global variable only once.
338       if (!VisitedSet.insert(DIG).second)
339         continue;
341       // If the global variable referenced by DIG is not null, the global
342       // variable is live.
343       if (DIG.getGlobal())
344         LiveGlobalVariables.push_back(DIG);
345       else
346         GlobalVariableChange = true;
347     }
349     // If we found dead subprograms or global variables, replace the current
350     // subprogram list/global variable list with our new live subprogram/global
351     // variable list.
352     if (SubprogramChange) {
353       // Make sure that 9 is still the index of the subprograms. This is to make
354       // sure that an assert is hit if the location of the subprogram array
355       // changes. This is just to make sure that this is updated if such an
356       // event occurs.
357       assert(DIC->getNumOperands() >= 10 &&
358              SPs == DIC->getOperand(9) &&
359              "DICompileUnits is expected to store Subprograms in operand "
360              "9.");
361       DIC->replaceOperandWith(9, MDNode::get(C, LiveSubprograms));
362       Changed = true;
363     }
365     if (GlobalVariableChange) {
366       // Make sure that 10 is still the index of global variables. This is to
367       // make sure that an assert is hit if the location of the subprogram array
368       // changes. This is just to make sure that this index is updated if such
369       // an event occurs.
370       assert(DIC->getNumOperands() >= 11 &&
371              GVs == DIC->getOperand(10) &&
372              "DICompileUnits is expected to store Global Variables in operand "
373              "10.");
374       DIC->replaceOperandWith(10, MDNode::get(C, LiveGlobalVariables));
375       Changed = true;
376     }
378     // Reset lists for the next iteration.
379     LiveSubprograms.clear();
380     LiveGlobalVariables.clear();
381   }
383   return Changed;