[llvm-exegesis] [NFC] Fixing typo.
[llvm-complete.git] / lib / Transforms / IPO / StripSymbols.cpp
blob67a473612fc103cfe3d613a17e1f8a64d7f8e2ff
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:
12 // * names for virtual registers
13 // * symbols for internal globals and functions
14 // * debug information
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.
20 //===----------------------------------------------------------------------===//
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Transforms/Utils/Local.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/TypeFinder.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Transforms/IPO.h"
33 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());
45 bool runOnModule(Module &M) override;
47 void getAnalysisUsage(AnalysisUsage &AU) const override {
48 AU.setPreservesAll();
52 class StripNonDebugSymbols : public ModulePass {
53 public:
54 static char ID; // Pass identification, replacement for typeid
55 explicit StripNonDebugSymbols()
56 : ModulePass(ID) {
57 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
60 bool runOnModule(Module &M) override;
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AU.setPreservesAll();
67 class StripDebugDeclare : public ModulePass {
68 public:
69 static char ID; // Pass identification, replacement for typeid
70 explicit StripDebugDeclare()
71 : ModulePass(ID) {
72 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
75 bool runOnModule(Module &M) override;
77 void getAnalysisUsage(AnalysisUsage &AU) const override {
78 AU.setPreservesAll();
82 class StripDeadDebugInfo : public ModulePass {
83 public:
84 static char ID; // Pass identification, replacement for typeid
85 explicit StripDeadDebugInfo()
86 : ModulePass(ID) {
87 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
90 bool runOnModule(Module &M) override;
92 void getAnalysisUsage(AnalysisUsage &AU) const override {
93 AU.setPreservesAll();
98 char StripSymbols::ID = 0;
99 INITIALIZE_PASS(StripSymbols, "strip",
100 "Strip all symbols from a module", false, false)
102 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
103 return new StripSymbols(OnlyDebugInfo);
106 char StripNonDebugSymbols::ID = 0;
107 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
108 "Strip all symbols, except dbg symbols, from a module",
109 false, false)
111 ModulePass *llvm::createStripNonDebugSymbolsPass() {
112 return new StripNonDebugSymbols();
115 char StripDebugDeclare::ID = 0;
116 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
117 "Strip all llvm.dbg.declare intrinsics", false, false)
119 ModulePass *llvm::createStripDebugDeclarePass() {
120 return new StripDebugDeclare();
123 char StripDeadDebugInfo::ID = 0;
124 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
125 "Strip debug info for unused symbols", false, false)
127 ModulePass *llvm::createStripDeadDebugInfoPass() {
128 return new StripDeadDebugInfo();
131 /// OnlyUsedBy - Return true if V is only used by Usr.
132 static bool OnlyUsedBy(Value *V, Value *Usr) {
133 for (User *U : V->users())
134 if (U != Usr)
135 return false;
137 return true;
140 static void RemoveDeadConstant(Constant *C) {
141 assert(C->use_empty() && "Constant is not dead!");
142 SmallPtrSet<Constant*, 4> Operands;
143 for (Value *Op : C->operands())
144 if (OnlyUsedBy(Op, C))
145 Operands.insert(cast<Constant>(Op));
146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
147 if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
148 GV->eraseFromParent();
150 else if (!isa<Function>(C))
151 if (isa<CompositeType>(C->getType()))
152 C->destroyConstant();
154 // If the constant referenced anything, see if we can delete it as well.
155 for (Constant *O : Operands)
156 RemoveDeadConstant(O);
159 // Strip the symbol table of its names.
161 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
162 for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
163 Value *V = VI->getValue();
164 ++VI;
165 if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
166 if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
167 // Set name to "", removing from symbol table!
168 V->setName("");
173 // Strip any named types of their names.
174 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
175 TypeFinder StructTypes;
176 StructTypes.run(M, false);
178 for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
179 StructType *STy = StructTypes[i];
180 if (STy->isLiteral() || STy->getName().empty()) continue;
182 if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
183 continue;
185 STy->setName("");
189 /// Find values that are marked as llvm.used.
190 static void findUsedValues(GlobalVariable *LLVMUsed,
191 SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
192 if (!LLVMUsed) return;
193 UsedValues.insert(LLVMUsed);
195 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
197 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
198 if (GlobalValue *GV =
199 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
200 UsedValues.insert(GV);
203 /// StripSymbolNames - Strip symbol names.
204 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
206 SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
207 findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
208 findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
210 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
211 I != E; ++I) {
212 if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
213 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
214 I->setName(""); // Internal symbols can't participate in linkage
217 for (Function &I : M) {
218 if (I.hasLocalLinkage() && llvmUsedValues.count(&I) == 0)
219 if (!PreserveDbgInfo || !I.getName().startswith("llvm.dbg"))
220 I.setName(""); // Internal symbols can't participate in linkage
221 if (auto *Symtab = I.getValueSymbolTable())
222 StripSymtab(*Symtab, PreserveDbgInfo);
225 // Remove all names from types.
226 StripTypeNames(M, PreserveDbgInfo);
228 return true;
231 bool StripSymbols::runOnModule(Module &M) {
232 if (skipModule(M))
233 return false;
235 bool Changed = false;
236 Changed |= StripDebugInfo(M);
237 if (!OnlyDebugInfo)
238 Changed |= StripSymbolNames(M, false);
239 return Changed;
242 bool StripNonDebugSymbols::runOnModule(Module &M) {
243 if (skipModule(M))
244 return false;
246 return StripSymbolNames(M, true);
249 bool StripDebugDeclare::runOnModule(Module &M) {
250 if (skipModule(M))
251 return false;
253 Function *Declare = M.getFunction("llvm.dbg.declare");
254 std::vector<Constant*> DeadConstants;
256 if (Declare) {
257 while (!Declare->use_empty()) {
258 CallInst *CI = cast<CallInst>(Declare->user_back());
259 Value *Arg1 = CI->getArgOperand(0);
260 Value *Arg2 = CI->getArgOperand(1);
261 assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
262 CI->eraseFromParent();
263 if (Arg1->use_empty()) {
264 if (Constant *C = dyn_cast<Constant>(Arg1))
265 DeadConstants.push_back(C);
266 else
267 RecursivelyDeleteTriviallyDeadInstructions(Arg1);
269 if (Arg2->use_empty())
270 if (Constant *C = dyn_cast<Constant>(Arg2))
271 DeadConstants.push_back(C);
273 Declare->eraseFromParent();
276 while (!DeadConstants.empty()) {
277 Constant *C = DeadConstants.back();
278 DeadConstants.pop_back();
279 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
280 if (GV->hasLocalLinkage())
281 RemoveDeadConstant(GV);
282 } else
283 RemoveDeadConstant(C);
286 return true;
289 /// Remove any debug info for global variables/functions in the given module for
290 /// which said global variable/function no longer exists (i.e. is null).
292 /// Debugging information is encoded in llvm IR using metadata. This is designed
293 /// such a way that debug info for symbols preserved even if symbols are
294 /// optimized away by the optimizer. This special pass removes debug info for
295 /// such symbols.
296 bool StripDeadDebugInfo::runOnModule(Module &M) {
297 if (skipModule(M))
298 return false;
300 bool Changed = false;
302 LLVMContext &C = M.getContext();
304 // Find all debug info in F. This is actually overkill in terms of what we
305 // want to do, but we want to try and be as resilient as possible in the face
306 // of potential debug info changes by using the formal interfaces given to us
307 // as much as possible.
308 DebugInfoFinder F;
309 F.processModule(M);
311 // For each compile unit, find the live set of global variables/functions and
312 // replace the current list of potentially dead global variables/functions
313 // with the live list.
314 SmallVector<Metadata *, 64> LiveGlobalVariables;
315 DenseSet<DIGlobalVariableExpression *> VisitedSet;
317 std::set<DIGlobalVariableExpression *> LiveGVs;
318 for (GlobalVariable &GV : M.globals()) {
319 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
320 GV.getDebugInfo(GVEs);
321 for (auto *GVE : GVEs)
322 LiveGVs.insert(GVE);
325 std::set<DICompileUnit *> LiveCUs;
326 // Any CU referenced from a subprogram is live.
327 for (DISubprogram *SP : F.subprograms()) {
328 if (SP->getUnit())
329 LiveCUs.insert(SP->getUnit());
332 bool HasDeadCUs = false;
333 for (DICompileUnit *DIC : F.compile_units()) {
334 // Create our live global variable list.
335 bool GlobalVariableChange = false;
336 for (auto *DIG : DIC->getGlobalVariables()) {
337 if (DIG->getExpression() && DIG->getExpression()->isConstant())
338 LiveGVs.insert(DIG);
340 // Make sure we only visit each global variable only once.
341 if (!VisitedSet.insert(DIG).second)
342 continue;
344 // If a global variable references DIG, the global variable is live.
345 if (LiveGVs.count(DIG))
346 LiveGlobalVariables.push_back(DIG);
347 else
348 GlobalVariableChange = true;
351 if (!LiveGlobalVariables.empty())
352 LiveCUs.insert(DIC);
353 else if (!LiveCUs.count(DIC))
354 HasDeadCUs = true;
356 // If we found dead global variables, replace the current global
357 // variable list with our new live global variable list.
358 if (GlobalVariableChange) {
359 DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
360 Changed = true;
363 // Reset lists for the next iteration.
364 LiveGlobalVariables.clear();
367 if (HasDeadCUs) {
368 // Delete the old node and replace it with a new one
369 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
370 NMD->clearOperands();
371 if (!LiveCUs.empty()) {
372 for (DICompileUnit *CU : LiveCUs)
373 NMD->addOperand(CU);
375 Changed = true;
378 return Changed;