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