LLVM API Documentation

StripSymbols.cpp

Go to the documentation of this file.
00001 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // The StripSymbols transformation implements code stripping. Specifically, it
00011 // can delete:
00012 // 
00013 //   * names for virtual registers
00014 //   * symbols for internal globals and functions
00015 //   * debug information
00016 //
00017 // Note that this transformation makes code much less readable, so it should
00018 // only be used in situations where the 'strip' utility would be used, such as
00019 // reducing code size or making it harder to reverse engineer code.
00020 //
00021 //===----------------------------------------------------------------------===//
00022 
00023 #include "llvm/Transforms/IPO.h"
00024 #include "llvm/Constants.h"
00025 #include "llvm/DerivedTypes.h"
00026 #include "llvm/Instructions.h"
00027 #include "llvm/LLVMContext.h"
00028 #include "llvm/Module.h"
00029 #include "llvm/Pass.h"
00030 #include "llvm/Analysis/DebugInfo.h"
00031 #include "llvm/ValueSymbolTable.h"
00032 #include "llvm/TypeSymbolTable.h"
00033 #include "llvm/Transforms/Utils/Local.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include "llvm/ADT/SmallPtrSet.h"
00036 using namespace llvm;
00037 
00038 namespace {
00039   class VISIBILITY_HIDDEN StripSymbols : public ModulePass {
00040     bool OnlyDebugInfo;
00041   public:
00042     static char ID; // Pass identification, replacement for typeid
00043     explicit StripSymbols(bool ODI = false) 
00044       : ModulePass(&ID), OnlyDebugInfo(ODI) {}
00045 
00046     virtual bool runOnModule(Module &M);
00047 
00048     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00049       AU.setPreservesAll();
00050     }
00051   };
00052 
00053   class VISIBILITY_HIDDEN StripNonDebugSymbols : public ModulePass {
00054   public:
00055     static char ID; // Pass identification, replacement for typeid
00056     explicit StripNonDebugSymbols()
00057       : ModulePass(&ID) {}
00058 
00059     virtual bool runOnModule(Module &M);
00060 
00061     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00062       AU.setPreservesAll();
00063     }
00064   };
00065 
00066   class VISIBILITY_HIDDEN StripDebugDeclare : public ModulePass {
00067   public:
00068     static char ID; // Pass identification, replacement for typeid
00069     explicit StripDebugDeclare()
00070       : ModulePass(&ID) {}
00071 
00072     virtual bool runOnModule(Module &M);
00073 
00074     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00075       AU.setPreservesAll();
00076     }
00077   };
00078 }
00079 
00080 char StripSymbols::ID = 0;
00081 static RegisterPass<StripSymbols>
00082 X("strip", "Strip all symbols from a module");
00083 
00084 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
00085   return new StripSymbols(OnlyDebugInfo);
00086 }
00087 
00088 char StripNonDebugSymbols::ID = 0;
00089 static RegisterPass<StripNonDebugSymbols>
00090 Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module");
00091 
00092 ModulePass *llvm::createStripNonDebugSymbolsPass() {
00093   return new StripNonDebugSymbols();
00094 }
00095 
00096 char StripDebugDeclare::ID = 0;
00097 static RegisterPass<StripDebugDeclare>
00098 Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics");
00099 
00100 ModulePass *llvm::createStripDebugDeclarePass() {
00101   return new StripDebugDeclare();
00102 }
00103 
00104 /// OnlyUsedBy - Return true if V is only used by Usr.
00105 static bool OnlyUsedBy(Value *V, Value *Usr) {
00106   for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
00107     User *U = *I;
00108     if (U != Usr)
00109       return false;
00110   }
00111   return true;
00112 }
00113 
00114 static void RemoveDeadConstant(Constant *C) {
00115   assert(C->use_empty() && "Constant is not dead!");
00116   SmallPtrSet<Constant *, 4> Operands;
00117   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
00118     if (isa<DerivedType>(C->getOperand(i)->getType()) &&
00119         OnlyUsedBy(C->getOperand(i), C)) 
00120       Operands.insert(C->getOperand(i));
00121   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00122     if (!GV->hasLocalLinkage()) return;   // Don't delete non static globals.
00123     GV->eraseFromParent();
00124   }
00125   else if (!isa<Function>(C))
00126     if (isa<CompositeType>(C->getType()))
00127       C->destroyConstant();
00128 
00129   // If the constant referenced anything, see if we can delete it as well.
00130   for (SmallPtrSet<Constant *, 4>::iterator OI = Operands.begin(),
00131          OE = Operands.end(); OI != OE; ++OI)
00132     RemoveDeadConstant(*OI);
00133 }
00134 
00135 // Strip the symbol table of its names.
00136 //
00137 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
00138   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
00139     Value *V = VI->getValue();
00140     ++VI;
00141     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
00142       if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
00143         // Set name to "", removing from symbol table!
00144         V->setName("");
00145     }
00146   }
00147 }
00148 
00149 // Strip the symbol table of its names.
00150 static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) {
00151   for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) {
00152     if (PreserveDbgInfo && strncmp(TI->first.c_str(), "llvm.dbg", 8) == 0)
00153       ++TI;
00154     else
00155       ST.remove(TI++);
00156   }
00157 }
00158 
00159 /// Find values that are marked as llvm.used.
00160 static void findUsedValues(GlobalVariable *LLVMUsed,
00161                            SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
00162   if (LLVMUsed == 0) return;
00163   UsedValues.insert(LLVMUsed);
00164   
00165   ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
00166   if (Inits == 0) return;
00167   
00168   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
00169     if (GlobalValue *GV = 
00170           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
00171       UsedValues.insert(GV);
00172 }
00173 
00174 /// StripSymbolNames - Strip symbol names.
00175 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
00176 
00177   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
00178   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
00179   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
00180 
00181   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00182        I != E; ++I) {
00183     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
00184       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
00185         I->setName("");     // Internal symbols can't participate in linkage
00186   }
00187   
00188   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00189     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
00190       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
00191         I->setName("");     // Internal symbols can't participate in linkage
00192     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
00193   }
00194   
00195   // Remove all names from types.
00196   StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
00197 
00198   return true;
00199 }
00200 
00201 // StripDebugInfo - Strip debug info in the module if it exists.  
00202 // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and 
00203 // llvm.dbg.region.end calls, and any globals they point to if now dead.
00204 static bool StripDebugInfo(Module &M) {
00205 
00206   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
00207   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
00208   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
00209 
00210   DebugInfoFinder DbgFinder;
00211   DbgFinder.processModule(M);
00212 
00213   // These anchors use LinkOnce linkage so that the optimizer does not
00214   // remove them accidently. Set InternalLinkage for all these debug
00215   // info anchors.
00216   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
00217          E = DbgFinder.compile_unit_end(); I != E; ++I)
00218     (*I)->setLinkage(GlobalValue::InternalLinkage);
00219   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
00220          E = DbgFinder.global_variable_end(); I != E; ++I)
00221     (*I)->setLinkage(GlobalValue::InternalLinkage);
00222   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
00223          E = DbgFinder.subprogram_end(); I != E; ++I)
00224     (*I)->setLinkage(GlobalValue::InternalLinkage);
00225 
00226 
00227  // Delete all dbg variables.
00228   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
00229        I != E; ++I) {
00230     GlobalVariable *GV = dyn_cast<GlobalVariable>(I);
00231     if (!GV) continue;
00232     if (!GV->use_empty() && llvmUsedValues.count(I) == 0) {
00233       if (GV->getName().startswith("llvm.dbg")) {
00234         GV->replaceAllUsesWith(UndefValue::get(GV->getType()));
00235       }
00236     }
00237   }
00238 
00239   Function *FuncStart = M.getFunction("llvm.dbg.func.start");
00240   Function *StopPoint = M.getFunction("llvm.dbg.stoppoint");
00241   Function *RegionStart = M.getFunction("llvm.dbg.region.start");
00242   Function *RegionEnd = M.getFunction("llvm.dbg.region.end");
00243   Function *Declare = M.getFunction("llvm.dbg.declare");
00244 
00245   std::vector<Constant*> DeadConstants;
00246 
00247   // Remove all of the calls to the debugger intrinsics, and remove them from
00248   // the module.
00249   if (FuncStart) {
00250     while (!FuncStart->use_empty()) {
00251       CallInst *CI = cast<CallInst>(FuncStart->use_back());
00252       Value *Arg = CI->getOperand(1);
00253       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00254       CI->eraseFromParent();
00255       if (Arg->use_empty())
00256         if (Constant *C = dyn_cast<Constant>(Arg)) 
00257           DeadConstants.push_back(C);
00258     }
00259     FuncStart->eraseFromParent();
00260   }
00261   if (StopPoint) {
00262     while (!StopPoint->use_empty()) {
00263       CallInst *CI = cast<CallInst>(StopPoint->use_back());
00264       Value *Arg = CI->getOperand(3);
00265       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00266       CI->eraseFromParent();
00267       if (Arg->use_empty())
00268         if (Constant *C = dyn_cast<Constant>(Arg)) 
00269           DeadConstants.push_back(C);
00270     }
00271     StopPoint->eraseFromParent();
00272   }
00273   if (RegionStart) {
00274     while (!RegionStart->use_empty()) {
00275       CallInst *CI = cast<CallInst>(RegionStart->use_back());
00276       Value *Arg = CI->getOperand(1);
00277       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00278       CI->eraseFromParent();
00279       if (Arg->use_empty())
00280         if (Constant *C = dyn_cast<Constant>(Arg)) 
00281           DeadConstants.push_back(C);
00282     }
00283     RegionStart->eraseFromParent();
00284   }
00285   if (RegionEnd) {
00286     while (!RegionEnd->use_empty()) {
00287       CallInst *CI = cast<CallInst>(RegionEnd->use_back());
00288       Value *Arg = CI->getOperand(1);
00289       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00290       CI->eraseFromParent();
00291       if (Arg->use_empty())
00292         if (Constant *C = dyn_cast<Constant>(Arg)) 
00293           DeadConstants.push_back(C);
00294     }
00295     RegionEnd->eraseFromParent();
00296   }
00297   if (Declare) {
00298     while (!Declare->use_empty()) {
00299       CallInst *CI = cast<CallInst>(Declare->use_back());
00300       Value *Arg1 = CI->getOperand(1);
00301       Value *Arg2 = CI->getOperand(2);
00302       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00303       CI->eraseFromParent();
00304       if (Arg1->use_empty()) {
00305         if (Constant *C = dyn_cast<Constant>(Arg1)) 
00306           DeadConstants.push_back(C);
00307         else 
00308           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
00309       }
00310       if (Arg2->use_empty())
00311         if (Constant *C = dyn_cast<Constant>(Arg2)) 
00312           DeadConstants.push_back(C);
00313     }
00314     Declare->eraseFromParent();
00315   }
00316 
00317   // llvm.dbg.compile_units and llvm.dbg.subprograms are marked as linkonce
00318   // but since we are removing all debug information, make them internal now.
00319   // FIXME: Use private linkage maybe?
00320   if (Constant *C = M.getNamedGlobal("llvm.dbg.compile_units"))
00321     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00322       GV->setLinkage(GlobalValue::InternalLinkage);
00323 
00324   if (Constant *C = M.getNamedGlobal("llvm.dbg.subprograms"))
00325     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00326       GV->setLinkage(GlobalValue::InternalLinkage);
00327  
00328   if (Constant *C = M.getNamedGlobal("llvm.dbg.global_variables"))
00329     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00330       GV->setLinkage(GlobalValue::InternalLinkage);
00331 
00332   // Delete all dbg variables.
00333   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
00334        I != E; ++I) {
00335     GlobalVariable *GV = dyn_cast<GlobalVariable>(I);
00336     if (!GV) continue;
00337     if (GV->use_empty() && llvmUsedValues.count(I) == 0
00338         && (!GV->hasSection() 
00339             || strcmp(GV->getSection().c_str(), "llvm.metadata") == 0))
00340       DeadConstants.push_back(GV);
00341   }
00342 
00343   if (DeadConstants.empty())
00344     return false;
00345 
00346   // Delete any internal globals that were only used by the debugger intrinsics.
00347   while (!DeadConstants.empty()) {
00348     Constant *C = DeadConstants.back();
00349     DeadConstants.pop_back();
00350     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00351       if (GV->hasLocalLinkage())
00352         RemoveDeadConstant(GV);
00353     }
00354     else
00355       RemoveDeadConstant(C);
00356   }
00357 
00358   // Remove all llvm.dbg types.
00359   TypeSymbolTable &ST = M.getTypeSymbolTable();
00360   for (TypeSymbolTable::iterator TI = ST.begin(), TE = ST.end(); TI != TE; ) {
00361     if (!strncmp(TI->first.c_str(), "llvm.dbg.", 9))
00362       ST.remove(TI++);
00363     else 
00364       ++TI;
00365   }
00366   
00367   return true;
00368 }
00369 
00370 bool StripSymbols::runOnModule(Module &M) {
00371   bool Changed = false;
00372   Changed |= StripDebugInfo(M);
00373   if (!OnlyDebugInfo)
00374     Changed |= StripSymbolNames(M, false);
00375   return Changed;
00376 }
00377 
00378 bool StripNonDebugSymbols::runOnModule(Module &M) {
00379   return StripSymbolNames(M, true);
00380 }
00381 
00382 bool StripDebugDeclare::runOnModule(Module &M) {
00383 
00384   Function *Declare = M.getFunction("llvm.dbg.declare");
00385   std::vector<Constant*> DeadConstants;
00386 
00387   if (Declare) {
00388     while (!Declare->use_empty()) {
00389       CallInst *CI = cast<CallInst>(Declare->use_back());
00390       Value *Arg1 = CI->getOperand(1);
00391       Value *Arg2 = CI->getOperand(2);
00392       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00393       CI->eraseFromParent();
00394       if (Arg1->use_empty()) {
00395         if (Constant *C = dyn_cast<Constant>(Arg1)) 
00396           DeadConstants.push_back(C);
00397         else 
00398           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
00399       }
00400       if (Arg2->use_empty())
00401         if (Constant *C = dyn_cast<Constant>(Arg2)) 
00402           DeadConstants.push_back(C);
00403     }
00404     Declare->eraseFromParent();
00405   }
00406 
00407   // Delete all llvm.dbg.global_variables.
00408   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
00409        I != E; ++I) {
00410     GlobalVariable *GV = dyn_cast<GlobalVariable>(I);
00411     if (!GV) continue;
00412     if (GV->use_empty() && GV->getName().startswith("llvm.dbg.global_variable"))
00413       DeadConstants.push_back(GV);
00414   }
00415 
00416   while (!DeadConstants.empty()) {
00417     Constant *C = DeadConstants.back();
00418     DeadConstants.pop_back();
00419     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00420       if (GV->hasLocalLinkage())
00421         RemoveDeadConstant(GV);
00422     }
00423     else
00424       RemoveDeadConstant(C);
00425   }
00426 
00427   return true;
00428 }