Skip to content

[lld][MachO]Multi-threaded i/o. Twice as fast linking a large project. #147134

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lld/MachO/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ struct Configuration {
bool interposable = false;
bool errorForArchMismatch = false;
bool ignoreAutoLink = false;
int readThreads = 0;
// ld64 allows invalid auto link options as long as the link succeeds. LLD
// does not, but there are cases in the wild where the invalid linker options
// exist. This allows users to ignore the specific invalid options in the case
Expand Down
168 changes: 158 additions & 10 deletions lld/MachO/Driver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TarWriter.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TimeProfiler.h"
Expand Down Expand Up @@ -282,11 +283,103 @@ static void saveThinArchiveToRepro(ArchiveFile const *file) {
": Archive::children failed: " + toString(std::move(e)));
}

static InputFile *addFile(StringRef path, LoadType loadType,
bool isLazy = false, bool isExplicit = true,
bool isBundleLoader = false,
bool isForceHidden = false) {
std::optional<MemoryBufferRef> buffer = readFile(path);
typedef struct {
StringRef path;
bool isLazy;
std::optional<MemoryBufferRef> buffer;
const char *start;
size_t size;
} DeferredFile;
typedef std::vector<DeferredFile> DeferredFiles;

#ifndef _WIN32
typedef struct {
DeferredFiles deferred;
size_t counter, total, pageSize;
pthread_mutex_t mutex;
} PageInState;

// Most input files have been mapped but not yet paged in.
// This code forces the page-ins on multiple threads so
// the process is not stalled waiting on disk buffer i/o.
static void multiThreadedPageInBackground(PageInState *state) {
#define MaxReadThreads 200
static size_t totalBytes;

pthread_t running[MaxReadThreads];
if (config->readThreads > MaxReadThreads)
config->readThreads = MaxReadThreads;
pthread_mutex_init(&state->mutex, nullptr);

for (int t = 0; t < config->readThreads; t++)
pthread_create(
&running[t], nullptr,
[](void *ptr) -> void * {
PageInState &state = *(PageInState *)ptr;
while (true) {
pthread_mutex_lock(&state.mutex);
if (state.counter >= state.deferred.size()) {
pthread_mutex_unlock(&state.mutex);
return nullptr;
}
DeferredFile &file = state.deferred[state.counter];
state.counter += 1;
pthread_mutex_unlock(&state.mutex);

const char *page = file.start, *end = page + file.size;
totalBytes += end - page;

int t = 0; // Reference each page to load it into memory.
for (; page < end; page += state.pageSize)
t += *page;
state.total += t; // Avoids the loop being optimised out.
}
},
state);

for (int t = 0; t < config->readThreads; t++)
pthread_join(running[t], nullptr);

pthread_mutex_destroy(&state->mutex);
if (getenv("LLD_MULTI_THREAD_PAGE"))
printf("multiThreadedPageIn %ld/%ld\n", totalBytes, state->deferred.size());
}
#endif

static void multiThreadedPageIn(DeferredFiles deferred) {
#ifndef _WIN32
static pthread_t running;
static pthread_mutex_t busy;

if (running)
pthread_join(running, nullptr);
else
pthread_mutex_init(&busy, nullptr);

PageInState *state =
new PageInState{deferred, 0, 0, llvm::sys::Process::getPageSizeEstimate(),
pthread_mutex_t()};

pthread_mutex_lock(&busy);
pthread_create(
&running, nullptr,
[](void *ptr) -> void * {
PageInState *state = (PageInState *)ptr;
multiThreadedPageInBackground(state);
pthread_mutex_unlock(&busy);
delete state;
return nullptr;
},
state);
#endif
}

static InputFile *processFile(std::optional<MemoryBufferRef> buffer,
DeferredFiles *archiveContents, StringRef path,
LoadType loadType, bool isLazy = false,
bool isExplicit = true,
bool isBundleLoader = false,
bool isForceHidden = false) {
if (!buffer)
return nullptr;
MemoryBufferRef mbref = *buffer;
Expand Down Expand Up @@ -379,6 +472,10 @@ static InputFile *addFile(StringRef path, LoadType loadType,
continue;
}

if (archiveContents)
archiveContents->push_back({path, isLazy, std::nullopt,
mb->getBuffer().data(),
mb->getBuffer().size()});
if (!hasObjCSection(*mb))
continue;
if (Error e = file->fetch(c, "-ObjC"))
Expand All @@ -390,7 +487,8 @@ static InputFile *addFile(StringRef path, LoadType loadType,
": Archive::children failed: " + toString(std::move(e)));
}
}
file->addLazySymbols();
if (!archiveContents || archiveContents->empty())
file->addLazySymbols();
loadedArchives[path] = ArchiveFileInfo{file, isCommandLineLoad};
newFile = file;
break;
Expand Down Expand Up @@ -441,6 +539,23 @@ static InputFile *addFile(StringRef path, LoadType loadType,
return newFile;
}

static InputFile *addFile(StringRef path, LoadType loadType,
bool isLazy = false, bool isExplicit = true,
bool isBundleLoader = false,
bool isForceHidden = false) {
return processFile(readFile(path), nullptr, path, loadType, isLazy,
isExplicit, isBundleLoader, isForceHidden);
}

static void deferFile(StringRef path, bool isLazy, DeferredFiles &deferred) {
std::optional<MemoryBufferRef> buffer = readFile(path);
if (config->readThreads)
deferred.push_back({path, isLazy, buffer, buffer->getBuffer().data(),
buffer->getBuffer().size()});
else
processFile(buffer, nullptr, path, LoadType::CommandLine, isLazy);
}

static std::vector<StringRef> missingAutolinkWarnings;
static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
bool isReexport, bool isHidden, bool isExplicit,
Expand Down Expand Up @@ -564,13 +679,14 @@ void macho::resolveLCLinkerOptions() {
}
}

static void addFileList(StringRef path, bool isLazy) {
static void addFileList(StringRef path, bool isLazy,
DeferredFiles &deferredFiles) {
std::optional<MemoryBufferRef> buffer = readFile(path);
if (!buffer)
return;
MemoryBufferRef mbref = *buffer;
for (StringRef path : args::getLines(mbref))
addFile(rerootPath(path), LoadType::CommandLine, isLazy);
deferFile(rerootPath(path), isLazy, deferredFiles);
}

// We expect sub-library names of the form "libfoo", which will match a dylib
Expand Down Expand Up @@ -1222,14 +1338,16 @@ static void createFiles(const InputArgList &args) {
bool isLazy = false;
// If we've processed an opening --start-lib, without a matching --end-lib
bool inLib = false;
DeferredFiles deferredFiles;

for (const Arg *arg : args) {
const Option &opt = arg->getOption();
warnIfDeprecatedOption(opt);
warnIfUnimplementedOption(opt);

switch (opt.getID()) {
case OPT_INPUT:
addFile(rerootPath(arg->getValue()), LoadType::CommandLine, isLazy);
deferFile(rerootPath(arg->getValue()), isLazy, deferredFiles);
break;
case OPT_needed_library:
if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
Expand All @@ -1249,7 +1367,7 @@ static void createFiles(const InputArgList &args) {
dylibFile->forceWeakImport = true;
break;
case OPT_filelist:
addFileList(arg->getValue(), isLazy);
addFileList(arg->getValue(), isLazy, deferredFiles);
break;
case OPT_force_load:
addFile(rerootPath(arg->getValue()), LoadType::CommandLineForce);
Expand Down Expand Up @@ -1295,6 +1413,28 @@ static void createFiles(const InputArgList &args) {
break;
}
}

if (config->readThreads) {
multiThreadedPageIn(deferredFiles);

DeferredFiles archiveContents;
std::vector<ArchiveFile *> archives;
for (auto &file : deferredFiles)
if (ArchiveFile *archive = dyn_cast<ArchiveFile>(
processFile(file.buffer, &archiveContents, file.path,
LoadType::CommandLine, file.isLazy)))
archives.push_back(archive);

if (!archiveContents.empty()) {
multiThreadedPageIn(archiveContents);
for (auto *archive : archives)
archive->addLazySymbols();
}

// flush threads
deferredFiles.clear();
multiThreadedPageIn(deferredFiles);
}
}

static void gatherInputSections() {
Expand Down Expand Up @@ -1687,6 +1827,14 @@ bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
}
}

if (auto *arg = args.getLastArg(OPT_read_threads)) {
StringRef v(arg->getValue());
unsigned threads = 0;
if (!llvm::to_integer(v, threads, 0) || threads < 0)
error(arg->getSpelling() + ": expected a positive integer, but got '" +
arg->getValue() + "'");
config->readThreads = threads;
}
if (auto *arg = args.getLastArg(OPT_threads_eq)) {
StringRef v(arg->getValue());
unsigned threads = 0;
Expand Down
3 changes: 3 additions & 0 deletions lld/MachO/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,9 @@ def dead_strip : Flag<["-"], "dead_strip">,
def interposable : Flag<["-"], "interposable">,
HelpText<"Indirects access to all exported symbols in an image">,
Group<grp_opts>;
def read_threads : Joined<["--"], "read-threads=">,
HelpText<"Number of threads to use paging in files.">,
Group<grp_lld>;
def order_file : Separate<["-"], "order_file">,
MetaVarName<"<file>">,
HelpText<"Layout functions and data according to specification in <file>">,
Expand Down