StripSymbols.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // The StripSymbols transformation implements code stripping. Specifically, it
  10. // can delete:
  11. //
  12. // * names for virtual registers
  13. // * symbols for internal globals and functions
  14. // * debug information
  15. //
  16. // Note that this transformation makes code much less readable, so it should
  17. // only be used in situations where the 'strip' utility would be used, such as
  18. // reducing code size or making it harder to reverse engineer code.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #include "llvm/Transforms/IPO/StripSymbols.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DerivedTypes.h"
  26. #include "llvm/IR/Instructions.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/PassManager.h"
  29. #include "llvm/IR/TypeFinder.h"
  30. #include "llvm/IR/ValueSymbolTable.h"
  31. #include "llvm/InitializePasses.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Transforms/IPO.h"
  34. #include "llvm/Transforms/Utils/Local.h"
  35. using namespace llvm;
  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. initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
  44. }
  45. bool runOnModule(Module &M) override;
  46. void getAnalysisUsage(AnalysisUsage &AU) const override {
  47. AU.setPreservesAll();
  48. }
  49. };
  50. class StripNonDebugSymbols : public ModulePass {
  51. public:
  52. static char ID; // Pass identification, replacement for typeid
  53. explicit StripNonDebugSymbols()
  54. : ModulePass(ID) {
  55. initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
  56. }
  57. bool runOnModule(Module &M) override;
  58. void getAnalysisUsage(AnalysisUsage &AU) const override {
  59. AU.setPreservesAll();
  60. }
  61. };
  62. class StripDebugDeclare : public ModulePass {
  63. public:
  64. static char ID; // Pass identification, replacement for typeid
  65. explicit StripDebugDeclare()
  66. : ModulePass(ID) {
  67. initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
  68. }
  69. bool runOnModule(Module &M) override;
  70. void getAnalysisUsage(AnalysisUsage &AU) const override {
  71. AU.setPreservesAll();
  72. }
  73. };
  74. class StripDeadDebugInfo : public ModulePass {
  75. public:
  76. static char ID; // Pass identification, replacement for typeid
  77. explicit StripDeadDebugInfo()
  78. : ModulePass(ID) {
  79. initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
  80. }
  81. bool runOnModule(Module &M) override;
  82. void getAnalysisUsage(AnalysisUsage &AU) const override {
  83. AU.setPreservesAll();
  84. }
  85. };
  86. }
  87. char StripSymbols::ID = 0;
  88. INITIALIZE_PASS(StripSymbols, "strip",
  89. "Strip all symbols from a module", false, false)
  90. ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
  91. return new StripSymbols(OnlyDebugInfo);
  92. }
  93. char StripNonDebugSymbols::ID = 0;
  94. INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
  95. "Strip all symbols, except dbg symbols, from a module",
  96. false, false)
  97. ModulePass *llvm::createStripNonDebugSymbolsPass() {
  98. return new StripNonDebugSymbols();
  99. }
  100. char StripDebugDeclare::ID = 0;
  101. INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
  102. "Strip all llvm.dbg.declare intrinsics", false, false)
  103. ModulePass *llvm::createStripDebugDeclarePass() {
  104. return new StripDebugDeclare();
  105. }
  106. char StripDeadDebugInfo::ID = 0;
  107. INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
  108. "Strip debug info for unused symbols", false, false)
  109. ModulePass *llvm::createStripDeadDebugInfoPass() {
  110. return new StripDeadDebugInfo();
  111. }
  112. /// OnlyUsedBy - Return true if V is only used by Usr.
  113. static bool OnlyUsedBy(Value *V, Value *Usr) {
  114. for (User *U : V->users())
  115. if (U != Usr)
  116. return false;
  117. return true;
  118. }
  119. static void RemoveDeadConstant(Constant *C) {
  120. assert(C->use_empty() && "Constant is not dead!");
  121. SmallPtrSet<Constant*, 4> Operands;
  122. for (Value *Op : C->operands())
  123. if (OnlyUsedBy(Op, C))
  124. Operands.insert(cast<Constant>(Op));
  125. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
  126. if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
  127. GV->eraseFromParent();
  128. } else if (!isa<Function>(C)) {
  129. // FIXME: Why does the type of the constant matter here?
  130. if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType()) ||
  131. isa<VectorType>(C->getType()))
  132. C->destroyConstant();
  133. }
  134. // If the constant referenced anything, see if we can delete it as well.
  135. for (Constant *O : Operands)
  136. RemoveDeadConstant(O);
  137. }
  138. // Strip the symbol table of its names.
  139. //
  140. static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
  141. for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
  142. Value *V = VI->getValue();
  143. ++VI;
  144. if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
  145. if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
  146. // Set name to "", removing from symbol table!
  147. V->setName("");
  148. }
  149. }
  150. }
  151. // Strip any named types of their names.
  152. static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
  153. TypeFinder StructTypes;
  154. StructTypes.run(M, false);
  155. for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
  156. StructType *STy = StructTypes[i];
  157. if (STy->isLiteral() || STy->getName().empty()) continue;
  158. if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
  159. continue;
  160. STy->setName("");
  161. }
  162. }
  163. /// Find values that are marked as llvm.used.
  164. static void findUsedValues(GlobalVariable *LLVMUsed,
  165. SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
  166. if (!LLVMUsed) return;
  167. UsedValues.insert(LLVMUsed);
  168. ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
  169. for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
  170. if (GlobalValue *GV =
  171. dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
  172. UsedValues.insert(GV);
  173. }
  174. /// StripSymbolNames - Strip symbol names.
  175. static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
  176. SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
  177. findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
  178. findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
  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. for (Function &I : M) {
  186. if (I.hasLocalLinkage() && llvmUsedValues.count(&I) == 0)
  187. if (!PreserveDbgInfo || !I.getName().startswith("llvm.dbg"))
  188. I.setName(""); // Internal symbols can't participate in linkage
  189. if (auto *Symtab = I.getValueSymbolTable())
  190. StripSymtab(*Symtab, PreserveDbgInfo);
  191. }
  192. // Remove all names from types.
  193. StripTypeNames(M, PreserveDbgInfo);
  194. return true;
  195. }
  196. bool StripSymbols::runOnModule(Module &M) {
  197. if (skipModule(M))
  198. return false;
  199. bool Changed = false;
  200. Changed |= StripDebugInfo(M);
  201. if (!OnlyDebugInfo)
  202. Changed |= StripSymbolNames(M, false);
  203. return Changed;
  204. }
  205. bool StripNonDebugSymbols::runOnModule(Module &M) {
  206. if (skipModule(M))
  207. return false;
  208. return StripSymbolNames(M, true);
  209. }
  210. static bool stripDebugDeclareImpl(Module &M) {
  211. Function *Declare = M.getFunction("llvm.dbg.declare");
  212. std::vector<Constant*> DeadConstants;
  213. if (Declare) {
  214. while (!Declare->use_empty()) {
  215. CallInst *CI = cast<CallInst>(Declare->user_back());
  216. Value *Arg1 = CI->getArgOperand(0);
  217. Value *Arg2 = CI->getArgOperand(1);
  218. assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
  219. CI->eraseFromParent();
  220. if (Arg1->use_empty()) {
  221. if (Constant *C = dyn_cast<Constant>(Arg1))
  222. DeadConstants.push_back(C);
  223. else
  224. RecursivelyDeleteTriviallyDeadInstructions(Arg1);
  225. }
  226. if (Arg2->use_empty())
  227. if (Constant *C = dyn_cast<Constant>(Arg2))
  228. DeadConstants.push_back(C);
  229. }
  230. Declare->eraseFromParent();
  231. }
  232. while (!DeadConstants.empty()) {
  233. Constant *C = DeadConstants.back();
  234. DeadConstants.pop_back();
  235. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
  236. if (GV->hasLocalLinkage())
  237. RemoveDeadConstant(GV);
  238. } else
  239. RemoveDeadConstant(C);
  240. }
  241. return true;
  242. }
  243. bool StripDebugDeclare::runOnModule(Module &M) {
  244. if (skipModule(M))
  245. return false;
  246. return stripDebugDeclareImpl(M);
  247. }
  248. static bool stripDeadDebugInfoImpl(Module &M) {
  249. bool Changed = false;
  250. LLVMContext &C = M.getContext();
  251. // Find all debug info in F. This is actually overkill in terms of what we
  252. // want to do, but we want to try and be as resilient as possible in the face
  253. // of potential debug info changes by using the formal interfaces given to us
  254. // as much as possible.
  255. DebugInfoFinder F;
  256. F.processModule(M);
  257. // For each compile unit, find the live set of global variables/functions and
  258. // replace the current list of potentially dead global variables/functions
  259. // with the live list.
  260. SmallVector<Metadata *, 64> LiveGlobalVariables;
  261. DenseSet<DIGlobalVariableExpression *> VisitedSet;
  262. std::set<DIGlobalVariableExpression *> LiveGVs;
  263. for (GlobalVariable &GV : M.globals()) {
  264. SmallVector<DIGlobalVariableExpression *, 1> GVEs;
  265. GV.getDebugInfo(GVEs);
  266. for (auto *GVE : GVEs)
  267. LiveGVs.insert(GVE);
  268. }
  269. std::set<DICompileUnit *> LiveCUs;
  270. // Any CU referenced from a subprogram is live.
  271. for (DISubprogram *SP : F.subprograms()) {
  272. if (SP->getUnit())
  273. LiveCUs.insert(SP->getUnit());
  274. }
  275. bool HasDeadCUs = false;
  276. for (DICompileUnit *DIC : F.compile_units()) {
  277. // Create our live global variable list.
  278. bool GlobalVariableChange = false;
  279. for (auto *DIG : DIC->getGlobalVariables()) {
  280. if (DIG->getExpression() && DIG->getExpression()->isConstant())
  281. LiveGVs.insert(DIG);
  282. // Make sure we only visit each global variable only once.
  283. if (!VisitedSet.insert(DIG).second)
  284. continue;
  285. // If a global variable references DIG, the global variable is live.
  286. if (LiveGVs.count(DIG))
  287. LiveGlobalVariables.push_back(DIG);
  288. else
  289. GlobalVariableChange = true;
  290. }
  291. if (!LiveGlobalVariables.empty())
  292. LiveCUs.insert(DIC);
  293. else if (!LiveCUs.count(DIC))
  294. HasDeadCUs = true;
  295. // If we found dead global variables, replace the current global
  296. // variable list with our new live global variable list.
  297. if (GlobalVariableChange) {
  298. DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
  299. Changed = true;
  300. }
  301. // Reset lists for the next iteration.
  302. LiveGlobalVariables.clear();
  303. }
  304. if (HasDeadCUs) {
  305. // Delete the old node and replace it with a new one
  306. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
  307. NMD->clearOperands();
  308. if (!LiveCUs.empty()) {
  309. for (DICompileUnit *CU : LiveCUs)
  310. NMD->addOperand(CU);
  311. }
  312. Changed = true;
  313. }
  314. return Changed;
  315. }
  316. /// Remove any debug info for global variables/functions in the given module for
  317. /// which said global variable/function no longer exists (i.e. is null).
  318. ///
  319. /// Debugging information is encoded in llvm IR using metadata. This is designed
  320. /// such a way that debug info for symbols preserved even if symbols are
  321. /// optimized away by the optimizer. This special pass removes debug info for
  322. /// such symbols.
  323. bool StripDeadDebugInfo::runOnModule(Module &M) {
  324. if (skipModule(M))
  325. return false;
  326. return stripDeadDebugInfoImpl(M);
  327. }
  328. PreservedAnalyses StripSymbolsPass::run(Module &M, ModuleAnalysisManager &AM) {
  329. StripDebugInfo(M);
  330. StripSymbolNames(M, false);
  331. return PreservedAnalyses::all();
  332. }
  333. PreservedAnalyses StripNonDebugSymbolsPass::run(Module &M,
  334. ModuleAnalysisManager &AM) {
  335. StripSymbolNames(M, true);
  336. return PreservedAnalyses::all();
  337. }
  338. PreservedAnalyses StripDebugDeclarePass::run(Module &M,
  339. ModuleAnalysisManager &AM) {
  340. stripDebugDeclareImpl(M);
  341. return PreservedAnalyses::all();
  342. }
  343. PreservedAnalyses StripDeadDebugInfoPass::run(Module &M,
  344. ModuleAnalysisManager &AM) {
  345. stripDeadDebugInfoImpl(M);
  346. return PreservedAnalyses::all();
  347. }