LLVM API Documentation

Internalize.cpp
Go to the documentation of this file.
00001 //===-- Internalize.cpp - Mark functions internal -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass loops over all of the functions and variables in the input module.
00011 // If the function or variable is not in the list of external names given to
00012 // the pass it is marked as internal.
00013 //
00014 // This transformation would not be legal in a regular compilation, but it gets
00015 // extra information from the linker about what is safe.
00016 //
00017 // For example: Internalizing a function with external linkage. Only if we are
00018 // told it is only used from within this module, it is safe to do it.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #include "llvm/Transforms/IPO.h"
00023 #include "llvm/ADT/SmallPtrSet.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/Analysis/CallGraph.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Pass.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Transforms/Utils/GlobalStatus.h"
00032 #include "llvm/Transforms/Utils/ModuleUtils.h"
00033 #include <fstream>
00034 #include <set>
00035 using namespace llvm;
00036 
00037 #define DEBUG_TYPE "internalize"
00038 
00039 STATISTIC(NumAliases  , "Number of aliases internalized");
00040 STATISTIC(NumFunctions, "Number of functions internalized");
00041 STATISTIC(NumGlobals  , "Number of global vars internalized");
00042 
00043 // APIFile - A file which contains a list of symbols that should not be marked
00044 // external.
00045 static cl::opt<std::string>
00046 APIFile("internalize-public-api-file", cl::value_desc("filename"),
00047         cl::desc("A file containing list of symbol names to preserve"));
00048 
00049 // APIList - A list of symbols that should not be marked internal.
00050 static cl::list<std::string>
00051 APIList("internalize-public-api-list", cl::value_desc("list"),
00052         cl::desc("A list of symbol names to preserve"),
00053         cl::CommaSeparated);
00054 
00055 namespace {
00056   class InternalizePass : public ModulePass {
00057     std::set<std::string> ExternalNames;
00058   public:
00059     static char ID; // Pass identification, replacement for typeid
00060     explicit InternalizePass();
00061     explicit InternalizePass(ArrayRef<const char *> ExportList);
00062     void LoadFile(const char *Filename);
00063     bool runOnModule(Module &M) override;
00064 
00065     void getAnalysisUsage(AnalysisUsage &AU) const override {
00066       AU.setPreservesCFG();
00067       AU.addPreserved<CallGraphWrapperPass>();
00068     }
00069   };
00070 } // end anonymous namespace
00071 
00072 char InternalizePass::ID = 0;
00073 INITIALIZE_PASS(InternalizePass, "internalize",
00074                 "Internalize Global Symbols", false, false)
00075 
00076 InternalizePass::InternalizePass() : ModulePass(ID) {
00077   initializeInternalizePassPass(*PassRegistry::getPassRegistry());
00078   if (!APIFile.empty())           // If a filename is specified, use it.
00079     LoadFile(APIFile.c_str());
00080   ExternalNames.insert(APIList.begin(), APIList.end());
00081 }
00082 
00083 InternalizePass::InternalizePass(ArrayRef<const char *> ExportList)
00084     : ModulePass(ID) {
00085   initializeInternalizePassPass(*PassRegistry::getPassRegistry());
00086   for(ArrayRef<const char *>::const_iterator itr = ExportList.begin();
00087         itr != ExportList.end(); itr++) {
00088     ExternalNames.insert(*itr);
00089   }
00090 }
00091 
00092 void InternalizePass::LoadFile(const char *Filename) {
00093   // Load the APIFile...
00094   std::ifstream In(Filename);
00095   if (!In.good()) {
00096     errs() << "WARNING: Internalize couldn't load file '" << Filename
00097          << "'! Continuing as if it's empty.\n";
00098     return; // Just continue as if the file were empty
00099   }
00100   while (In) {
00101     std::string Symbol;
00102     In >> Symbol;
00103     if (!Symbol.empty())
00104       ExternalNames.insert(Symbol);
00105   }
00106 }
00107 
00108 static bool shouldInternalize(const GlobalValue &GV,
00109                               const std::set<std::string> &ExternalNames) {
00110   // Function must be defined here
00111   if (GV.isDeclaration())
00112     return false;
00113 
00114   // Available externally is really just a "declaration with a body".
00115   if (GV.hasAvailableExternallyLinkage())
00116     return false;
00117 
00118   // Assume that dllexported symbols are referenced elsewhere
00119   if (GV.hasDLLExportStorageClass())
00120     return false;
00121 
00122   // Already has internal linkage
00123   if (GV.hasLocalLinkage())
00124     return false;
00125 
00126   // Marked to keep external?
00127   if (ExternalNames.count(GV.getName()))
00128     return false;
00129 
00130   return true;
00131 }
00132 
00133 bool InternalizePass::runOnModule(Module &M) {
00134   CallGraphWrapperPass *CGPass = getAnalysisIfAvailable<CallGraphWrapperPass>();
00135   CallGraph *CG = CGPass ? &CGPass->getCallGraph() : nullptr;
00136   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : nullptr;
00137   bool Changed = false;
00138 
00139   SmallPtrSet<GlobalValue *, 8> Used;
00140   collectUsedGlobalVariables(M, Used, false);
00141 
00142   // We must assume that globals in llvm.used have a reference that not even
00143   // the linker can see, so we don't internalize them.
00144   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
00145   // linker can drop those symbols. If this pass is running as part of LTO,
00146   // one might think that it could just drop llvm.compiler.used. The problem
00147   // is that even in LTO llvm doesn't see every reference. For example,
00148   // we don't see references from function local inline assembly. To be
00149   // conservative, we internalize symbols in llvm.compiler.used, but we
00150   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
00151   for (GlobalValue *V : Used) {
00152     ExternalNames.insert(V->getName());
00153   }
00154 
00155   // Mark all functions not in the api as internal.
00156   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00157     if (!shouldInternalize(*I, ExternalNames))
00158       continue;
00159 
00160     I->setVisibility(GlobalValue::DefaultVisibility);
00161     I->setLinkage(GlobalValue::InternalLinkage);
00162 
00163     if (ExternalNode)
00164       // Remove a callgraph edge from the external node to this function.
00165       ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
00166 
00167     Changed = true;
00168     ++NumFunctions;
00169     DEBUG(dbgs() << "Internalizing func " << I->getName() << "\n");
00170   }
00171 
00172   // Never internalize the llvm.used symbol.  It is used to implement
00173   // attribute((used)).
00174   // FIXME: Shouldn't this just filter on llvm.metadata section??
00175   ExternalNames.insert("llvm.used");
00176   ExternalNames.insert("llvm.compiler.used");
00177 
00178   // Never internalize anchors used by the machine module info, else the info
00179   // won't find them.  (see MachineModuleInfo.)
00180   ExternalNames.insert("llvm.global_ctors");
00181   ExternalNames.insert("llvm.global_dtors");
00182   ExternalNames.insert("llvm.global.annotations");
00183 
00184   // Never internalize symbols code-gen inserts.
00185   // FIXME: We should probably add this (and the __stack_chk_guard) via some
00186   // type of call-back in CodeGen.
00187   ExternalNames.insert("__stack_chk_fail");
00188   ExternalNames.insert("__stack_chk_guard");
00189 
00190   // Mark all global variables with initializers that are not in the api as
00191   // internal as well.
00192   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00193        I != E; ++I) {
00194     if (!shouldInternalize(*I, ExternalNames))
00195       continue;
00196 
00197     I->setVisibility(GlobalValue::DefaultVisibility);
00198     I->setLinkage(GlobalValue::InternalLinkage);
00199     Changed = true;
00200     ++NumGlobals;
00201     DEBUG(dbgs() << "Internalized gvar " << I->getName() << "\n");
00202   }
00203 
00204   // Mark all aliases that are not in the api as internal as well.
00205   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
00206        I != E; ++I) {
00207     if (!shouldInternalize(*I, ExternalNames))
00208       continue;
00209 
00210     I->setVisibility(GlobalValue::DefaultVisibility);
00211     I->setLinkage(GlobalValue::InternalLinkage);
00212     Changed = true;
00213     ++NumAliases;
00214     DEBUG(dbgs() << "Internalized alias " << I->getName() << "\n");
00215   }
00216 
00217   return Changed;
00218 }
00219 
00220 ModulePass *llvm::createInternalizePass() { return new InternalizePass(); }
00221 
00222 ModulePass *llvm::createInternalizePass(ArrayRef<const char *> ExportList) {
00223   return new InternalizePass(ExportList);
00224 }