1
0
mirror of https://github.com/RPCS3/llvm-mirror.git synced 2025-01-31 12:41:49 +01:00

Use LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN instead of the "dso list".

There are two ways one could implement hiding of linkonce_odr symbols in LTO:
* LLVM tells the linker which symbols can be hidden if not used from native
  files.
* The linker tells LLVM which symbols are not used from other object files,
  but will be put in the dso symbol table if present.

GOLD's API is the second option. It was implemented almost 1:1 in llvm by
passing the list down to internalize.

LLVM already had partial support for the first option. It is also very similar
to how ld64 handles hiding these symbols when *not* doing LTO.

This patch then
* removes the APIs for the DSO list.
* marks LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN all linkonce_odr unnamed_addr
  global values and other linkonce_odr whose address is not used.
* makes the gold plugin responsible for handling the API mismatch.

llvm-svn: 193800
This commit is contained in:
Rafael Espindola 2013-10-31 20:51:58 +00:00
parent b603d15176
commit 24353f2de2
14 changed files with 96 additions and 130 deletions

View File

@ -270,15 +270,6 @@ lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args,
extern void extern void
lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol); lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol);
/**
* Tells LTO optimization passes that a dynamic shared library is being
* built and this symbol may be exported. Unless IR semantics allow the symbol
* to be made local to the library, it should remain so it can be exported by
* the shared library.
*/
extern void lto_codegen_add_dso_symbol(lto_code_gen_t cg, const char *symbol);
/** /**
* Writes a new object file at the specified path that contains the * Writes a new object file at the specified path that contains the
* merged contents of all modules added so far. * merged contents of all modules added so far.

View File

@ -73,10 +73,6 @@ struct LTOCodeGenerator {
void addMustPreserveSymbol(const char *sym) { MustPreserveSymbols[sym] = 1; } void addMustPreserveSymbol(const char *sym) { MustPreserveSymbols[sym] = 1; }
void addDSOSymbol(const char* Sym) {
DSOSymbols[Sym] = 1;
}
// To pass options to the driver and optimization passes. These options are // To pass options to the driver and optimization passes. These options are
// not necessarily for debugging purpose (The function name is misleading). // not necessarily for debugging purpose (The function name is misleading).
// This function should be called before LTOCodeGenerator::compilexxx(), // This function should be called before LTOCodeGenerator::compilexxx(),
@ -130,7 +126,6 @@ private:
void applyScopeRestrictions(); void applyScopeRestrictions();
void applyRestriction(llvm::GlobalValue &GV, void applyRestriction(llvm::GlobalValue &GV,
std::vector<const char*> &MustPreserveList, std::vector<const char*> &MustPreserveList,
std::vector<const char*> &SymtabList,
llvm::SmallPtrSet<llvm::GlobalValue*, 8> &AsmUsed, llvm::SmallPtrSet<llvm::GlobalValue*, 8> &AsmUsed,
llvm::Mangler &Mangler); llvm::Mangler &Mangler);
bool determineTarget(std::string &errMsg); bool determineTarget(std::string &errMsg);
@ -143,7 +138,6 @@ private:
bool EmitDwarfDebugInfo; bool EmitDwarfDebugInfo;
bool ScopeRestrictionsDone; bool ScopeRestrictionsDone;
lto_codegen_model CodeModel; lto_codegen_model CodeModel;
StringSet DSOSymbols;
StringSet MustPreserveSymbols; StringSet MustPreserveSymbols;
StringSet AsmUndefinedRefs; StringSet AsmUndefinedRefs;
llvm::MemoryBuffer *NativeObjectFile; llvm::MemoryBuffer *NativeObjectFile;

View File

@ -111,25 +111,9 @@ Pass *createPruneEHPass();
/// The symbol in DSOList are internalized if it is safe to drop them from /// The symbol in DSOList are internalized if it is safe to drop them from
/// the symbol table. /// the symbol table.
/// ///
/// For example of the difference, consider a dynamic library being built from
/// two translation units. The first one compiled to a native object
/// (ELF/MachO/COFF) and second one compiled to IL. Translation unit A has a
/// copy of linkonce_odr unnamed_addr function F. The translation unit B has a
/// copy of the linkonce_odr unnamed_addr functions F and G.
///
/// Assume the linker decides to keep the copy of F in B. This means that LLVM
/// must produce F in the object file it passes to the linker, otherwise we
/// will have an undefined reference. For G the situation is different. The
/// linker puts the function in the DSOList, since it is only wanted for the
/// symbol table. With this information internalize can now reason that since
/// the function is a linkonce_odr and its address is not important, it can be
/// omitted. Any other shared library needing this function will have a copy of
/// it.
///
/// Note that commandline options that are used with the above function are not /// Note that commandline options that are used with the above function are not
/// used now! /// used now!
ModulePass *createInternalizePass(ArrayRef<const char *> ExportList, ModulePass *createInternalizePass(ArrayRef<const char *> ExportList);
ArrayRef<const char *> DSOList);
/// createInternalizePass - Same as above, but with an empty exportList. /// createInternalizePass - Same as above, but with an empty exportList.
ModulePass *createInternalizePass(); ModulePass *createInternalizePass();

View File

@ -313,7 +313,6 @@ bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
void LTOCodeGenerator:: void LTOCodeGenerator::
applyRestriction(GlobalValue &GV, applyRestriction(GlobalValue &GV,
std::vector<const char*> &MustPreserveList, std::vector<const char*> &MustPreserveList,
std::vector<const char*> &DSOList,
SmallPtrSet<GlobalValue*, 8> &AsmUsed, SmallPtrSet<GlobalValue*, 8> &AsmUsed,
Mangler &Mangler) { Mangler &Mangler) {
SmallString<64> Buffer; SmallString<64> Buffer;
@ -323,8 +322,6 @@ applyRestriction(GlobalValue &GV,
return; return;
if (MustPreserveSymbols.count(Buffer)) if (MustPreserveSymbols.count(Buffer))
MustPreserveList.push_back(GV.getName().data()); MustPreserveList.push_back(GV.getName().data());
if (DSOSymbols.count(Buffer))
DSOList.push_back(GV.getName().data());
if (AsmUndefinedRefs.count(Buffer)) if (AsmUndefinedRefs.count(Buffer))
AsmUsed.insert(&GV); AsmUsed.insert(&GV);
} }
@ -352,18 +349,17 @@ void LTOCodeGenerator::applyScopeRestrictions() {
// mark which symbols can not be internalized // mark which symbols can not be internalized
Mangler Mangler(TargetMach); Mangler Mangler(TargetMach);
std::vector<const char*> MustPreserveList; std::vector<const char*> MustPreserveList;
std::vector<const char*> DSOList;
SmallPtrSet<GlobalValue*, 8> AsmUsed; SmallPtrSet<GlobalValue*, 8> AsmUsed;
for (Module::iterator f = mergedModule->begin(), for (Module::iterator f = mergedModule->begin(),
e = mergedModule->end(); f != e; ++f) e = mergedModule->end(); f != e; ++f)
applyRestriction(*f, MustPreserveList, DSOList, AsmUsed, Mangler); applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
for (Module::global_iterator v = mergedModule->global_begin(), for (Module::global_iterator v = mergedModule->global_begin(),
e = mergedModule->global_end(); v != e; ++v) e = mergedModule->global_end(); v != e; ++v)
applyRestriction(*v, MustPreserveList, DSOList, AsmUsed, Mangler); applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
for (Module::alias_iterator a = mergedModule->alias_begin(), for (Module::alias_iterator a = mergedModule->alias_begin(),
e = mergedModule->alias_end(); a != e; ++a) e = mergedModule->alias_end(); a != e; ++a)
applyRestriction(*a, MustPreserveList, DSOList, AsmUsed, Mangler); applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
GlobalVariable *LLVMCompilerUsed = GlobalVariable *LLVMCompilerUsed =
mergedModule->getGlobalVariable("llvm.compiler.used"); mergedModule->getGlobalVariable("llvm.compiler.used");
@ -391,7 +387,7 @@ void LTOCodeGenerator::applyScopeRestrictions() {
LLVMCompilerUsed->setSection("llvm.metadata"); LLVMCompilerUsed->setSection("llvm.metadata");
} }
passes.add(createInternalizePass(MustPreserveList, DSOList)); passes.add(createInternalizePass(MustPreserveList));
// apply scope restrictions // apply scope restrictions
passes.run(*mergedModule); passes.run(*mergedModule);

View File

@ -38,6 +38,7 @@
#include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetSelect.h"
#include "llvm/Support/system_error.h" #include "llvm/Support/system_error.h"
#include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
using namespace llvm; using namespace llvm;
LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t) LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
@ -162,6 +163,8 @@ LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr, TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
options); options);
m->MaterializeAllPermanently();
LTOModule *Ret = new LTOModule(m.take(), target); LTOModule *Ret = new LTOModule(m.take(), target);
if (Ret->parseSymbols(errMsg)) { if (Ret->parseSymbols(errMsg)) {
delete Ret; delete Ret;
@ -333,6 +336,25 @@ void LTOModule::addDefinedFunctionSymbol(const Function *f) {
addDefinedSymbol(f, true); addDefinedSymbol(f, true);
} }
static bool canBeHidden(const GlobalValue *GV) {
GlobalValue::LinkageTypes L = GV->getLinkage();
if (L == GlobalValue::LinkOnceODRAutoHideLinkage)
return true;
if (L != GlobalValue::LinkOnceODRLinkage)
return false;
if (GV->hasUnnamedAddr())
return true;
GlobalStatus GS;
if (GlobalStatus::analyzeGlobal(GV, GS))
return false;
return !GS.IsCompared;
}
/// addDefinedSymbol - Add a defined symbol to the list. /// addDefinedSymbol - Add a defined symbol to the list.
void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) { void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
// ignore all llvm.* symbols // ignore all llvm.* symbols
@ -372,12 +394,12 @@ void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
attr |= LTO_SYMBOL_SCOPE_HIDDEN; attr |= LTO_SYMBOL_SCOPE_HIDDEN;
else if (def->hasProtectedVisibility()) else if (def->hasProtectedVisibility())
attr |= LTO_SYMBOL_SCOPE_PROTECTED; attr |= LTO_SYMBOL_SCOPE_PROTECTED;
else if (canBeHidden(def))
attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
else if (def->hasExternalLinkage() || def->hasWeakLinkage() || else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
def->hasLinkOnceLinkage() || def->hasCommonLinkage() || def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
def->hasLinkerPrivateWeakLinkage()) def->hasLinkerPrivateWeakLinkage())
attr |= LTO_SYMBOL_SCOPE_DEFAULT; attr |= LTO_SYMBOL_SCOPE_DEFAULT;
else if (def->hasLinkOnceODRAutoHideLinkage())
attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
else else
attr |= LTO_SYMBOL_SCOPE_INTERNAL; attr |= LTO_SYMBOL_SCOPE_INTERNAL;

View File

@ -98,7 +98,7 @@ void LLVMAddInternalizePass(LLVMPassManagerRef PM, unsigned AllButMain) {
std::vector<const char *> Export; std::vector<const char *> Export;
if (AllButMain) if (AllButMain)
Export.push_back("main"); Export.push_back("main");
unwrap(PM)->add(createInternalizePass(Export, None)); unwrap(PM)->add(createInternalizePass(Export));
} }
void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM) { void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM) {

View File

@ -11,18 +11,11 @@
// If the function or variable is not in the list of external names given to // If the function or variable is not in the list of external names given to
// the pass it is marked as internal. // the pass it is marked as internal.
// //
// This transformation would not be legal or profitable in a regular // This transformation would not be legal in a regular compilation, but it gets
// compilation, but it gets extra information from the linker about what is safe // extra information from the linker about what is safe.
// or profitable.
// //
// As an example of a normally illegal transformation: Internalizing a function // For example: Internalizing a function with external linkage. Only if we are
// with external linkage. Only if we are told it is only used from within this // told it is only used from within this module, it is safe to do it.
// module, it is safe to do it.
//
// On the profitability side: It is always legal to internalize a linkonce_odr
// whose address is not used. Doing so normally would introduce code bloat, but
// if we are told by the linker that the only use of this would be for a
// DSO symbol table, it is profitable to hide it.
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@ -58,20 +51,13 @@ APIList("internalize-public-api-list", cl::value_desc("list"),
cl::desc("A list of symbol names to preserve"), cl::desc("A list of symbol names to preserve"),
cl::CommaSeparated); cl::CommaSeparated);
static cl::list<std::string>
DSOList("internalize-dso-list", cl::value_desc("list"),
cl::desc("A list of symbol names need for a dso symbol table"),
cl::CommaSeparated);
namespace { namespace {
class InternalizePass : public ModulePass { class InternalizePass : public ModulePass {
std::set<std::string> ExternalNames; std::set<std::string> ExternalNames;
std::set<std::string> DSONames;
public: public:
static char ID; // Pass identification, replacement for typeid static char ID; // Pass identification, replacement for typeid
explicit InternalizePass(); explicit InternalizePass();
explicit InternalizePass(ArrayRef<const char *> ExportList, explicit InternalizePass(ArrayRef<const char *> ExportList);
ArrayRef<const char *> DSOList);
void LoadFile(const char *Filename); void LoadFile(const char *Filename);
virtual bool runOnModule(Module &M); virtual bool runOnModule(Module &M);
@ -92,21 +78,15 @@ InternalizePass::InternalizePass()
if (!APIFile.empty()) // If a filename is specified, use it. if (!APIFile.empty()) // If a filename is specified, use it.
LoadFile(APIFile.c_str()); LoadFile(APIFile.c_str());
ExternalNames.insert(APIList.begin(), APIList.end()); ExternalNames.insert(APIList.begin(), APIList.end());
DSONames.insert(DSOList.begin(), DSOList.end());
} }
InternalizePass::InternalizePass(ArrayRef<const char *> ExportList, InternalizePass::InternalizePass(ArrayRef<const char *> ExportList)
ArrayRef<const char *> DSOList)
: ModulePass(ID){ : ModulePass(ID){
initializeInternalizePassPass(*PassRegistry::getPassRegistry()); initializeInternalizePassPass(*PassRegistry::getPassRegistry());
for(ArrayRef<const char *>::const_iterator itr = ExportList.begin(); for(ArrayRef<const char *>::const_iterator itr = ExportList.begin();
itr != ExportList.end(); itr++) { itr != ExportList.end(); itr++) {
ExternalNames.insert(*itr); ExternalNames.insert(*itr);
} }
for(ArrayRef<const char *>::const_iterator itr = DSOList.begin();
itr != DSOList.end(); itr++) {
DSONames.insert(*itr);
}
} }
void InternalizePass::LoadFile(const char *Filename) { void InternalizePass::LoadFile(const char *Filename) {
@ -126,8 +106,7 @@ void InternalizePass::LoadFile(const char *Filename) {
} }
static bool shouldInternalize(const GlobalValue &GV, static bool shouldInternalize(const GlobalValue &GV,
const std::set<std::string> &ExternalNames, const std::set<std::string> &ExternalNames) {
const std::set<std::string> &DSONames) {
// Function must be defined here // Function must be defined here
if (GV.isDeclaration()) if (GV.isDeclaration())
return false; return false;
@ -144,23 +123,7 @@ static bool shouldInternalize(const GlobalValue &GV,
if (ExternalNames.count(GV.getName())) if (ExternalNames.count(GV.getName()))
return false; return false;
// Not needed for the symbol table? return true;
if (!DSONames.count(GV.getName()))
return true;
// Not a linkonce. Someone can depend on it being on the symbol table.
if (!GV.hasLinkOnceLinkage())
return false;
// The address is not important, we can hide it.
if (GV.hasUnnamedAddr())
return true;
GlobalStatus GS;
if (GlobalStatus::analyzeGlobal(&GV, GS))
return false;
return !GS.IsCompared;
} }
bool InternalizePass::runOnModule(Module &M) { bool InternalizePass::runOnModule(Module &M) {
@ -189,7 +152,7 @@ bool InternalizePass::runOnModule(Module &M) {
// Mark all functions not in the api as internal. // Mark all functions not in the api as internal.
// FIXME: maybe use private linkage? // FIXME: maybe use private linkage?
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (!shouldInternalize(*I, ExternalNames, DSONames)) if (!shouldInternalize(*I, ExternalNames))
continue; continue;
I->setLinkage(GlobalValue::InternalLinkage); I->setLinkage(GlobalValue::InternalLinkage);
@ -226,7 +189,7 @@ bool InternalizePass::runOnModule(Module &M) {
// FIXME: maybe use private linkage? // FIXME: maybe use private linkage?
for (Module::global_iterator I = M.global_begin(), E = M.global_end(); for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I) { I != E; ++I) {
if (!shouldInternalize(*I, ExternalNames, DSONames)) if (!shouldInternalize(*I, ExternalNames))
continue; continue;
I->setLinkage(GlobalValue::InternalLinkage); I->setLinkage(GlobalValue::InternalLinkage);
@ -238,7 +201,7 @@ bool InternalizePass::runOnModule(Module &M) {
// Mark all aliases that are not in the api as internal as well. // Mark all aliases that are not in the api as internal as well.
for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
I != E; ++I) { I != E; ++I) {
if (!shouldInternalize(*I, ExternalNames, DSONames)) if (!shouldInternalize(*I, ExternalNames))
continue; continue;
I->setLinkage(GlobalValue::InternalLinkage); I->setLinkage(GlobalValue::InternalLinkage);
@ -254,7 +217,6 @@ ModulePass *llvm::createInternalizePass() {
return new InternalizePass(); return new InternalizePass();
} }
ModulePass *llvm::createInternalizePass(ArrayRef<const char *> ExportList, ModulePass *llvm::createInternalizePass(ArrayRef<const char *> ExportList) {
ArrayRef<const char *> DSOList) { return new InternalizePass(ExportList);
return new InternalizePass(ExportList, DSOList);
} }

View File

@ -277,7 +277,7 @@ void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
// for a main function. If main is defined, mark all other functions // for a main function. If main is defined, mark all other functions
// internal. // internal.
if (Internalize) if (Internalize)
PM.add(createInternalizePass("main", None)); PM.add(createInternalizePass("main"));
// Propagate constants at call sites into the functions they call. This // Propagate constants at call sites into the functions they call. This
// opens opportunities for globalopt (and inlining) by substituting function // opens opportunities for globalopt (and inlining) by substituting function

View File

@ -1,27 +1,32 @@
; RUN: opt < %s -internalize -internalize-dso-list foo1,foo2,foo3,foo4 -S | FileCheck %s ; RUN: llvm-as < %s >%t1
; RUN: llvm-lto -o %t2 -dso-symbol=foo1 -dso-symbol=foo2 -dso-symbol=foo3 \
; RUN: -dso-symbol=foo4 %t1 -disable-opt
; RUN: llvm-nm %t2 | FileCheck %s
; CHECK: define internal void @foo1( ; CHECK: t foo1
define linkonce_odr void @foo1() noinline { define linkonce_odr void @foo1() noinline {
ret void ret void
} }
; CHECK: define linkonce_odr void @foo2( ; CHECK: W foo2
define linkonce_odr void @foo2() noinline { define linkonce_odr void @foo2() noinline {
ret void ret void
} }
; CHECK: define internal void @foo3( ; CHECK: t foo3
define linkonce_odr void @foo3() noinline { define linkonce_odr void @foo3() noinline {
ret void ret void
} }
; CHECK: define linkonce_odr void @foo4( ; CHECK: W foo4
define linkonce_odr void @foo4() noinline { define linkonce_odr void @foo4() noinline {
ret void ret void
} }
declare void @f(void()*) declare void @f(void()*)
declare void @p()
define void @bar() { define void @bar() {
bb0: bb0:
call void @foo1() call void @foo1()
@ -32,6 +37,6 @@ bb1:
bb2: bb2:
ret void ret void
clean: clean:
landingpad i32 personality i8* null cleanup landingpad {i32, i32} personality void()* @p cleanup
ret void ret void
} }

View File

@ -13,10 +13,6 @@
; -file and -list options should be merged, the apifile contains foo and j ; -file and -list options should be merged, the apifile contains foo and j
; RUN: opt < %s -internalize -internalize-public-api-list bar -internalize-public-api-file %S/apifile -S | FileCheck --check-prefix=FOO_J_AND_BAR %s ; RUN: opt < %s -internalize -internalize-public-api-list bar -internalize-public-api-file %S/apifile -S | FileCheck --check-prefix=FOO_J_AND_BAR %s
; Put zed1 and zed2 in the symbol table. If the address is not relevant, we
; internalize them.
; RUN: opt < %s -internalize -internalize-dso-list zed1,zed2,zed3 -S | FileCheck --check-prefix=ZEDS %s
; ALL: @i = internal global ; ALL: @i = internal global
; FOO_AND_J: @i = internal global ; FOO_AND_J: @i = internal global
; FOO_AND_BAR: @i = internal global ; FOO_AND_BAR: @i = internal global
@ -29,18 +25,6 @@
; FOO_J_AND_BAR: @j = global ; FOO_J_AND_BAR: @j = global
@j = global i32 0 @j = global i32 0
; ZEDS: @zed1 = internal global i32 42
@zed1 = linkonce_odr global i32 42
; ZEDS: @zed2 = internal unnamed_addr global i32 42
@zed2 = linkonce_odr unnamed_addr global i32 42
; ZEDS: @zed3 = linkonce_odr global i32 42
@zed3 = linkonce_odr global i32 42
define i32* @get_zed3() {
ret i32* @zed3
}
; ALL: define internal void @main() { ; ALL: define internal void @main() {
; FOO_AND_J: define internal void @main() { ; FOO_AND_J: define internal void @main() {
; FOO_AND_BAR: define internal void @main() { ; FOO_AND_BAR: define internal void @main() {

View File

@ -15,6 +15,7 @@
#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
#include "plugin-api.h" #include "plugin-api.h"
#include "llvm-c/lto.h" #include "llvm-c/lto.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/OwningPtr.h"
#include "llvm/Support/Errno.h" #include "llvm/Support/Errno.h"
#include "llvm/Support/FileSystem.h" #include "llvm/Support/FileSystem.h"
@ -67,6 +68,7 @@ namespace {
std::list<claimed_file> Modules; std::list<claimed_file> Modules;
std::vector<std::string> Cleanup; std::vector<std::string> Cleanup;
lto_code_gen_t code_gen = NULL; lto_code_gen_t code_gen = NULL;
StringSet<> CannotBeHidden;
} }
namespace options { namespace options {
@ -297,6 +299,9 @@ static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
sym.version = NULL; sym.version = NULL;
int scope = attrs & LTO_SYMBOL_SCOPE_MASK; int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
bool CanBeHidden = scope == LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
if (!CanBeHidden)
CannotBeHidden.insert(sym.name);
switch (scope) { switch (scope) {
case LTO_SYMBOL_SCOPE_HIDDEN: case LTO_SYMBOL_SCOPE_HIDDEN:
sym.visibility = LDPV_HIDDEN; sym.visibility = LDPV_HIDDEN;
@ -306,6 +311,7 @@ static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
break; break;
case 0: // extern case 0: // extern
case LTO_SYMBOL_SCOPE_DEFAULT: case LTO_SYMBOL_SCOPE_DEFAULT:
case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
sym.visibility = LDPV_DEFAULT; sym.visibility = LDPV_DEFAULT;
break; break;
default: default:
@ -364,6 +370,14 @@ static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
return LDPS_OK; return LDPS_OK;
} }
static bool mustPreserve(const claimed_file &F, int i) {
if (F.syms[i].resolution == LDPR_PREVAILING_DEF)
return true;
if (F.syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP)
return CannotBeHidden.count(F.syms[i].name);
return false;
}
/// all_symbols_read_hook - gold informs us that all symbols have been read. /// all_symbols_read_hook - gold informs us that all symbols have been read.
/// At this point, we use get_symbols to see if any of our definitions have /// At this point, we use get_symbols to see if any of our definitions have
/// been overridden by a native object file. Then, perform optimization and /// been overridden by a native object file. Then, perform optimization and
@ -386,16 +400,11 @@ static ld_plugin_status all_symbols_read_hook(void) {
continue; continue;
(*get_symbols)(I->handle, I->syms.size(), &I->syms[0]); (*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
for (unsigned i = 0, e = I->syms.size(); i != e; i++) { for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
if (I->syms[i].resolution == LDPR_PREVAILING_DEF) { if (mustPreserve(*I, i)) {
lto_codegen_add_must_preserve_symbol(code_gen, I->syms[i].name); lto_codegen_add_must_preserve_symbol(code_gen, I->syms[i].name);
if (options::generate_api_file) if (options::generate_api_file)
api_file << I->syms[i].name << "\n"; api_file << I->syms[i].name << "\n";
} else if (I->syms[i].resolution == LDPR_PREVAILING_DEF_IRONLY_EXP) {
lto_codegen_add_dso_symbol(code_gen, I->syms[i].name);
if (options::generate_api_file)
api_file << I->syms[i].name << " dso only\n";
} }
} }
} }

View File

@ -12,6 +12,7 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "llvm/ADT/StringSet.h"
#include "llvm/CodeGen/CommandFlags.h" #include "llvm/CodeGen/CommandFlags.h"
#include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/LTO/LTOCodeGenerator.h"
#include "llvm/LTO/LTOModule.h" #include "llvm/LTO/LTOModule.h"
@ -55,6 +56,12 @@ DSOSymbols("dso-symbol",
cl::desc("Symbol to put in the symtab in the resulting dso"), cl::desc("Symbol to put in the symtab in the resulting dso"),
cl::ZeroOrMore); cl::ZeroOrMore);
namespace {
struct ModuleInfo {
std::vector<bool> CanBeHidden;
};
}
int main(int argc, char **argv) { int main(int argc, char **argv) {
// Print a stack trace if we signal out. // Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal(); sys::PrintStackTraceOnErrorSignal();
@ -99,6 +106,12 @@ int main(int argc, char **argv) {
CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF); CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
CodeGen.setTargetOptions(Options); CodeGen.setTargetOptions(Options);
llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
for (unsigned i = 0; i < DSOSymbols.size(); ++i)
DSOSymbolsSet.insert(DSOSymbols[i]);
std::vector<std::string> KeptDSOSyms;
for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) { for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
std::string error; std::string error;
OwningPtr<LTOModule> Module(LTOModule::makeLTOModule(InputFilenames[i].c_str(), OwningPtr<LTOModule> Module(LTOModule::makeLTOModule(InputFilenames[i].c_str(),
@ -115,6 +128,17 @@ int main(int argc, char **argv) {
<< "': " << error << "\n"; << "': " << error << "\n";
return 1; return 1;
} }
unsigned NumSyms = Module->getSymbolCount();
for (unsigned I = 0; I < NumSyms; ++I) {
StringRef Name = Module->getSymbolName(I);
if (!DSOSymbolsSet.count(Name))
continue;
lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
KeptDSOSyms.push_back(Name);
}
} }
// Add all the exported symbols to the table of symbols to preserve. // Add all the exported symbols to the table of symbols to preserve.
@ -122,8 +146,8 @@ int main(int argc, char **argv) {
CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str()); CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
// Add all the dso symbols to the table of symbols to expose. // Add all the dso symbols to the table of symbols to expose.
for (unsigned i = 0; i < DSOSymbols.size(); ++i) for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
CodeGen.addDSOSymbol(DSOSymbols[i].c_str()); CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
if (!OutputFilename.empty()) { if (!OutputFilename.empty()) {
size_t len = 0; size_t len = 0;

View File

@ -260,10 +260,6 @@ void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg,
cg->addMustPreserveSymbol(symbol); cg->addMustPreserveSymbol(symbol);
} }
void lto_codegen_add_dso_symbol(lto_code_gen_t cg, const char *symbol) {
cg->addDSOSymbol(symbol);
}
/// lto_codegen_write_merged_modules - Writes a new file at the specified path /// lto_codegen_write_merged_modules - Writes a new file at the specified path
/// that contains the merged contents of all modules added so far. Returns true /// that contains the merged contents of all modules added so far. Returns true
/// on error (check lto_get_error_message() for details). /// on error (check lto_get_error_message() for details).

View File

@ -15,7 +15,6 @@ lto_module_is_object_file_for_target
lto_module_is_object_file_in_memory lto_module_is_object_file_in_memory
lto_module_is_object_file_in_memory_for_target lto_module_is_object_file_in_memory_for_target
lto_module_dispose lto_module_dispose
lto_codegen_add_dso_symbol
lto_codegen_add_module lto_codegen_add_module
lto_codegen_add_must_preserve_symbol lto_codegen_add_must_preserve_symbol
lto_codegen_compile lto_codegen_compile