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   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : nullptr;
217 
218   SmallPtrSet<GlobalValue *, 8> Used;
219   collectUsedGlobalVariables(M, Used, false);
220 
221   // Collect comdat visiblity information for the module.
222   std::set<const Comdat *> ExternalComdats;
223   if (!M.getComdatSymbolTable().empty()) {
224     for (Function &F : M)
225       checkComdatVisibility(F, ExternalComdats);
226     for (GlobalVariable &GV : M.globals())
227       checkComdatVisibility(GV, ExternalComdats);
228     for (GlobalAlias &GA : M.aliases())
229       checkComdatVisibility(GA, ExternalComdats);
230   }
231 
232   // We must assume that globals in llvm.used have a reference that not even
233   // the linker can see, so we don't internalize them.
234   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
235   // linker can drop those symbols. If this pass is running as part of LTO,
236   // one might think that it could just drop llvm.compiler.used. The problem
237   // is that even in LTO llvm doesn't see every reference. For example,
238   // we don't see references from function local inline assembly. To be
239   // conservative, we internalize symbols in llvm.compiler.used, but we
240   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
241   for (GlobalValue *V : Used) {
242     AlwaysPreserved.insert(V->getName());
243   }
244 
245   // Mark all functions not in the api as internal.
246   for (Function &I : M) {
247     if (!maybeInternalize(I, ExternalComdats))
248       continue;
249 
250     if (ExternalNode)
251       // Remove a callgraph edge from the external node to this function.
252       ExternalNode->removeOneAbstractEdgeTo((*CG)[&I]);
253 
254     ++NumFunctions;
255     DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");
256   }
257 
258   // Never internalize the llvm.used symbol.  It is used to implement
259   // attribute((used)).
260   // FIXME: Shouldn't this just filter on llvm.metadata section??
261   AlwaysPreserved.insert("llvm.used");
262   AlwaysPreserved.insert("llvm.compiler.used");
263 
264   // Never internalize anchors used by the machine module info, else the info
265   // won't find them.  (see MachineModuleInfo.)
266   AlwaysPreserved.insert("llvm.global_ctors");
267   AlwaysPreserved.insert("llvm.global_dtors");
268   AlwaysPreserved.insert("llvm.global.annotations");
269 
270   // Never internalize symbols code-gen inserts.
271   // FIXME: We should probably add this (and the __stack_chk_guard) via some
272   // type of call-back in CodeGen.
273   AlwaysPreserved.insert("__stack_chk_fail");
274   AlwaysPreserved.insert("__stack_chk_guard");
275 
276   // Mark all global variables with initializers that are not in the api as
277   // internal as well.
278   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
279        ++I) {
280     if (!maybeInternalize(*I, ExternalComdats))
281       continue;
282 
283     ++NumGlobals;
284     DEBUG(dbgs() << "Internalized gvar " << I->getName() << "\n");
285   }
286 
287   // Mark all aliases that are not in the api as internal as well.
288   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
289        ++I) {
290     if (!maybeInternalize(*I, ExternalComdats))
291       continue;
292 
293     ++NumAliases;
294     DEBUG(dbgs() << "Internalized alias " << I->getName() << "\n");
295   }
296 
297   // We do not keep track of whether this pass changed the module because
298   // it adds unnecessary complexity:
299   // 1) This pass will generally be near the start of the pass pipeline, so
300   //    there will be no analyses to invalidate.
301   // 2) This pass will most likely end up changing the module and it isn't worth
302   //    worrying about optimizing the case where the module is unchanged.
303   return true;
304 }
305 
306 /// Public API below
307 
308 bool llvm::internalizeModule(
309     Module &TheModule,
310     const std::function<bool(const GlobalValue &)> &MustPreserveGV,
311     CallGraph *CG) {
312   return Internalizer(MustPreserveGV).internalizeModule(TheModule, CG);
313 }
314 
315 ModulePass *llvm::createInternalizePass() { return new InternalizePass(); }
316 
317 ModulePass *llvm::createInternalizePass(
318     std::function<bool(const GlobalValue &)> MustPreserveGV) {
319   return new InternalizePass(std::move(MustPreserveGV));
320 }
321