1 //===-- Internalize.cpp - Mark functions internal -------------------------===//
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 // This pass loops over all of the functions and variables in the input module.
11 // If the function or variable is not in the list of external names given to
12 // the pass it is marked as internal.
13 //
14 // This transformation would not be legal in a regular compilation, but it gets
15 // extra information from the linker about what is safe.
16 //
17 // For example: Internalizing a function with external linkage. Only if we are
18 // told it is only used from within this module, it is safe to do it.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "llvm/Transforms/IPO/Internalize.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/GlobalStatus.h"
34 #include "llvm/Transforms/Utils/ModuleUtils.h"
35 #include <fstream>
36 #include <set>
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "internalize"
40 
41 STATISTIC(NumAliases, "Number of aliases internalized");
42 STATISTIC(NumFunctions, "Number of functions internalized");
43 STATISTIC(NumGlobals, "Number of global vars internalized");
44 
45 // APIFile - A file which contains a list of symbols that should not be marked
46 // external.
47 static cl::opt<std::string>
48     APIFile("internalize-public-api-file", cl::value_desc("filename"),
49             cl::desc("A file containing list of symbol names to preserve"));
50 
51 // APIList - A list of symbols that should not be marked internal.
52 static cl::list<std::string>
53     APIList("internalize-public-api-list", cl::value_desc("list"),
54             cl::desc("A list of symbol names to preserve"), cl::CommaSeparated);
55 
56 namespace {
57 
58 // Helper to load an API list to preserve from file and expose it as a functor
59 // for internalization.
60 class PreserveAPIList {
61 public:
62   PreserveAPIList() {
63     if (!APIFile.empty())
64       LoadFile(APIFile);
65     ExternalNames.insert(APIList.begin(), APIList.end());
66   }
67 
68   bool operator()(const GlobalValue &GV) {
69     return ExternalNames.count(GV.getName());
70   }
71 
72 private:
73   // Contains the set of symbols loaded from file
74   StringSet<> ExternalNames;
75 
76   void LoadFile(StringRef Filename) {
77     // Load the APIFile...
78     std::ifstream In(Filename.data());
79     if (!In.good()) {
80       errs() << "WARNING: Internalize couldn't load file '" << Filename
81              << "'! Continuing as if it's empty.\n";
82       return; // Just continue as if the file were empty
83     }
84     while (In) {
85       std::string Symbol;
86       In >> Symbol;
87       if (!Symbol.empty())
88         ExternalNames.insert(Symbol);
89     }
90   }
91 };
92 
93 // Internalization exposed as a pass
94 class InternalizePass : public ModulePass {
95   // Client supplied callback to control wheter a symbol must be preserved.
96   std::function<bool(const GlobalValue &)> MustPreserveGV;
97 
98 public:
99   static char ID; // Pass identification, replacement for typeid
100 
101   InternalizePass() : ModulePass(ID), MustPreserveGV(PreserveAPIList()) {}
102 
103   InternalizePass(std::function<bool(const GlobalValue &)> MustPreserveGV)
104       : ModulePass(ID), MustPreserveGV(std::move(MustPreserveGV)) {
105     initializeInternalizePassPass(*PassRegistry::getPassRegistry());
106   }
107 
108   bool runOnModule(Module &M) override {
109     CallGraphWrapperPass *CGPass =
110         getAnalysisIfAvailable<CallGraphWrapperPass>();
111     CallGraph *CG = CGPass ? &CGPass->getCallGraph() : nullptr;
112     return internalizeModule(M, MustPreserveGV, CG);
113   }
114 
115   void getAnalysisUsage(AnalysisUsage &AU) const override {
116     AU.setPreservesCFG();
117     AU.addPreserved<CallGraphWrapperPass>();
118   }
119 };
120 } // end anonymous namespace
121 
122 char InternalizePass::ID = 0;
123 INITIALIZE_PASS(InternalizePass, "internalize", "Internalize Global Symbols",
124                 false, false)
125 
126 // Helper class to perform internalization.
127 class Internalizer {
128   // Client supplied callback to control wheter a symbol must be preserved.
129   const std::function<bool(const GlobalValue &)> &MustPreserveGV;
130 
131   // Set of symbols private to the compiler that this pass should not touch.
132   StringSet<> AlwaysPreserved;
133 
134   // Return false if we're allowed to internalize this GV.
135   bool ShouldPreserveGV(const GlobalValue &GV) {
136     // Function must be defined here
137     if (GV.isDeclaration())
138       return true;
139 
140     // Available externally is really just a "declaration with a body".
141     if (GV.hasAvailableExternallyLinkage())
142       return true;
143 
144     // Assume that dllexported symbols are referenced elsewhere
145     if (GV.hasDLLExportStorageClass())
146       return true;
147 
148     // Already local, has nothing to do.
149     if (GV.hasLocalLinkage())
150       return false;
151 
152     // Check some special cases
153     if (AlwaysPreserved.count(GV.getName()))
154       return true;
155 
156     return MustPreserveGV(GV);
157   }
158 
159   bool maybeInternalize(GlobalValue &GV,
160                         const std::set<const Comdat *> &ExternalComdats);
161   void checkComdatVisibility(GlobalValue &GV,
162                              std::set<const Comdat *> &ExternalComdats);
163 
164 public:
165   Internalizer(const std::function<bool(const GlobalValue &)> &MustPreserveGV)
166       : MustPreserveGV(MustPreserveGV) {}
167 
168   /// Run the internalizer on \p TheModule, returns true if any changes was
169   /// made.
170   ///
171   /// If the CallGraph \p CG is supplied, it will be updated when
172   /// internalizing a function (by removing any edge from the "external node")
173   bool internalizeModule(Module &TheModule, CallGraph *CG = nullptr);
174 };
175 
176 // Internalize GV if it is possible to do so, i.e. it is not externally visible
177 // and is not a member of an externally visible comdat.
178 bool Internalizer::maybeInternalize(
179     GlobalValue &GV, const std::set<const Comdat *> &ExternalComdats) {
180   if (Comdat *C = GV.getComdat()) {
181     if (ExternalComdats.count(C))
182       return false;
183 
184     // If a comdat is not externally visible we can drop it.
185     if (auto GO = dyn_cast<GlobalObject>(&GV))
186       GO->setComdat(nullptr);
187 
188     if (GV.hasLocalLinkage())
189       return false;
190   } else {
191     if (GV.hasLocalLinkage())
192       return false;
193 
194     if (ShouldPreserveGV(GV))
195       return false;
196   }
197 
198   GV.setVisibility(GlobalValue::DefaultVisibility);
199   GV.setLinkage(GlobalValue::InternalLinkage);
200   return true;
201 }
202 
203 // If GV is part of a comdat and is externally visible, keep track of its
204 // comdat so that we don't internalize any of its members.
205 void Internalizer::checkComdatVisibility(
206     GlobalValue &GV, std::set<const Comdat *> &ExternalComdats) {
207   Comdat *C = GV.getComdat();
208   if (!C)
209     return;
210 
211   if (ShouldPreserveGV(GV))
212     ExternalComdats.insert(C);
213 }
214 
215 bool Internalizer::internalizeModule(Module &M, CallGraph *CG) {
216   bool Changed = false;
217   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : nullptr;
218 
219   SmallPtrSet<GlobalValue *, 8> Used;
220   collectUsedGlobalVariables(M, Used, false);
221 
222   // Collect comdat visiblity information for the module.
223   std::set<const Comdat *> ExternalComdats;
224   if (!M.getComdatSymbolTable().empty()) {
225     for (Function &F : M)
226       checkComdatVisibility(F, ExternalComdats);
227     for (GlobalVariable &GV : M.globals())
228       checkComdatVisibility(GV, ExternalComdats);
229     for (GlobalAlias &GA : M.aliases())
230       checkComdatVisibility(GA, ExternalComdats);
231   }
232 
233   // We must assume that globals in llvm.used have a reference that not even
234   // the linker can see, so we don't internalize them.
235   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
236   // linker can drop those symbols. If this pass is running as part of LTO,
237   // one might think that it could just drop llvm.compiler.used. The problem
238   // is that even in LTO llvm doesn't see every reference. For example,
239   // we don't see references from function local inline assembly. To be
240   // conservative, we internalize symbols in llvm.compiler.used, but we
241   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
242   for (GlobalValue *V : Used) {
243     AlwaysPreserved.insert(V->getName());
244   }
245 
246   // Mark all functions not in the api as internal.
247   for (Function &I : M) {
248     if (!maybeInternalize(I, ExternalComdats))
249       continue;
250     Changed = true;
251 
252     if (ExternalNode)
253       // Remove a callgraph edge from the external node to this function.
254       ExternalNode->removeOneAbstractEdgeTo((*CG)[&I]);
255 
256     ++NumFunctions;
257     DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");
258   }
259 
260   // Never internalize the llvm.used symbol.  It is used to implement
261   // attribute((used)).
262   // FIXME: Shouldn't this just filter on llvm.metadata section??
263   AlwaysPreserved.insert("llvm.used");
264   AlwaysPreserved.insert("llvm.compiler.used");
265 
266   // Never internalize anchors used by the machine module info, else the info
267   // won't find them.  (see MachineModuleInfo.)
268   AlwaysPreserved.insert("llvm.global_ctors");
269   AlwaysPreserved.insert("llvm.global_dtors");
270   AlwaysPreserved.insert("llvm.global.annotations");
271 
272   // Never internalize symbols code-gen inserts.
273   // FIXME: We should probably add this (and the __stack_chk_guard) via some
274   // type of call-back in CodeGen.
275   AlwaysPreserved.insert("__stack_chk_fail");
276   AlwaysPreserved.insert("__stack_chk_guard");
277 
278   // Mark all global variables with initializers that are not in the api as
279   // internal as well.
280   for (auto &GV : M.globals()) {
281     if (!maybeInternalize(GV, ExternalComdats))
282       continue;
283     Changed = true;
284 
285     ++NumGlobals;
286     DEBUG(dbgs() << "Internalized gvar " << GV.getName() << "\n");
287   }
288 
289   // Mark all aliases that are not in the api as internal as well.
290   for (auto &GA : M.aliases()) {
291     if (!maybeInternalize(GA, ExternalComdats))
292       continue;
293     Changed = true;
294 
295     ++NumAliases;
296     DEBUG(dbgs() << "Internalized alias " << GA.getName() << "\n");
297   }
298 
299   return Changed;
300 }
301 
302 /// Public API below
303 
304 bool llvm::internalizeModule(
305     Module &TheModule,
306     const std::function<bool(const GlobalValue &)> &MustPreserveGV,
307     CallGraph *CG) {
308   return Internalizer(MustPreserveGV).internalizeModule(TheModule, CG);
309 }
310 
311 ModulePass *llvm::createInternalizePass() { return new InternalizePass(); }
312 
313 ModulePass *llvm::createInternalizePass(
314     std::function<bool(const GlobalValue &)> MustPreserveGV) {
315   return new InternalizePass(std::move(MustPreserveGV));
316 }
317