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