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