Internalize.cpp 7.8 KB

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