StripSymbols.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. #include "llvm/Transforms/IPO.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/SmallPtrSet.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/Utils/Local.h"
  34. using namespace llvm;
  35. namespace {
  36. class StripSymbols : public ModulePass {
  37. bool OnlyDebugInfo;
  38. public:
  39. static char ID; // Pass identification, replacement for typeid
  40. explicit StripSymbols(bool ODI = false)
  41. : ModulePass(ID), OnlyDebugInfo(ODI) {
  42. initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
  43. }
  44. bool runOnModule(Module &M) override;
  45. void getAnalysisUsage(AnalysisUsage &AU) const override {
  46. AU.setPreservesAll();
  47. }
  48. };
  49. class StripNonDebugSymbols : public ModulePass {
  50. public:
  51. static char ID; // Pass identification, replacement for typeid
  52. explicit StripNonDebugSymbols()
  53. : ModulePass(ID) {
  54. initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
  55. }
  56. bool runOnModule(Module &M) override;
  57. void getAnalysisUsage(AnalysisUsage &AU) const override {
  58. AU.setPreservesAll();
  59. }
  60. };
  61. class StripDebugDeclare : public ModulePass {
  62. public:
  63. static char ID; // Pass identification, replacement for typeid
  64. explicit StripDebugDeclare()
  65. : ModulePass(ID) {
  66. initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
  67. }
  68. bool runOnModule(Module &M) override;
  69. void getAnalysisUsage(AnalysisUsage &AU) const override {
  70. AU.setPreservesAll();
  71. }
  72. };
  73. class StripDeadDebugInfo : public ModulePass {
  74. public:
  75. static char ID; // Pass identification, replacement for typeid
  76. explicit StripDeadDebugInfo()
  77. : ModulePass(ID) {
  78. initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
  79. }
  80. bool runOnModule(Module &M) override;
  81. void getAnalysisUsage(AnalysisUsage &AU) const override {
  82. AU.setPreservesAll();
  83. }
  84. };
  85. }
  86. char StripSymbols::ID = 0;
  87. INITIALIZE_PASS(StripSymbols, "strip",
  88. "Strip all symbols from a module", false, false)
  89. ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
  90. return new StripSymbols(OnlyDebugInfo);
  91. }
  92. char StripNonDebugSymbols::ID = 0;
  93. INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
  94. "Strip all symbols, except dbg symbols, from a module",
  95. false, false)
  96. ModulePass *llvm::createStripNonDebugSymbolsPass() {
  97. return new StripNonDebugSymbols();
  98. }
  99. char StripDebugDeclare::ID = 0;
  100. INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
  101. "Strip all llvm.dbg.declare intrinsics", false, false)
  102. ModulePass *llvm::createStripDebugDeclarePass() {
  103. return new StripDebugDeclare();
  104. }
  105. char StripDeadDebugInfo::ID = 0;
  106. INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
  107. "Strip debug info for unused symbols", false, false)
  108. ModulePass *llvm::createStripDeadDebugInfoPass() {
  109. return new StripDeadDebugInfo();
  110. }
  111. /// OnlyUsedBy - Return true if V is only used by Usr.
  112. static bool OnlyUsedBy(Value *V, Value *Usr) {
  113. for (User *U : V->users())
  114. if (U != Usr)
  115. return false;
  116. return true;
  117. }
  118. static void RemoveDeadConstant(Constant *C) {
  119. assert(C->use_empty() && "Constant is not dead!");
  120. SmallPtrSet<Constant*, 4> Operands;
  121. for (Value *Op : C->operands())
  122. if (OnlyUsedBy(Op, C))
  123. Operands.insert(cast<Constant>(Op));
  124. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
  125. if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
  126. GV->eraseFromParent();
  127. }
  128. else if (!isa<Function>(C))
  129. if (isa<CompositeType>(C->getType()))
  130. C->destroyConstant();
  131. // If the constant referenced anything, see if we can delete it as well.
  132. for (Constant *O : Operands)
  133. RemoveDeadConstant(O);
  134. }
  135. // Strip the symbol table of its names.
  136. //
  137. static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
  138. for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
  139. Value *V = VI->getValue();
  140. ++VI;
  141. if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
  142. if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
  143. // Set name to "", removing from symbol table!
  144. V->setName("");
  145. }
  146. }
  147. }
  148. // Strip any named types of their names.
  149. static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
  150. TypeFinder StructTypes;
  151. StructTypes.run(M, false);
  152. for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
  153. StructType *STy = StructTypes[i];
  154. if (STy->isLiteral() || STy->getName().empty()) continue;
  155. if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
  156. continue;
  157. STy->setName("");
  158. }
  159. }
  160. /// Find values that are marked as llvm.used.
  161. static void findUsedValues(GlobalVariable *LLVMUsed,
  162. SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
  163. if (!LLVMUsed) return;
  164. UsedValues.insert(LLVMUsed);
  165. ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
  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. /// StripSymbolNames - Strip symbol names.
  172. static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
  173. SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
  174. findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
  175. findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
  176. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  177. I != E; ++I) {
  178. if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
  179. if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
  180. I->setName(""); // Internal symbols can't participate in linkage
  181. }
  182. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
  183. if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
  184. if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
  185. I->setName(""); // Internal symbols can't participate in linkage
  186. StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
  187. }
  188. // Remove all names from types.
  189. StripTypeNames(M, PreserveDbgInfo);
  190. return true;
  191. }
  192. bool StripSymbols::runOnModule(Module &M) {
  193. bool Changed = false;
  194. Changed |= StripDebugInfo(M);
  195. if (!OnlyDebugInfo)
  196. Changed |= StripSymbolNames(M, false);
  197. return Changed;
  198. }
  199. bool StripNonDebugSymbols::runOnModule(Module &M) {
  200. return StripSymbolNames(M, true);
  201. }
  202. bool StripDebugDeclare::runOnModule(Module &M) {
  203. Function *Declare = M.getFunction("llvm.dbg.declare");
  204. std::vector<Constant*> DeadConstants;
  205. if (Declare) {
  206. while (!Declare->use_empty()) {
  207. CallInst *CI = cast<CallInst>(Declare->user_back());
  208. Value *Arg1 = CI->getArgOperand(0);
  209. Value *Arg2 = CI->getArgOperand(1);
  210. assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
  211. CI->eraseFromParent();
  212. if (Arg1->use_empty()) {
  213. if (Constant *C = dyn_cast<Constant>(Arg1))
  214. DeadConstants.push_back(C);
  215. else
  216. RecursivelyDeleteTriviallyDeadInstructions(Arg1);
  217. }
  218. if (Arg2->use_empty())
  219. if (Constant *C = dyn_cast<Constant>(Arg2))
  220. DeadConstants.push_back(C);
  221. }
  222. Declare->eraseFromParent();
  223. }
  224. while (!DeadConstants.empty()) {
  225. Constant *C = DeadConstants.back();
  226. DeadConstants.pop_back();
  227. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
  228. if (GV->hasLocalLinkage())
  229. RemoveDeadConstant(GV);
  230. } else
  231. RemoveDeadConstant(C);
  232. }
  233. return true;
  234. }
  235. /// Remove any debug info for global variables/functions in the given module for
  236. /// which said global variable/function no longer exists (i.e. is null).
  237. ///
  238. /// Debugging information is encoded in llvm IR using metadata. This is designed
  239. /// such a way that debug info for symbols preserved even if symbols are
  240. /// optimized away by the optimizer. This special pass removes debug info for
  241. /// such symbols.
  242. bool StripDeadDebugInfo::runOnModule(Module &M) {
  243. bool Changed = false;
  244. LLVMContext &C = M.getContext();
  245. // Find all debug info in F. This is actually overkill in terms of what we
  246. // want to do, but we want to try and be as resilient as possible in the face
  247. // of potential debug info changes by using the formal interfaces given to us
  248. // as much as possible.
  249. DebugInfoFinder F;
  250. F.processModule(M);
  251. // For each compile unit, find the live set of global variables/functions and
  252. // replace the current list of potentially dead global variables/functions
  253. // with the live list.
  254. SmallVector<Metadata *, 64> LiveGlobalVariables;
  255. SmallVector<Metadata *, 64> LiveSubprograms;
  256. DenseSet<const MDNode *> VisitedSet;
  257. for (DICompileUnit *DIC : F.compile_units()) {
  258. // Create our live subprogram list.
  259. bool SubprogramChange = false;
  260. for (DISubprogram *DISP : DIC->getSubprograms()) {
  261. // Make sure we visit each subprogram only once.
  262. if (!VisitedSet.insert(DISP).second)
  263. continue;
  264. // If the function referenced by DISP is not null, the function is live.
  265. if (DISP->getFunction())
  266. LiveSubprograms.push_back(DISP);
  267. else
  268. SubprogramChange = true;
  269. }
  270. // Create our live global variable list.
  271. bool GlobalVariableChange = false;
  272. for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) {
  273. // Make sure we only visit each global variable only once.
  274. if (!VisitedSet.insert(DIG).second)
  275. continue;
  276. // If the global variable referenced by DIG is not null, the global
  277. // variable is live.
  278. if (DIG->getVariable())
  279. LiveGlobalVariables.push_back(DIG);
  280. else
  281. GlobalVariableChange = true;
  282. }
  283. // If we found dead subprograms or global variables, replace the current
  284. // subprogram list/global variable list with our new live subprogram/global
  285. // variable list.
  286. if (SubprogramChange) {
  287. DIC->replaceSubprograms(MDTuple::get(C, LiveSubprograms));
  288. Changed = true;
  289. }
  290. if (GlobalVariableChange) {
  291. DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
  292. Changed = true;
  293. }
  294. // Reset lists for the next iteration.
  295. LiveSubprograms.clear();
  296. LiveGlobalVariables.clear();
  297. }
  298. return Changed;
  299. }