dae69ce09156d101f27edec25dad50c6958e6f75
[oota-llvm.git] / lib / Transforms / IPO / Internalize.cpp
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 #define DEBUG_TYPE "internalize"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/CallGraph.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/GlobalStatus.h"
33 #include "llvm/Transforms/Utils/ModuleUtils.h"
34 #include <fstream>
35 #include <set>
36 using namespace llvm;
37
38 STATISTIC(NumAliases  , "Number of aliases internalized");
39 STATISTIC(NumFunctions, "Number of functions internalized");
40 STATISTIC(NumGlobals  , "Number of global vars internalized");
41
42 // APIFile - A file which contains a list of symbols that should not be marked
43 // external.
44 static cl::opt<std::string>
45 APIFile("internalize-public-api-file", cl::value_desc("filename"),
46         cl::desc("A file containing list of symbol names to preserve"));
47
48 // APIList - A list of symbols that should not be marked internal.
49 static cl::list<std::string>
50 APIList("internalize-public-api-list", cl::value_desc("list"),
51         cl::desc("A list of symbol names to preserve"),
52         cl::CommaSeparated);
53
54 namespace {
55   class InternalizePass : public ModulePass {
56     std::set<std::string> ExternalNames;
57   public:
58     static char ID; // Pass identification, replacement for typeid
59     explicit InternalizePass();
60     explicit InternalizePass(ArrayRef<const char *> ExportList);
61     void LoadFile(const char *Filename);
62     virtual bool runOnModule(Module &M);
63
64     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65       AU.setPreservesCFG();
66       AU.addPreserved<CallGraphWrapperPass>();
67     }
68   };
69 } // end anonymous namespace
70
71 char InternalizePass::ID = 0;
72 INITIALIZE_PASS(InternalizePass, "internalize",
73                 "Internalize Global Symbols", false, false)
74
75 InternalizePass::InternalizePass()
76   : ModulePass(ID) {
77   initializeInternalizePassPass(*PassRegistry::getPassRegistry());
78   if (!APIFile.empty())           // If a filename is specified, use it.
79     LoadFile(APIFile.c_str());
80   ExternalNames.insert(APIList.begin(), APIList.end());
81 }
82
83 InternalizePass::InternalizePass(ArrayRef<const char *> ExportList)
84   : ModulePass(ID){
85   initializeInternalizePassPass(*PassRegistry::getPassRegistry());
86   for(ArrayRef<const char *>::const_iterator itr = ExportList.begin();
87         itr != ExportList.end(); itr++) {
88     ExternalNames.insert(*itr);
89   }
90 }
91
92 void InternalizePass::LoadFile(const char *Filename) {
93   // Load the APIFile...
94   std::ifstream In(Filename);
95   if (!In.good()) {
96     errs() << "WARNING: Internalize couldn't load file '" << Filename
97          << "'! Continuing as if it's empty.\n";
98     return; // Just continue as if the file were empty
99   }
100   while (In) {
101     std::string Symbol;
102     In >> Symbol;
103     if (!Symbol.empty())
104       ExternalNames.insert(Symbol);
105   }
106 }
107
108 static bool shouldInternalize(const GlobalValue &GV,
109                               const std::set<std::string> &ExternalNames) {
110   // Function must be defined here
111   if (GV.isDeclaration())
112     return false;
113
114   // Available externally is really just a "declaration with a body".
115   if (GV.hasAvailableExternallyLinkage())
116     return false;
117
118   // Assume that dllexported symbols are referenced elsewhere
119   if (GV.hasDLLExportLinkage())
120     return false;
121
122   // Already has internal linkage
123   if (GV.hasLocalLinkage())
124     return false;
125
126   // Marked to keep external?
127   if (ExternalNames.count(GV.getName()))
128     return false;
129
130   return true;
131 }
132
133 bool InternalizePass::runOnModule(Module &M) {
134   CallGraphWrapperPass *CGPass = getAnalysisIfAvailable<CallGraphWrapperPass>();
135   CallGraph *CG = CGPass ? &CGPass->getCallGraph() : 0;
136   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : 0;
137   bool Changed = false;
138
139   SmallPtrSet<GlobalValue *, 8> Used;
140   collectUsedGlobalVariables(M, Used, false);
141
142   // We must assume that globals in llvm.used have a reference that not even
143   // the linker can see, so we don't internalize them.
144   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
145   // linker can drop those symbols. If this pass is running as part of LTO,
146   // one might think that it could just drop llvm.compiler.used. The problem
147   // is that even in LTO llvm doesn't see every reference. For example,
148   // we don't see references from function local inline assembly. To be
149   // conservative, we internalize symbols in llvm.compiler.used, but we
150   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
151   for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.begin(), E = Used.end();
152        I != E; ++I) {
153     GlobalValue *V = *I;
154     ExternalNames.insert(V->getName());
155   }
156
157   // Mark all functions not in the api as internal.
158   // FIXME: maybe use private linkage?
159   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
160     if (!shouldInternalize(*I, ExternalNames))
161       continue;
162
163     I->setLinkage(GlobalValue::InternalLinkage);
164
165     if (ExternalNode)
166       // Remove a callgraph edge from the external node to this function.
167       ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
168
169     Changed = true;
170     ++NumFunctions;
171     DEBUG(dbgs() << "Internalizing func " << I->getName() << "\n");
172   }
173
174   // Never internalize the llvm.used symbol.  It is used to implement
175   // attribute((used)).
176   // FIXME: Shouldn't this just filter on llvm.metadata section??
177   ExternalNames.insert("llvm.used");
178   ExternalNames.insert("llvm.compiler.used");
179
180   // Never internalize anchors used by the machine module info, else the info
181   // won't find them.  (see MachineModuleInfo.)
182   ExternalNames.insert("llvm.global_ctors");
183   ExternalNames.insert("llvm.global_dtors");
184   ExternalNames.insert("llvm.global.annotations");
185
186   // Never internalize symbols code-gen inserts.
187   // FIXME: We should probably add this (and the __stack_chk_guard) via some
188   // type of call-back in CodeGen.
189   ExternalNames.insert("__stack_chk_fail");
190   ExternalNames.insert("__stack_chk_guard");
191
192   // Mark all global variables with initializers that are not in the api as
193   // internal as well.
194   // FIXME: maybe use private linkage?
195   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
196        I != E; ++I) {
197     if (!shouldInternalize(*I, ExternalNames))
198       continue;
199
200     I->setLinkage(GlobalValue::InternalLinkage);
201     Changed = true;
202     ++NumGlobals;
203     DEBUG(dbgs() << "Internalized gvar " << I->getName() << "\n");
204   }
205
206   // Mark all aliases that are not in the api as internal as well.
207   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
208        I != E; ++I) {
209     if (!shouldInternalize(*I, ExternalNames))
210       continue;
211
212     I->setLinkage(GlobalValue::InternalLinkage);
213     Changed = true;
214     ++NumAliases;
215     DEBUG(dbgs() << "Internalized alias " << I->getName() << "\n");
216   }
217
218   return Changed;
219 }
220
221 ModulePass *llvm::createInternalizePass() {
222   return new InternalizePass();
223 }
224
225 ModulePass *llvm::createInternalizePass(ArrayRef<const char *> ExportList) {
226   return new InternalizePass(ExportList);
227 }