#include "LTO.h"
#include "Config.h"
#include "InputFiles.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "lld/Common/Args.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Strings.h"
#include "lld/Common/TargetOptionsCommandFlags.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/LTO/Config.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Support/Caching.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <string>
#include <system_error>
#include <vector>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) {
std::error_code ec;
auto ret =
std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
if (ec) {
error("cannot open " + file + ": " + ec.message());
return nullptr;
}
return ret;
}
static std::unique_ptr<raw_fd_ostream> openLTOOutputFile(StringRef file) {
std::error_code ec;
std::unique_ptr<raw_fd_ostream> fs =
std::make_unique<raw_fd_stream>(file, ec);
if (!ec)
return fs;
return openFile(file);
}
static std::string getThinLTOOutputFile(StringRef modulePath) {
return lto::getThinLTOOutputFile(modulePath, config->thinLTOPrefixReplaceOld,
config->thinLTOPrefixReplaceNew);
}
static lto::Config createConfig() {
lto::Config c;
c.Options = initTargetOptionsFromCodeGenFlags();
c.Options.EmitAddrsig = true;
for (StringRef C : config->mllvmOpts)
c.MllvmArgs.emplace_back(C.str());
c.Options.FunctionSections = true;
c.Options.DataSections = true;
c.Options.BBAddrMap = config->ltoBBAddrMap;
if (!config->ltoBasicBlockSections.empty()) {
if (config->ltoBasicBlockSections == "all") {
c.Options.BBSections = BasicBlockSection::All;
} else if (config->ltoBasicBlockSections == "labels") {
c.Options.BBSections = BasicBlockSection::Labels;
} else if (config->ltoBasicBlockSections == "none") {
c.Options.BBSections = BasicBlockSection::None;
} else {
ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
MemoryBuffer::getFile(config->ltoBasicBlockSections.str());
if (!MBOrErr) {
error("cannot open " + config->ltoBasicBlockSections + ":" +
MBOrErr.getError().message());
} else {
c.Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
}
c.Options.BBSections = BasicBlockSection::List;
}
}
c.Options.UniqueBasicBlockSectionNames =
config->ltoUniqueBasicBlockSectionNames;
if (auto relocModel = getRelocModelFromCMModel())
c.RelocModel = *relocModel;
else if (config->relocatable)
c.RelocModel = std::nullopt;
else if (config->isPic)
c.RelocModel = Reloc::PIC_;
else
c.RelocModel = Reloc::Static;
c.CodeModel = getCodeModelFromCMModel();
c.DisableVerify = config->disableVerify;
c.DiagHandler = diagnosticHandler;
c.OptLevel = config->ltoo;
c.CPU = getCPUStr();
c.MAttrs = getMAttrs();
c.CGOptLevel = config->ltoCgo;
c.PTO.LoopVectorization = c.OptLevel > 1;
c.PTO.SLPVectorization = c.OptLevel > 1;
c.OptPipeline = std::string(config->ltoNewPmPasses);
c.AAPipeline = std::string(config->ltoAAPipeline);
c.RemarksFilename = std::string(config->optRemarksFilename);
c.RemarksPasses = std::string(config->optRemarksPasses);
c.RemarksWithHotness = config->optRemarksWithHotness;
c.RemarksHotnessThreshold = config->optRemarksHotnessThreshold;
c.RemarksFormat = std::string(config->optRemarksFormat);
c.StatsFile = std::string(config->optStatsFilename);
c.SampleProfile = std::string(config->ltoSampleProfile);
for (StringRef pluginFn : config->passPlugins)
c.PassPlugins.push_back(std::string(pluginFn));
c.DebugPassManager = config->ltoDebugPassManager;
c.DwoDir = std::string(config->dwoDir);
c.HasWholeProgramVisibility = config->ltoWholeProgramVisibility;
c.ValidateAllVtablesHaveTypeInfos =
config->ltoValidateAllVtablesHaveTypeInfos;
c.AllVtablesHaveTypeInfos = ctx.ltoAllVtablesHaveTypeInfos;
c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();
for (const llvm::StringRef &name : config->thinLTOModulesToCompile)
c.ThinLTOModulesToCompile.emplace_back(name);
c.TimeTraceEnabled = config->timeTraceEnabled;
c.TimeTraceGranularity = config->timeTraceGranularity;
c.CSIRProfile = std::string(config->ltoCSProfileFile);
c.RunCSIRInstr = config->ltoCSProfileGenerate;
c.PGOWarnMismatch = config->ltoPGOWarnMismatch;
if (config->emitLLVM) {
c.PostInternalizeModuleHook = [](size_t task, const Module &m) {
if (std::unique_ptr<raw_fd_ostream> os =
openLTOOutputFile(config->outputFile))
WriteBitcodeToFile(m, *os, false);
return false;
};
}
if (config->ltoEmitAsm) {
c.CGFileType = CGFT_AssemblyFile;
c.Options.MCOptions.AsmVerbose = true;
}
if (!config->saveTempsArgs.empty())
checkError(c.addSaveTemps(config->outputFile.str() + ".",
true,
config->saveTempsArgs));
return c;
}
BitcodeCompiler::BitcodeCompiler() {
if (!config->thinLTOIndexOnlyArg.empty())
indexFile = openFile(config->thinLTOIndexOnlyArg);
lto::ThinBackend backend;
auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); };
if (config->thinLTOIndexOnly) {
backend = lto::createWriteIndexesThinBackend(
std::string(config->thinLTOPrefixReplaceOld),
std::string(config->thinLTOPrefixReplaceNew),
std::string(config->thinLTOPrefixReplaceNativeObject),
config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);
} else {
backend = lto::createInProcessThinBackend(
llvm::heavyweight_hardware_concurrency(config->thinLTOJobs),
onIndexWrite, config->thinLTOEmitIndexFiles,
config->thinLTOEmitImportsFiles);
}
constexpr llvm::lto::LTO::LTOKind ltoModes[3] =
{llvm::lto::LTO::LTOKind::LTOK_UnifiedThin,
llvm::lto::LTO::LTOKind::LTOK_UnifiedRegular,
llvm::lto::LTO::LTOKind::LTOK_Default};
ltoObj = std::make_unique<lto::LTO>(
createConfig(), backend, config->ltoPartitions,
ltoModes[config->ltoKind]);
if (ctx.bitcodeFiles.empty())
return;
for (Symbol *sym : symtab.getSymbols()) {
if (sym->isPlaceholder())
continue;
StringRef s = sym->getName();
for (StringRef prefix : {"__start_", "__stop_"})
if (s.starts_with(prefix))
usedStartStop.insert(s.substr(prefix.size()));
}
}
BitcodeCompiler::~BitcodeCompiler() = default;
void BitcodeCompiler::add(BitcodeFile &f) {
lto::InputFile &obj = *f.obj;
bool isExec = !config->shared && !config->relocatable;
if (config->thinLTOEmitIndexFiles)
thinIndices.insert(obj.getName());
ArrayRef<Symbol *> syms = f.getSymbols();
ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();
std::vector<lto::SymbolResolution> resols(syms.size());
for (size_t i = 0, e = syms.size(); i != e; ++i) {
Symbol *sym = syms[i];
const lto::InputFile::Symbol &objSym = objSyms[i];
lto::SymbolResolution &r = resols[i];
r.Prevailing = !objSym.isUndefined() && sym->file == &f;
r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj ||
sym->referencedAfterWrap ||
(r.Prevailing && sym->includeInDynsym()) ||
usedStartStop.count(objSym.getSectionName());
r.ExportDynamic =
sym->computeBinding() != STB_LOCAL &&
(config->exportDynamic || sym->exportDynamic || sym->inDynamicList);
const auto *dr = dyn_cast<Defined>(sym);
r.FinalDefinitionInLinkageUnit =
(isExec || sym->visibility() != STV_DEFAULT) && dr &&
!(dr->section == nullptr && (!sym->file || sym->file->isElf()));
if (r.Prevailing)
Undefined(nullptr, StringRef(), STB_GLOBAL, STV_DEFAULT, sym->type)
.overwrite(*sym);
r.LinkerRedefined = sym->scriptDefined;
}
checkError(ltoObj->add(std::move(f.obj), resols));
}
static void thinLTOCreateEmptyIndexFiles() {
DenseSet<StringRef> linkedBitCodeFiles;
for (BitcodeFile *f : ctx.bitcodeFiles)
linkedBitCodeFiles.insert(f->getName());
for (BitcodeFile *f : ctx.lazyBitcodeFiles) {
if (!f->lazy)
continue;
if (linkedBitCodeFiles.contains(f->getName()))
continue;
std::string path =
replaceThinLTOSuffix(getThinLTOOutputFile(f->obj->getName()));
std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");
if (!os)
continue;
ModuleSummaryIndex m( false);
m.setSkipModuleByDistributedBackend();
writeIndexToFile(m, *os);
if (config->thinLTOEmitImportsFiles)
openFile(path + ".imports");
}
}
std::vector<InputFile *> BitcodeCompiler::compile() {
unsigned maxTasks = ltoObj->getMaxTasks();
buf.resize(maxTasks);
bufPart.resize(maxTasks);
files.resize(maxTasks);
FileCache cache;
if (!config->thinLTOCacheDir.empty())
cache = check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir,
[&](size_t task, const Twine &moduleName,
std::unique_ptr<MemoryBuffer> mb) {
files[task] = std::move(mb);
}));
if (!ctx.bitcodeFiles.empty())
checkError(ltoObj->run(
[&](size_t task, const Twine &moduleName) {
return std::make_unique<CachedFileStream>(
std::make_unique<raw_svector_ostream>(buf[task]));
},
cache, bufPart));
if (config->thinLTOModulesToCompile.empty()) {
for (StringRef s : thinIndices) {
std::string path = getThinLTOOutputFile(s);
openFile(path + ".thinlto.bc");
if (config->thinLTOEmitImportsFiles)
openFile(path + ".imports");
}
}
if (config->thinLTOEmitIndexFiles)
thinLTOCreateEmptyIndexFiles();
if (config->thinLTOIndexOnly) {
if (!config->ltoObjPath.empty())
saveBuffer(buf[0], config->ltoObjPath);
if (indexFile)
indexFile->close();
return {};
}
if (!config->thinLTOCacheDir.empty())
pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy, files);
if (!config->ltoObjPath.empty()) {
for (unsigned i = 0; i != maxTasks; ++i) {
Twine baseWithTask = (i == 0) ? Twine(config->ltoObjPath)
: (Twine(config->ltoObjPath) + Twine(i));
if (bufPart[i].empty()) {
saveBuffer(buf[i], baseWithTask);
} else {
for (unsigned j = 0; j != bufPart[i].size(); ++j)
saveBuffer(bufPart[i][j],
config->ltoObjPath + Twine(i) +
(j == 0 ? Twine("") : Twine('.') + Twine(j)));
}
}
}
bool savePrelink = config->saveTempsArgs.contains("prelink");
std::vector<InputFile *> ret;
for (unsigned i = 0; i != maxTasks; ++i) {
if (bufPart[i].size() == 0)
bufPart[i].emplace_back(std::move(buf[i]));
for (unsigned j = 0; j != bufPart[i].size(); ++j) {
StringRef objBuf = bufPart[i][j];
if (objBuf.empty())
continue;
std::string objNumStr;
if (i == 0 && j == 0) {
objNumStr = "";
} else if (j == 0) {
objNumStr = Twine(i).str();
} else {
objNumStr = (Twine(i) + "." + Twine(j)).str();
}
if (savePrelink || config->ltoEmitAsm)
saveBuffer(objBuf, config->outputFile + Twine(objNumStr) +
Twine(config->ltoEmitAsm ? "" : ".lto.o"));
if (!config->ltoEmitAsm)
ret.push_back(createObjFile(MemoryBufferRef(bufPart[i][j], "lto.tmp")));
}
}
for (std::unique_ptr<MemoryBuffer> &file : files)
if (file)
ret.push_back(createObjFile(*file));
return ret;
}