Path: blob/main/contrib/llvm-project/lld/MachO/LTO.cpp
34878 views
//===- LTO.cpp ------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "LTO.h"9#include "Config.h"10#include "Driver.h"11#include "InputFiles.h"12#include "Symbols.h"13#include "Target.h"1415#include "lld/Common/Args.h"16#include "lld/Common/CommonLinkerContext.h"17#include "lld/Common/Filesystem.h"18#include "lld/Common/Strings.h"19#include "lld/Common/TargetOptionsCommandFlags.h"20#include "llvm/Bitcode/BitcodeWriter.h"21#include "llvm/LTO/Config.h"22#include "llvm/LTO/LTO.h"23#include "llvm/Support/Caching.h"24#include "llvm/Support/FileSystem.h"25#include "llvm/Support/Path.h"26#include "llvm/Support/raw_ostream.h"27#include "llvm/Transforms/ObjCARC.h"2829using namespace lld;30using namespace lld::macho;31using namespace llvm;32using namespace llvm::MachO;33using namespace llvm::sys;3435static std::string getThinLTOOutputFile(StringRef modulePath) {36return lto::getThinLTOOutputFile(modulePath, config->thinLTOPrefixReplaceOld,37config->thinLTOPrefixReplaceNew);38}3940static lto::Config createConfig() {41lto::Config c;42c.Options = initTargetOptionsFromCodeGenFlags();43c.Options.EmitAddrsig = config->icfLevel == ICFLevel::safe;44for (StringRef C : config->mllvmOpts)45c.MllvmArgs.emplace_back(C.str());46c.CodeModel = getCodeModelFromCMModel();47c.CPU = getCPUStr();48c.MAttrs = getMAttrs();49c.DiagHandler = diagnosticHandler;50c.PreCodeGenPassesHook = [](legacy::PassManager &pm) {51pm.add(createObjCARCContractPass());52};5354c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty();5556c.TimeTraceEnabled = config->timeTraceEnabled;57c.TimeTraceGranularity = config->timeTraceGranularity;58c.DebugPassManager = config->ltoDebugPassManager;59c.CSIRProfile = std::string(config->csProfilePath);60c.RunCSIRInstr = config->csProfileGenerate;61c.PGOWarnMismatch = config->pgoWarnMismatch;62c.OptLevel = config->ltoo;63c.CGOptLevel = config->ltoCgo;64if (config->saveTemps)65checkError(c.addSaveTemps(config->outputFile.str() + ".",66/*UseInputModulePath=*/true));67return c;68}6970// If `originalPath` exists, hardlinks `path` to `originalPath`. If that fails,71// or `originalPath` is not set, saves `buffer` to `path`.72static void saveOrHardlinkBuffer(StringRef buffer, const Twine &path,73std::optional<StringRef> originalPath) {74if (originalPath) {75auto err = fs::create_hard_link(*originalPath, path);76if (!err)77return;78}79saveBuffer(buffer, path);80}8182BitcodeCompiler::BitcodeCompiler() {83// Initialize indexFile.84if (!config->thinLTOIndexOnlyArg.empty())85indexFile = openFile(config->thinLTOIndexOnlyArg);8687// Initialize ltoObj.88lto::ThinBackend backend;89auto onIndexWrite = [&](StringRef S) { thinIndices.erase(S); };90if (config->thinLTOIndexOnly) {91backend = lto::createWriteIndexesThinBackend(92std::string(config->thinLTOPrefixReplaceOld),93std::string(config->thinLTOPrefixReplaceNew),94std::string(config->thinLTOPrefixReplaceNativeObject),95config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite);96} else {97backend = lto::createInProcessThinBackend(98llvm::heavyweight_hardware_concurrency(config->thinLTOJobs),99onIndexWrite, config->thinLTOEmitIndexFiles,100config->thinLTOEmitImportsFiles);101}102103ltoObj = std::make_unique<lto::LTO>(createConfig(), backend);104}105106void BitcodeCompiler::add(BitcodeFile &f) {107lto::InputFile &obj = *f.obj;108109if (config->thinLTOEmitIndexFiles)110thinIndices.insert(obj.getName());111112ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols();113std::vector<lto::SymbolResolution> resols;114resols.reserve(objSyms.size());115116// Provide a resolution to the LTO API for each symbol.117bool exportDynamic =118config->outputType != MH_EXECUTE || config->exportDynamic;119auto symIt = f.symbols.begin();120for (const lto::InputFile::Symbol &objSym : objSyms) {121resols.emplace_back();122lto::SymbolResolution &r = resols.back();123Symbol *sym = *symIt++;124125// Ideally we shouldn't check for SF_Undefined but currently IRObjectFile126// reports two symbols for module ASM defined. Without this check, lld127// flags an undefined in IR with a definition in ASM as prevailing.128// Once IRObjectFile is fixed to report only one symbol this hack can129// be removed.130r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f;131132if (const auto *defined = dyn_cast<Defined>(sym)) {133r.ExportDynamic =134defined->isExternal() && !defined->privateExtern && exportDynamic;135r.FinalDefinitionInLinkageUnit =136!defined->isExternalWeakDef() && !defined->interposable;137} else if (const auto *common = dyn_cast<CommonSymbol>(sym)) {138r.ExportDynamic = !common->privateExtern && exportDynamic;139r.FinalDefinitionInLinkageUnit = true;140}141142r.VisibleToRegularObj =143sym->isUsedInRegularObj || (r.Prevailing && r.ExportDynamic);144145// Un-define the symbol so that we don't get duplicate symbol errors when we146// load the ObjFile emitted by LTO compilation.147if (r.Prevailing)148replaceSymbol<Undefined>(sym, sym->getName(), sym->getFile(),149RefState::Strong, /*wasBitcodeSymbol=*/true);150151// TODO: set the other resolution configs properly152}153checkError(ltoObj->add(std::move(f.obj), resols));154hasFiles = true;155}156157// If LazyObjFile has not been added to link, emit empty index files.158// This is needed because this is what GNU gold plugin does and we have a159// distributed build system that depends on that behavior.160static void thinLTOCreateEmptyIndexFiles() {161DenseSet<StringRef> linkedBitCodeFiles;162for (InputFile *file : inputFiles)163if (auto *f = dyn_cast<BitcodeFile>(file))164if (!f->lazy)165linkedBitCodeFiles.insert(f->getName());166167for (InputFile *file : inputFiles) {168if (auto *f = dyn_cast<BitcodeFile>(file)) {169if (!f->lazy)170continue;171if (linkedBitCodeFiles.contains(f->getName()))172continue;173std::string path =174replaceThinLTOSuffix(getThinLTOOutputFile(f->obj->getName()));175std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc");176if (!os)177continue;178179ModuleSummaryIndex m(/*HaveGVs=*/false);180m.setSkipModuleByDistributedBackend();181writeIndexToFile(m, *os);182if (config->thinLTOEmitImportsFiles)183openFile(path + ".imports");184}185}186}187188// Merge all the bitcode files we have seen, codegen the result189// and return the resulting ObjectFile(s).190std::vector<ObjFile *> BitcodeCompiler::compile() {191unsigned maxTasks = ltoObj->getMaxTasks();192buf.resize(maxTasks);193files.resize(maxTasks);194195// The -cache_path_lto option specifies the path to a directory in which196// to cache native object files for ThinLTO incremental builds. If a path was197// specified, configure LTO to use it as the cache directory.198FileCache cache;199if (!config->thinLTOCacheDir.empty())200cache = check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir,201[&](size_t task, const Twine &moduleName,202std::unique_ptr<MemoryBuffer> mb) {203files[task] = std::move(mb);204}));205206if (hasFiles)207checkError(ltoObj->run(208[&](size_t task, const Twine &moduleName) {209return std::make_unique<CachedFileStream>(210std::make_unique<raw_svector_ostream>(buf[task]));211},212cache));213214// Emit empty index files for non-indexed files215for (StringRef s : thinIndices) {216std::string path = getThinLTOOutputFile(s);217openFile(path + ".thinlto.bc");218if (config->thinLTOEmitImportsFiles)219openFile(path + ".imports");220}221222if (config->thinLTOEmitIndexFiles)223thinLTOCreateEmptyIndexFiles();224225// In ThinLTO mode, Clang passes a temporary directory in -object_path_lto,226// while the argument is a single file in FullLTO mode.227bool objPathIsDir = true;228if (!config->ltoObjPath.empty()) {229if (std::error_code ec = fs::create_directories(config->ltoObjPath))230fatal("cannot create LTO object path " + config->ltoObjPath + ": " +231ec.message());232233if (!fs::is_directory(config->ltoObjPath)) {234objPathIsDir = false;235unsigned objCount =236count_if(buf, [](const SmallString<0> &b) { return !b.empty(); });237if (objCount > 1)238fatal("-object_path_lto must specify a directory when using ThinLTO");239}240}241242auto outputFilePath = [objPathIsDir](int i) {243SmallString<261> filePath("/tmp/lto.tmp");244if (!config->ltoObjPath.empty()) {245filePath = config->ltoObjPath;246if (objPathIsDir)247path::append(filePath, Twine(i) + "." +248getArchitectureName(config->arch()) +249".lto.o");250}251return filePath;252};253254// ThinLTO with index only option is required to generate only the index255// files. After that, we exit from linker and ThinLTO backend runs in a256// distributed environment.257if (config->thinLTOIndexOnly) {258if (!config->ltoObjPath.empty())259saveBuffer(buf[0], outputFilePath(0));260if (indexFile)261indexFile->close();262return {};263}264265if (!config->thinLTOCacheDir.empty())266pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy, files);267268std::vector<ObjFile *> ret;269for (unsigned i = 0; i < maxTasks; ++i) {270// Get the native object contents either from the cache or from memory. Do271// not use the cached MemoryBuffer directly to ensure dsymutil does not272// race with the cache pruner.273StringRef objBuf;274std::optional<StringRef> cachePath;275if (files[i]) {276objBuf = files[i]->getBuffer();277cachePath = files[i]->getBufferIdentifier();278} else {279objBuf = buf[i];280}281if (objBuf.empty())282continue;283284// FIXME: should `saveTemps` and `ltoObjPath` use the same file name?285if (config->saveTemps)286saveBuffer(objBuf,287config->outputFile + ((i == 0) ? "" : Twine(i)) + ".lto.o");288289auto filePath = outputFilePath(i);290uint32_t modTime = 0;291if (!config->ltoObjPath.empty()) {292saveOrHardlinkBuffer(objBuf, filePath, cachePath);293modTime = getModTime(filePath);294}295ret.push_back(make<ObjFile>(296MemoryBufferRef(objBuf, saver().save(filePath.str())), modTime,297/*archiveName=*/"", /*lazy=*/false,298/*forceHidden=*/false, /*compatArch=*/true, /*builtFromBitcode=*/true));299}300301return ret;302}303304305