2016-08-11 16:58:12 +02:00
|
|
|
//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
|
|
|
|
//
|
2019-01-19 09:50:56 +01:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2016-08-11 16:58:12 +02:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file implements the "backend" phase of LTO, i.e. it performs
|
|
|
|
// optimization and code generation on a loaded module. It is generally used
|
|
|
|
// internally by the LTO class but can also be used independently, for example
|
|
|
|
// to implement a standalone ThinLTO backend.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "llvm/LTO/LTOBackend.h"
|
2020-12-09 13:06:50 +01:00
|
|
|
#include "llvm/Analysis/AliasAnalysis.h"
|
2016-09-07 19:46:16 +02:00
|
|
|
#include "llvm/Analysis/CGSCCPassManager.h"
|
2020-06-02 10:19:57 +02:00
|
|
|
#include "llvm/Analysis/ModuleSummaryAnalysis.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Analysis/TargetLibraryInfo.h"
|
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
2016-11-11 06:34:58 +01:00
|
|
|
#include "llvm/Bitcode/BitcodeReader.h"
|
|
|
|
#include "llvm/Bitcode/BitcodeWriter.h"
|
2019-10-28 22:53:31 +01:00
|
|
|
#include "llvm/IR/LLVMRemarkStreamer.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/IR/LegacyPassManager.h"
|
2016-09-07 19:46:16 +02:00
|
|
|
#include "llvm/IR/PassManager.h"
|
|
|
|
#include "llvm/IR/Verifier.h"
|
2016-08-17 08:23:09 +02:00
|
|
|
#include "llvm/LTO/LTO.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/MC/SubtargetFeature.h"
|
2017-03-29 01:35:34 +02:00
|
|
|
#include "llvm/Object/ModuleSymbolTable.h"
|
2016-09-07 19:46:16 +02:00
|
|
|
#include "llvm/Passes/PassBuilder.h"
|
2020-03-26 18:09:13 +01:00
|
|
|
#include "llvm/Passes/PassPlugin.h"
|
2019-08-15 19:47:44 +02:00
|
|
|
#include "llvm/Passes/StandardInstrumentations.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Support/Error.h"
|
|
|
|
#include "llvm/Support/FileSystem.h"
|
2018-04-13 07:03:28 +02:00
|
|
|
#include "llvm/Support/MemoryBuffer.h"
|
|
|
|
#include "llvm/Support/Path.h"
|
|
|
|
#include "llvm/Support/Program.h"
|
[LTO] Support for embedding bitcode section during LTO
Summary:
This adds support for embedding bitcode in a binary during LTO. The libLTO gains supports the `-lto-embed-bitcode` flag. The option allows users of the LTO library to embed a bitcode section. For example, LLD can pass the option via `ld.lld -mllvm=-lto-embed-bitcode`.
This feature allows doing something comparable to `clang -c -fembed-bitcode`, but on the (LTO) linker level. Having bitcode alongside native code has many use-cases. To give an example, the MacOS linker can create a `-bitcode_bundle` section containing bitcode. Also, having this feature built into LLVM is an alternative to 3rd party tools such as [[ https://github.com/travitch/whole-program-llvm | wllvm ]] or [[ https://github.com/SRI-CSL/gllvm | gllvm ]]. As with these tools, this feature simplifies creating "whole-program" llvm bitcode files, but in contrast to wllvm/gllvm it does not rely on a specific llvm frontend/driver.
Patch by Josef Eisl <josef.eisl@oracle.com>
Reviewers: #llvm, #clang, rsmith, pcc, alexshap, tejohnson
Reviewed By: tejohnson
Subscribers: tejohnson, mehdi_amini, inglorion, hiraditya, aheejin, steven_wu, dexonsmith, dang, cfe-commits, llvm-commits, #llvm, #clang
Tags: #clang, #llvm
Differential Revision: https://reviews.llvm.org/D68213
2019-12-12 20:59:36 +01:00
|
|
|
#include "llvm/Support/SmallVectorMemoryBuffer.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Support/TargetRegistry.h"
|
|
|
|
#include "llvm/Support/ThreadPool.h"
|
2019-06-14 18:20:51 +02:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Target/TargetMachine.h"
|
|
|
|
#include "llvm/Transforms/IPO.h"
|
|
|
|
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
|
2017-01-11 10:43:56 +01:00
|
|
|
#include "llvm/Transforms/Scalar/LoopPassManager.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
|
|
|
|
#include "llvm/Transforms/Utils/SplitModule.h"
|
|
|
|
|
|
|
|
using namespace llvm;
|
|
|
|
using namespace lto;
|
|
|
|
|
2020-09-14 19:45:00 +02:00
|
|
|
#define DEBUG_TYPE "lto-backend"
|
|
|
|
|
[ThinLTO] Make -lto-embed-bitcode an enum
The current behavior of -lto-embed-bitcode is not quite the same as that
of -fembed-bitcode. While both populate .llvmbc with bitcode, the latter
populates it with pre-optimized bitcode(*), while the former with
post-optimized. The scenarios driving them are different - the latter's
goal is to allow re-compilation, while the former, IIUC, is execution.
I plan to add a third mode for thinlto cases, closely-related to
-fembed-bitcode's scenario: adding the bitcode pre-optimization, but
post-merging. This would allow re-compilation without requiring the
other .bc files that were merged (akin to how -fembed-bitcode allows
recompilation without all the .h files)
The third mode can't co-exist with the current -lto-embed-bitcode mode,
because the latter would overwrite it. For clarity, we change
-lto-embed-bitcode to be an enum.
(*) That's the compiler semantics. The driver splits compilation in 2
phases, so if -fembed-bitcode is given to the driver, the .llvmbc is
optimized bitcode; if the option is passed to the compiler (after -cc1),
the section is pre-optimized.
Differential Revision: https://reviews.llvm.org/D87477
2020-09-10 21:16:26 +02:00
|
|
|
enum class LTOBitcodeEmbedding {
|
|
|
|
DoNotEmbed = 0,
|
|
|
|
EmbedOptimized = 1,
|
2020-09-14 19:45:00 +02:00
|
|
|
EmbedPostMergePreOptimized = 2
|
[ThinLTO] Make -lto-embed-bitcode an enum
The current behavior of -lto-embed-bitcode is not quite the same as that
of -fembed-bitcode. While both populate .llvmbc with bitcode, the latter
populates it with pre-optimized bitcode(*), while the former with
post-optimized. The scenarios driving them are different - the latter's
goal is to allow re-compilation, while the former, IIUC, is execution.
I plan to add a third mode for thinlto cases, closely-related to
-fembed-bitcode's scenario: adding the bitcode pre-optimization, but
post-merging. This would allow re-compilation without requiring the
other .bc files that were merged (akin to how -fembed-bitcode allows
recompilation without all the .h files)
The third mode can't co-exist with the current -lto-embed-bitcode mode,
because the latter would overwrite it. For clarity, we change
-lto-embed-bitcode to be an enum.
(*) That's the compiler semantics. The driver splits compilation in 2
phases, so if -fembed-bitcode is given to the driver, the .llvmbc is
optimized bitcode; if the option is passed to the compiler (after -cc1),
the section is pre-optimized.
Differential Revision: https://reviews.llvm.org/D87477
2020-09-10 21:16:26 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
static cl::opt<LTOBitcodeEmbedding> EmbedBitcode(
|
|
|
|
"lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
|
|
|
|
cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none",
|
|
|
|
"Do not embed"),
|
|
|
|
clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized",
|
2020-09-14 19:45:00 +02:00
|
|
|
"Embed after all optimization passes"),
|
|
|
|
clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized,
|
|
|
|
"post-merge-pre-opt",
|
|
|
|
"Embed post merge, but before optimizations")),
|
[ThinLTO] Make -lto-embed-bitcode an enum
The current behavior of -lto-embed-bitcode is not quite the same as that
of -fembed-bitcode. While both populate .llvmbc with bitcode, the latter
populates it with pre-optimized bitcode(*), while the former with
post-optimized. The scenarios driving them are different - the latter's
goal is to allow re-compilation, while the former, IIUC, is execution.
I plan to add a third mode for thinlto cases, closely-related to
-fembed-bitcode's scenario: adding the bitcode pre-optimization, but
post-merging. This would allow re-compilation without requiring the
other .bc files that were merged (akin to how -fembed-bitcode allows
recompilation without all the .h files)
The third mode can't co-exist with the current -lto-embed-bitcode mode,
because the latter would overwrite it. For clarity, we change
-lto-embed-bitcode to be an enum.
(*) That's the compiler semantics. The driver splits compilation in 2
phases, so if -fembed-bitcode is given to the driver, the .llvmbc is
optimized bitcode; if the option is passed to the compiler (after -cc1),
the section is pre-optimized.
Differential Revision: https://reviews.llvm.org/D87477
2020-09-10 21:16:26 +02:00
|
|
|
cl::desc("Embed LLVM bitcode in object files produced by LTO"));
|
|
|
|
|
2020-09-16 21:08:15 +02:00
|
|
|
static cl::opt<bool> ThinLTOAssumeMerged(
|
|
|
|
"thinlto-assume-merged", cl::init(false),
|
|
|
|
cl::desc("Assume the input has already undergone ThinLTO function "
|
|
|
|
"importing and the other pre-optimization pipeline changes."));
|
|
|
|
|
2016-10-18 21:39:31 +02:00
|
|
|
LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
|
2016-09-18 00:32:42 +02:00
|
|
|
errs() << "failed to open " << Path << ": " << Msg << '\n';
|
|
|
|
errs().flush();
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
Error Config::addSaveTemps(std::string OutputFileName,
|
|
|
|
bool UseInputModulePath) {
|
|
|
|
ShouldDiscardValueNames = false;
|
|
|
|
|
|
|
|
std::error_code EC;
|
2019-08-15 17:54:37 +02:00
|
|
|
ResolutionFile = std::make_unique<raw_fd_ostream>(
|
2019-08-05 07:43:48 +02:00
|
|
|
OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
|
2020-03-01 21:06:51 +01:00
|
|
|
if (EC) {
|
|
|
|
ResolutionFile.reset();
|
2016-08-11 16:58:12 +02:00
|
|
|
return errorCodeToError(EC);
|
2020-03-01 21:06:51 +01:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
|
|
|
|
// Keep track of the hook provided by the linker, which also needs to run.
|
|
|
|
ModuleHookFn LinkerHook = Hook;
|
2016-08-22 18:17:40 +02:00
|
|
|
Hook = [=](unsigned Task, const Module &M) {
|
2016-08-11 16:58:12 +02:00
|
|
|
// If the linker's hook returned false, we need to pass that result
|
|
|
|
// through.
|
|
|
|
if (LinkerHook && !LinkerHook(Task, M))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
std::string PathPrefix;
|
|
|
|
// If this is the combined module (not a ThinLTO backend compile) or the
|
|
|
|
// user hasn't requested using the input module's path, emit to a file
|
|
|
|
// named from the provided OutputFileName with the Task ID appended.
|
|
|
|
if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
|
2018-05-05 16:37:20 +02:00
|
|
|
PathPrefix = OutputFileName;
|
|
|
|
if (Task != (unsigned)-1)
|
|
|
|
PathPrefix += utostr(Task) + ".";
|
2016-08-11 16:58:12 +02:00
|
|
|
} else
|
2018-05-05 16:37:20 +02:00
|
|
|
PathPrefix = M.getModuleIdentifier() + ".";
|
|
|
|
std::string Path = PathPrefix + PathSuffix + ".bc";
|
2016-08-11 16:58:12 +02:00
|
|
|
std::error_code EC;
|
2019-08-05 07:43:48 +02:00
|
|
|
raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
|
2016-09-18 00:32:42 +02:00
|
|
|
// Because -save-temps is a debugging feature, we report the error
|
|
|
|
// directly and exit.
|
|
|
|
if (EC)
|
|
|
|
reportOpenError(Path, EC.message());
|
2018-02-14 20:11:32 +01:00
|
|
|
WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
|
2016-08-11 16:58:12 +02:00
|
|
|
return true;
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
setHook("0.preopt", PreOptModuleHook);
|
|
|
|
setHook("1.promote", PostPromoteModuleHook);
|
|
|
|
setHook("2.internalize", PostInternalizeModuleHook);
|
|
|
|
setHook("3.import", PostImportModuleHook);
|
|
|
|
setHook("4.opt", PostOptModuleHook);
|
|
|
|
setHook("5.precodegen", PreCodeGenModuleHook);
|
|
|
|
|
2019-12-18 16:33:15 +01:00
|
|
|
CombinedIndexHook =
|
|
|
|
[=](const ModuleSummaryIndex &Index,
|
|
|
|
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
|
|
|
|
std::string Path = OutputFileName + "index.bc";
|
|
|
|
std::error_code EC;
|
|
|
|
raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
|
|
|
|
// Because -save-temps is a debugging feature, we report the error
|
|
|
|
// directly and exit.
|
|
|
|
if (EC)
|
|
|
|
reportOpenError(Path, EC.message());
|
|
|
|
WriteIndexToFile(Index, OS);
|
|
|
|
|
|
|
|
Path = OutputFileName + "index.dot";
|
|
|
|
raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
|
|
|
|
if (EC)
|
|
|
|
reportOpenError(Path, EC.message());
|
|
|
|
Index.exportToDot(OSDot, GUIDPreservedSymbols);
|
|
|
|
return true;
|
|
|
|
};
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2020-03-26 18:09:13 +01:00
|
|
|
#define HANDLE_EXTENSION(Ext) \
|
|
|
|
llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
|
|
|
|
#include "llvm/Support/Extension.def"
|
|
|
|
|
|
|
|
static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins,
|
|
|
|
PassBuilder &PB) {
|
|
|
|
#define HANDLE_EXTENSION(Ext) \
|
|
|
|
get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
|
|
|
|
#include "llvm/Support/Extension.def"
|
|
|
|
|
|
|
|
// Load requested pass plugins and let them register pass builder callbacks
|
|
|
|
for (auto &PluginFN : PassPlugins) {
|
|
|
|
auto PassPlugin = PassPlugin::Load(PluginFN);
|
|
|
|
if (!PassPlugin) {
|
|
|
|
errs() << "Failed to load passes from '" << PluginFN
|
|
|
|
<< "'. Request ignored.\n";
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
PassPlugin->registerPassBuilderCallbacks(PB);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-13 10:02:23 +01:00
|
|
|
static std::unique_ptr<TargetMachine>
|
2020-01-13 21:23:34 +01:00
|
|
|
createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
|
2017-05-22 23:11:35 +02:00
|
|
|
StringRef TheTriple = M.getTargetTriple();
|
2016-08-11 16:58:12 +02:00
|
|
|
SubtargetFeatures Features;
|
|
|
|
Features.getDefaultSubtargetFeatures(Triple(TheTriple));
|
2016-09-07 03:08:31 +02:00
|
|
|
for (const std::string &A : Conf.MAttrs)
|
2016-08-11 16:58:12 +02:00
|
|
|
Features.AddFeature(A);
|
|
|
|
|
2021-03-10 23:20:09 +01:00
|
|
|
Optional<Reloc::Model> RelocModel = None;
|
2017-05-22 23:11:35 +02:00
|
|
|
if (Conf.RelocModel)
|
|
|
|
RelocModel = *Conf.RelocModel;
|
2021-03-10 23:20:09 +01:00
|
|
|
else if (M.getModuleFlag("PIC Level"))
|
2017-05-22 23:11:35 +02:00
|
|
|
RelocModel =
|
|
|
|
M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
|
|
|
|
|
2018-09-21 20:41:31 +02:00
|
|
|
Optional<CodeModel::Model> CodeModel;
|
|
|
|
if (Conf.CodeModel)
|
|
|
|
CodeModel = *Conf.CodeModel;
|
|
|
|
else
|
|
|
|
CodeModel = M.getCodeModel();
|
|
|
|
|
2020-11-22 06:04:12 +01:00
|
|
|
std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
|
2017-05-22 23:11:35 +02:00
|
|
|
TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
|
2018-09-21 20:41:31 +02:00
|
|
|
CodeModel, Conf.CGOptLevel));
|
2020-11-22 06:04:12 +01:00
|
|
|
assert(TM && "Failed to create target machine");
|
|
|
|
return TM;
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2020-01-13 21:23:34 +01:00
|
|
|
static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
|
2018-07-19 16:51:32 +02:00
|
|
|
unsigned OptLevel, bool IsThinLTO,
|
|
|
|
ModuleSummaryIndex *ExportSummary,
|
|
|
|
const ModuleSummaryIndex *ImportSummary) {
|
2017-08-02 03:28:31 +02:00
|
|
|
Optional<PGOOptions> PGOOpt;
|
|
|
|
if (!Conf.SampleProfile.empty())
|
2019-03-04 21:21:27 +01:00
|
|
|
PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
|
|
|
|
PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
|
|
|
|
else if (Conf.RunCSIRInstr) {
|
|
|
|
PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
|
|
|
|
PGOOptions::IRUse, PGOOptions::CSIRInstr);
|
|
|
|
} else if (!Conf.CSIRProfile.empty()) {
|
|
|
|
PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
|
|
|
|
PGOOptions::IRUse, PGOOptions::CSIRUse);
|
|
|
|
}
|
2017-08-02 03:28:31 +02:00
|
|
|
|
2019-08-15 19:47:44 +02:00
|
|
|
PassInstrumentationCallbacks PIC;
|
2020-07-21 18:48:22 +02:00
|
|
|
StandardInstrumentations SI(Conf.DebugPassManager);
|
2019-08-15 19:47:44 +02:00
|
|
|
SI.registerCallbacks(PIC);
|
2020-10-29 23:43:31 +01:00
|
|
|
PassBuilder PB(Conf.DebugPassManager, TM, Conf.PTO, PGOOpt, &PIC);
|
2017-01-24 01:58:24 +01:00
|
|
|
|
2020-03-26 18:09:13 +01:00
|
|
|
RegisterPassPlugins(Conf.PassPlugins, PB);
|
|
|
|
|
2017-08-02 05:03:19 +02:00
|
|
|
LoopAnalysisManager LAM(Conf.DebugPassManager);
|
|
|
|
FunctionAnalysisManager FAM(Conf.DebugPassManager);
|
|
|
|
CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
|
|
|
|
ModuleAnalysisManager MAM(Conf.DebugPassManager);
|
2017-01-24 01:58:24 +01:00
|
|
|
|
2021-01-22 14:13:54 +01:00
|
|
|
std::unique_ptr<TargetLibraryInfoImpl> TLII(
|
|
|
|
new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
|
|
|
|
if (Conf.Freestanding)
|
|
|
|
TLII->disableAllFunctions();
|
|
|
|
FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
|
|
|
|
|
2021-02-11 23:37:29 +01:00
|
|
|
AAManager AA;
|
|
|
|
// Parse a custom AA pipeline if asked to.
|
|
|
|
if (!Conf.AAPipeline.empty()) {
|
|
|
|
if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
|
|
|
|
report_fatal_error("unable to parse AA pipeline description '" +
|
|
|
|
Conf.AAPipeline + "': " + toString(std::move(Err)));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
AA = PB.buildDefaultAAPipeline();
|
|
|
|
}
|
2017-01-24 01:58:24 +01:00
|
|
|
// Register the AA manager first so that our version is the one used.
|
|
|
|
FAM.registerPass([&] { return std::move(AA); });
|
|
|
|
|
|
|
|
// Register all the basic analyses with the managers.
|
|
|
|
PB.registerModuleAnalyses(MAM);
|
|
|
|
PB.registerCGSCCAnalyses(CGAM);
|
|
|
|
PB.registerFunctionAnalyses(FAM);
|
|
|
|
PB.registerLoopAnalyses(LAM);
|
|
|
|
PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
|
|
|
|
|
2017-08-02 05:03:19 +02:00
|
|
|
ModulePassManager MPM(Conf.DebugPassManager);
|
2020-12-01 19:14:38 +01:00
|
|
|
|
|
|
|
if (!Conf.DisableVerify)
|
|
|
|
MPM.addPass(VerifierPass());
|
2017-01-24 01:58:24 +01:00
|
|
|
|
|
|
|
PassBuilder::OptimizationLevel OL;
|
|
|
|
|
|
|
|
switch (OptLevel) {
|
|
|
|
default:
|
|
|
|
llvm_unreachable("Invalid optimization level");
|
|
|
|
case 0:
|
[llvm] Make new pass manager's OptimizationLevel a class
Summary:
The old pass manager separated speed optimization and size optimization
levels into two unsigned values. Coallescing both in an enum in the new
pass manager may lead to unintentional casts and comparisons.
In particular, taking a look at how the loop unroll passes were constructed
previously, the Os/Oz are now (==new pass manager) treated just like O3,
likely unintentionally.
This change disallows raw comparisons between optimization levels, to
avoid such unintended effects. As an effect, the O{s|z} behavior changes
for loop unrolling and loop unroll and jam, matching O2 rather than O3.
The change also parameterizes the threshold values used for loop
unrolling, primarily to aid testing.
Reviewers: tejohnson, davidxl
Reviewed By: tejohnson
Subscribers: zzheng, ychen, mehdi_amini, hiraditya, steven_wu, dexonsmith, dang, cfe-commits, llvm-commits
Tags: #clang, #llvm
Differential Revision: https://reviews.llvm.org/D72547
2020-01-16 17:51:50 +01:00
|
|
|
OL = PassBuilder::OptimizationLevel::O0;
|
2017-01-24 01:58:24 +01:00
|
|
|
break;
|
|
|
|
case 1:
|
[llvm] Make new pass manager's OptimizationLevel a class
Summary:
The old pass manager separated speed optimization and size optimization
levels into two unsigned values. Coallescing both in an enum in the new
pass manager may lead to unintentional casts and comparisons.
In particular, taking a look at how the loop unroll passes were constructed
previously, the Os/Oz are now (==new pass manager) treated just like O3,
likely unintentionally.
This change disallows raw comparisons between optimization levels, to
avoid such unintended effects. As an effect, the O{s|z} behavior changes
for loop unrolling and loop unroll and jam, matching O2 rather than O3.
The change also parameterizes the threshold values used for loop
unrolling, primarily to aid testing.
Reviewers: tejohnson, davidxl
Reviewed By: tejohnson
Subscribers: zzheng, ychen, mehdi_amini, hiraditya, steven_wu, dexonsmith, dang, cfe-commits, llvm-commits
Tags: #clang, #llvm
Differential Revision: https://reviews.llvm.org/D72547
2020-01-16 17:51:50 +01:00
|
|
|
OL = PassBuilder::OptimizationLevel::O1;
|
2017-01-24 01:58:24 +01:00
|
|
|
break;
|
|
|
|
case 2:
|
[llvm] Make new pass manager's OptimizationLevel a class
Summary:
The old pass manager separated speed optimization and size optimization
levels into two unsigned values. Coallescing both in an enum in the new
pass manager may lead to unintentional casts and comparisons.
In particular, taking a look at how the loop unroll passes were constructed
previously, the Os/Oz are now (==new pass manager) treated just like O3,
likely unintentionally.
This change disallows raw comparisons between optimization levels, to
avoid such unintended effects. As an effect, the O{s|z} behavior changes
for loop unrolling and loop unroll and jam, matching O2 rather than O3.
The change also parameterizes the threshold values used for loop
unrolling, primarily to aid testing.
Reviewers: tejohnson, davidxl
Reviewed By: tejohnson
Subscribers: zzheng, ychen, mehdi_amini, hiraditya, steven_wu, dexonsmith, dang, cfe-commits, llvm-commits
Tags: #clang, #llvm
Differential Revision: https://reviews.llvm.org/D72547
2020-01-16 17:51:50 +01:00
|
|
|
OL = PassBuilder::OptimizationLevel::O2;
|
2017-01-24 01:58:24 +01:00
|
|
|
break;
|
|
|
|
case 3:
|
[llvm] Make new pass manager's OptimizationLevel a class
Summary:
The old pass manager separated speed optimization and size optimization
levels into two unsigned values. Coallescing both in an enum in the new
pass manager may lead to unintentional casts and comparisons.
In particular, taking a look at how the loop unroll passes were constructed
previously, the Os/Oz are now (==new pass manager) treated just like O3,
likely unintentionally.
This change disallows raw comparisons between optimization levels, to
avoid such unintended effects. As an effect, the O{s|z} behavior changes
for loop unrolling and loop unroll and jam, matching O2 rather than O3.
The change also parameterizes the threshold values used for loop
unrolling, primarily to aid testing.
Reviewers: tejohnson, davidxl
Reviewed By: tejohnson
Subscribers: zzheng, ychen, mehdi_amini, hiraditya, steven_wu, dexonsmith, dang, cfe-commits, llvm-commits
Tags: #clang, #llvm
Differential Revision: https://reviews.llvm.org/D72547
2020-01-16 17:51:50 +01:00
|
|
|
OL = PassBuilder::OptimizationLevel::O3;
|
2017-01-24 01:58:24 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2021-02-11 23:37:29 +01:00
|
|
|
// Parse a custom pipeline if asked to.
|
|
|
|
if (!Conf.OptPipeline.empty()) {
|
|
|
|
if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
|
|
|
|
report_fatal_error("unable to parse pass pipeline description '" +
|
|
|
|
Conf.OptPipeline + "': " + toString(std::move(Err)));
|
|
|
|
}
|
|
|
|
} else if (IsThinLTO) {
|
2020-12-01 19:14:38 +01:00
|
|
|
MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
|
2021-02-11 23:37:29 +01:00
|
|
|
} else {
|
2020-12-01 19:14:38 +01:00
|
|
|
MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
|
2021-02-11 23:37:29 +01:00
|
|
|
}
|
2017-01-24 01:58:24 +01:00
|
|
|
|
2020-12-01 19:14:38 +01:00
|
|
|
if (!Conf.DisableVerify)
|
|
|
|
MPM.addPass(VerifierPass());
|
|
|
|
|
|
|
|
MPM.run(Mod, MAM);
|
2017-01-24 01:58:24 +01:00
|
|
|
}
|
|
|
|
|
2020-01-13 21:23:34 +01:00
|
|
|
static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
|
2017-03-22 19:22:59 +01:00
|
|
|
bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
|
|
|
|
const ModuleSummaryIndex *ImportSummary) {
|
2016-08-11 16:58:12 +02:00
|
|
|
legacy::PassManager passes;
|
|
|
|
passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
|
|
|
|
|
|
|
|
PassManagerBuilder PMB;
|
|
|
|
PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
|
2021-01-22 14:13:54 +01:00
|
|
|
if (Conf.Freestanding)
|
|
|
|
PMB.LibraryInfo->disableAllFunctions();
|
2016-08-11 16:58:12 +02:00
|
|
|
PMB.Inliner = createFunctionInliningPass();
|
2017-03-22 19:22:59 +01:00
|
|
|
PMB.ExportSummary = ExportSummary;
|
|
|
|
PMB.ImportSummary = ImportSummary;
|
2016-08-11 16:58:12 +02:00
|
|
|
// Unconditionally verify input since it is not verified before this
|
|
|
|
// point and has unknown origin.
|
|
|
|
PMB.VerifyInput = true;
|
2016-09-07 03:08:31 +02:00
|
|
|
PMB.VerifyOutput = !Conf.DisableVerify;
|
2016-08-11 16:58:12 +02:00
|
|
|
PMB.LoopVectorize = true;
|
|
|
|
PMB.SLPVectorize = true;
|
2016-09-07 03:08:31 +02:00
|
|
|
PMB.OptLevel = Conf.OptLevel;
|
2016-12-16 17:48:46 +01:00
|
|
|
PMB.PGOSampleUse = Conf.SampleProfile;
|
2019-03-04 21:21:27 +01:00
|
|
|
PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
|
|
|
|
if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
|
|
|
|
PMB.EnablePGOCSInstrUse = true;
|
|
|
|
PMB.PGOInstrUse = Conf.CSIRProfile;
|
|
|
|
}
|
2016-11-24 01:23:09 +01:00
|
|
|
if (IsThinLTO)
|
2016-08-11 16:58:12 +02:00
|
|
|
PMB.populateThinLTOPassManager(passes);
|
|
|
|
else
|
|
|
|
PMB.populateLTOPassManager(passes);
|
2016-09-07 03:08:31 +02:00
|
|
|
passes.run(Mod);
|
2016-08-31 19:02:44 +02:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2021-01-14 10:53:41 +01:00
|
|
|
bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
|
|
|
|
bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
|
|
|
|
const ModuleSummaryIndex *ImportSummary,
|
|
|
|
const std::vector<uint8_t> &CmdArgs) {
|
2020-09-14 19:45:00 +02:00
|
|
|
if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
|
|
|
|
// FIXME: the motivation for capturing post-merge bitcode and command line
|
|
|
|
// is replicating the compilation environment from bitcode, without needing
|
|
|
|
// to understand the dependencies (the functions to be imported). This
|
|
|
|
// assumes a clang - based invocation, case in which we have the command
|
|
|
|
// line.
|
|
|
|
// It's not very clear how the above motivation would map in the
|
|
|
|
// linker-based case, so we currently don't plumb the command line args in
|
|
|
|
// that case.
|
2020-10-28 20:08:26 +01:00
|
|
|
if (CmdArgs.empty())
|
2020-09-14 19:45:00 +02:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
|
|
|
|
"command line arguments are not available");
|
|
|
|
llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
|
2020-10-28 01:22:30 +01:00
|
|
|
/*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
|
2020-10-28 20:08:26 +01:00
|
|
|
/*Cmdline*/ CmdArgs);
|
2020-09-14 19:45:00 +02:00
|
|
|
}
|
2017-01-24 01:58:24 +01:00
|
|
|
// FIXME: Plumb the combined index into the new pass manager.
|
2021-02-15 20:49:09 +01:00
|
|
|
if (Conf.UseNewPM || !Conf.OptPipeline.empty()) {
|
2018-07-19 16:51:32 +02:00
|
|
|
runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
|
|
|
|
ImportSummary);
|
2021-02-11 23:37:29 +01:00
|
|
|
} else {
|
2017-03-22 19:22:59 +01:00
|
|
|
runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
|
2021-02-11 23:37:29 +01:00
|
|
|
}
|
2016-09-07 03:08:31 +02:00
|
|
|
return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2021-01-13 10:02:23 +01:00
|
|
|
static void codegen(const Config &Conf, TargetMachine *TM,
|
|
|
|
AddStreamFn AddStream, unsigned Task, Module &Mod,
|
|
|
|
const ModuleSummaryIndex &CombinedIndex) {
|
2016-09-07 03:08:31 +02:00
|
|
|
if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
|
2016-08-11 16:58:12 +02:00
|
|
|
return;
|
|
|
|
|
[ThinLTO] Make -lto-embed-bitcode an enum
The current behavior of -lto-embed-bitcode is not quite the same as that
of -fembed-bitcode. While both populate .llvmbc with bitcode, the latter
populates it with pre-optimized bitcode(*), while the former with
post-optimized. The scenarios driving them are different - the latter's
goal is to allow re-compilation, while the former, IIUC, is execution.
I plan to add a third mode for thinlto cases, closely-related to
-fembed-bitcode's scenario: adding the bitcode pre-optimization, but
post-merging. This would allow re-compilation without requiring the
other .bc files that were merged (akin to how -fembed-bitcode allows
recompilation without all the .h files)
The third mode can't co-exist with the current -lto-embed-bitcode mode,
because the latter would overwrite it. For clarity, we change
-lto-embed-bitcode to be an enum.
(*) That's the compiler semantics. The driver splits compilation in 2
phases, so if -fembed-bitcode is given to the driver, the .llvmbc is
optimized bitcode; if the option is passed to the compiler (after -cc1),
the section is pre-optimized.
Differential Revision: https://reviews.llvm.org/D87477
2020-09-10 21:16:26 +02:00
|
|
|
if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
|
|
|
|
llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
|
|
|
|
/*EmbedBitcode*/ true,
|
2020-10-28 01:22:30 +01:00
|
|
|
/*EmbedCmdline*/ false,
|
2020-10-28 20:08:26 +01:00
|
|
|
/*CmdArgs*/ std::vector<uint8_t>());
|
[LTO] Support for embedding bitcode section during LTO
Summary:
This adds support for embedding bitcode in a binary during LTO. The libLTO gains supports the `-lto-embed-bitcode` flag. The option allows users of the LTO library to embed a bitcode section. For example, LLD can pass the option via `ld.lld -mllvm=-lto-embed-bitcode`.
This feature allows doing something comparable to `clang -c -fembed-bitcode`, but on the (LTO) linker level. Having bitcode alongside native code has many use-cases. To give an example, the MacOS linker can create a `-bitcode_bundle` section containing bitcode. Also, having this feature built into LLVM is an alternative to 3rd party tools such as [[ https://github.com/travitch/whole-program-llvm | wllvm ]] or [[ https://github.com/SRI-CSL/gllvm | gllvm ]]. As with these tools, this feature simplifies creating "whole-program" llvm bitcode files, but in contrast to wllvm/gllvm it does not rely on a specific llvm frontend/driver.
Patch by Josef Eisl <josef.eisl@oracle.com>
Reviewers: #llvm, #clang, rsmith, pcc, alexshap, tejohnson
Reviewed By: tejohnson
Subscribers: tejohnson, mehdi_amini, inglorion, hiraditya, aheejin, steven_wu, dexonsmith, dang, cfe-commits, llvm-commits, #llvm, #clang
Tags: #clang, #llvm
Differential Revision: https://reviews.llvm.org/D68213
2019-12-12 20:59:36 +01:00
|
|
|
|
2018-05-21 22:26:49 +02:00
|
|
|
std::unique_ptr<ToolOutputFile> DwoOut;
|
2019-06-15 17:38:51 +02:00
|
|
|
SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
|
2018-04-13 07:03:28 +02:00
|
|
|
if (!Conf.DwoDir.empty()) {
|
2018-05-21 22:26:49 +02:00
|
|
|
std::error_code EC;
|
|
|
|
if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
|
|
|
|
report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
|
|
|
|
EC.message());
|
|
|
|
|
2018-05-31 20:25:59 +02:00
|
|
|
DwoFile = Conf.DwoDir;
|
2018-05-21 22:26:49 +02:00
|
|
|
sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
|
2020-01-30 06:14:15 +01:00
|
|
|
TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
|
2019-06-15 17:38:51 +02:00
|
|
|
} else
|
|
|
|
TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
|
2018-05-31 20:25:59 +02:00
|
|
|
|
|
|
|
if (!DwoFile.empty()) {
|
|
|
|
std::error_code EC;
|
2019-08-15 17:54:37 +02:00
|
|
|
DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
|
2018-05-21 22:26:49 +02:00
|
|
|
if (EC)
|
|
|
|
report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
|
2018-04-13 07:03:28 +02:00
|
|
|
}
|
|
|
|
|
2016-09-23 23:33:43 +02:00
|
|
|
auto Stream = AddStream(Task);
|
2016-08-11 16:58:12 +02:00
|
|
|
legacy::PassManager CodeGenPasses;
|
2020-06-02 10:19:57 +02:00
|
|
|
CodeGenPasses.add(
|
|
|
|
createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
|
2021-01-12 20:41:56 +01:00
|
|
|
if (Conf.PreCodeGenPassesHook)
|
|
|
|
Conf.PreCodeGenPassesHook(CodeGenPasses);
|
2018-05-21 22:26:49 +02:00
|
|
|
if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
|
|
|
|
DwoOut ? &DwoOut->os() : nullptr,
|
2018-05-21 22:16:41 +02:00
|
|
|
Conf.CGFileType))
|
2016-08-11 16:58:12 +02:00
|
|
|
report_fatal_error("Failed to setup codegen");
|
2016-09-07 03:08:31 +02:00
|
|
|
CodeGenPasses.run(Mod);
|
2018-05-21 22:26:49 +02:00
|
|
|
|
|
|
|
if (DwoOut)
|
|
|
|
DwoOut->keep();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2021-01-13 10:02:23 +01:00
|
|
|
static void splitCodeGen(const Config &C, TargetMachine *TM,
|
|
|
|
AddStreamFn AddStream,
|
2021-01-29 11:20:54 +01:00
|
|
|
unsigned ParallelCodeGenParallelismLevel, Module &Mod,
|
2021-01-13 10:02:23 +01:00
|
|
|
const ModuleSummaryIndex &CombinedIndex) {
|
[Support] On Windows, ensure hardware_concurrency() extends to all CPU sockets and all NUMA groups
The goal of this patch is to maximize CPU utilization on multi-socket or high core count systems, so that parallel computations such as LLD/ThinLTO can use all hardware threads in the system. Before this patch, on Windows, a maximum of 64 hardware threads could be used at most, in some cases dispatched only on one CPU socket.
== Background ==
Windows doesn't have a flat cpu_set_t like Linux. Instead, it projects hardware CPUs (or NUMA nodes) to applications through a concept of "processor groups". A "processor" is the smallest unit of execution on a CPU, that is, an hyper-thread if SMT is active; a core otherwise. There's a limit of 32-bit processors on older 32-bit versions of Windows, which later was raised to 64-processors with 64-bit versions of Windows. This limit comes from the affinity mask, which historically is represented by the sizeof(void*). Consequently, the concept of "processor groups" was introduced for dealing with systems with more than 64 hyper-threads.
By default, the Windows OS assigns only one "processor group" to each starting application, in a round-robin manner. If the application wants to use more processors, it needs to programmatically enable it, by assigning threads to other "processor groups". This also means that affinity cannot cross "processor group" boundaries; one can only specify a "preferred" group on start-up, but the application is free to allocate more groups if it wants to.
This creates a peculiar situation, where newer CPUs like the AMD EPYC 7702P (64-cores, 128-hyperthreads) are projected by the OS as two (2) "processor groups". This means that by default, an application can only use half of the cores. This situation could only get worse in the years to come, as dies with more cores will appear on the market.
== The problem ==
The heavyweight_hardware_concurrency() API was introduced so that only *one hardware thread per core* was used. Once that API returns, that original intention is lost, only the number of threads is retained. Consider a situation, on Windows, where the system has 2 CPU sockets, 18 cores each, each core having 2 hyper-threads, for a total of 72 hyper-threads. Both heavyweight_hardware_concurrency() and hardware_concurrency() currently return 36, because on Windows they are simply wrappers over std::thread::hardware_concurrency() -- which can only return processors from the current "processor group".
== The changes in this patch ==
To solve this situation, we capture (and retain) the initial intention until the point of usage, through a new ThreadPoolStrategy class. The number of threads to use is deferred as late as possible, until the moment where the std::threads are created (ThreadPool in the case of ThinLTO).
When using hardware_concurrency(), setting ThreadCount to 0 now means to use all the possible hardware CPU (SMT) threads. Providing a ThreadCount above to the maximum number of threads will have no effect, the maximum will be used instead.
The heavyweight_hardware_concurrency() is similar to hardware_concurrency(), except that only one thread per hardware *core* will be used.
When LLVM_ENABLE_THREADS is OFF, the threading APIs will always return 1, to ensure any caller loops will be exercised at least once.
Differential Revision: https://reviews.llvm.org/D71775
2020-02-14 04:49:57 +01:00
|
|
|
ThreadPool CodegenThreadPool(
|
|
|
|
heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
|
2016-08-11 16:58:12 +02:00
|
|
|
unsigned ThreadCount = 0;
|
|
|
|
const Target *T = &TM->getTarget();
|
|
|
|
|
|
|
|
SplitModule(
|
2021-01-29 11:20:54 +01:00
|
|
|
Mod, ParallelCodeGenParallelismLevel,
|
2016-08-11 16:58:12 +02:00
|
|
|
[&](std::unique_ptr<Module> MPart) {
|
|
|
|
// We want to clone the module in a new context to multi-thread the
|
|
|
|
// codegen. We do it by serializing partition modules to bitcode
|
|
|
|
// (while still on the main thread, in order to avoid data races) and
|
|
|
|
// spinning up new threads which deserialize the partitions into
|
|
|
|
// separate contexts.
|
|
|
|
// FIXME: Provide a more direct way to do this in LLVM.
|
|
|
|
SmallString<0> BC;
|
|
|
|
raw_svector_ostream BCOS(BC);
|
2018-02-14 20:11:32 +01:00
|
|
|
WriteBitcodeToFile(*MPart, BCOS);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
// Enqueue the task
|
|
|
|
CodegenThreadPool.async(
|
|
|
|
[&](const SmallString<0> &BC, unsigned ThreadId) {
|
|
|
|
LTOLLVMContext Ctx(C);
|
2016-11-13 08:00:17 +01:00
|
|
|
Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
|
2016-08-11 16:58:12 +02:00
|
|
|
MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
|
|
|
|
Ctx);
|
|
|
|
if (!MOrErr)
|
|
|
|
report_fatal_error("Failed to read bitcode");
|
|
|
|
std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
|
|
|
|
|
|
|
|
std::unique_ptr<TargetMachine> TM =
|
2017-05-22 23:11:35 +02:00
|
|
|
createTargetMachine(C, T, *MPartInCtx);
|
2016-08-23 23:30:12 +02:00
|
|
|
|
2020-06-02 10:19:57 +02:00
|
|
|
codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
|
|
|
|
CombinedIndex);
|
2016-08-11 16:58:12 +02:00
|
|
|
},
|
|
|
|
// Pass BC using std::move to ensure that it get moved rather than
|
|
|
|
// copied into the thread's context.
|
|
|
|
std::move(BC), ThreadCount++);
|
|
|
|
},
|
|
|
|
false);
|
2016-09-29 05:29:28 +02:00
|
|
|
|
|
|
|
// Because the inner lambda (which runs in a worker thread) captures our local
|
|
|
|
// variables, we need to wait for the worker threads to terminate before we
|
|
|
|
// can leave the function scope.
|
2016-09-29 03:28:36 +02:00
|
|
|
CodegenThreadPool.wait();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2021-01-13 10:02:23 +01:00
|
|
|
static Expected<const Target *> initAndLookupTarget(const Config &C,
|
|
|
|
Module &Mod) {
|
2016-08-11 16:58:12 +02:00
|
|
|
if (!C.OverrideTriple.empty())
|
2016-09-07 03:08:31 +02:00
|
|
|
Mod.setTargetTriple(C.OverrideTriple);
|
|
|
|
else if (Mod.getTargetTriple().empty())
|
|
|
|
Mod.setTargetTriple(C.DefaultTriple);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
std::string Msg;
|
2016-09-07 03:08:31 +02:00
|
|
|
const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
|
2016-08-11 16:58:12 +02:00
|
|
|
if (!T)
|
|
|
|
return make_error<StringError>(Msg, inconvertibleErrorCode());
|
|
|
|
return T;
|
|
|
|
}
|
|
|
|
|
2020-01-29 02:13:12 +01:00
|
|
|
Error lto::finalizeOptimizationRemarks(
|
|
|
|
std::unique_ptr<ToolOutputFile> DiagOutputFile) {
|
2017-02-13 15:39:51 +01:00
|
|
|
// Make sure we flush the diagnostic remarks file in case the linker doesn't
|
|
|
|
// call the global destructors before exiting.
|
|
|
|
if (!DiagOutputFile)
|
2018-05-03 22:24:12 +02:00
|
|
|
return Error::success();
|
2017-02-13 15:39:51 +01:00
|
|
|
DiagOutputFile->keep();
|
|
|
|
DiagOutputFile->os().flush();
|
2018-05-03 22:24:12 +02:00
|
|
|
return Error::success();
|
2017-02-13 15:39:51 +01:00
|
|
|
}
|
|
|
|
|
2020-01-13 21:23:34 +01:00
|
|
|
Error lto::backend(const Config &C, AddStreamFn AddStream,
|
2021-01-29 11:20:54 +01:00
|
|
|
unsigned ParallelCodeGenParallelismLevel, Module &Mod,
|
2017-01-20 23:18:52 +01:00
|
|
|
ModuleSummaryIndex &CombinedIndex) {
|
2021-01-29 11:20:54 +01:00
|
|
|
Expected<const Target *> TOrErr = initAndLookupTarget(C, Mod);
|
2016-08-11 16:58:12 +02:00
|
|
|
if (!TOrErr)
|
|
|
|
return TOrErr.takeError();
|
|
|
|
|
2021-01-29 11:20:54 +01:00
|
|
|
std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2017-02-13 15:39:51 +01:00
|
|
|
if (!C.CodeGenOnly) {
|
2021-01-29 11:20:54 +01:00
|
|
|
if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
|
2020-10-28 20:08:26 +01:00
|
|
|
/*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
|
|
|
|
/*CmdArgs*/ std::vector<uint8_t>()))
|
2020-01-29 02:13:12 +01:00
|
|
|
return Error::success();
|
2017-02-13 15:39:51 +01:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
if (ParallelCodeGenParallelismLevel == 1) {
|
2021-01-29 11:20:54 +01:00
|
|
|
codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
|
2016-08-23 23:30:12 +02:00
|
|
|
} else {
|
2021-01-29 11:20:54 +01:00
|
|
|
splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
|
|
|
|
CombinedIndex);
|
2016-08-23 23:30:12 +02:00
|
|
|
}
|
2020-01-29 02:13:12 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2018-01-29 09:03:30 +01:00
|
|
|
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
|
|
|
|
const ModuleSummaryIndex &Index) {
|
2018-02-06 01:43:39 +01:00
|
|
|
std::vector<GlobalValue*> DeadGVs;
|
2018-02-05 16:44:27 +01:00
|
|
|
for (auto &GV : Mod.global_values())
|
2018-02-02 13:21:26 +01:00
|
|
|
if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
|
2018-02-06 01:43:39 +01:00
|
|
|
if (!Index.isGlobalValueLive(GVS)) {
|
|
|
|
DeadGVs.push_back(&GV);
|
|
|
|
convertToDeclaration(GV);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now that all dead bodies have been dropped, delete the actual objects
|
|
|
|
// themselves when possible.
|
|
|
|
for (GlobalValue *GV : DeadGVs) {
|
|
|
|
GV->removeDeadConstantUsers();
|
|
|
|
// Might reference something defined in native object (i.e. dropped a
|
|
|
|
// non-prevailing IR def, but we need to keep the declaration).
|
|
|
|
if (GV->use_empty())
|
|
|
|
GV->eraseFromParent();
|
|
|
|
}
|
2018-01-29 09:03:30 +01:00
|
|
|
}
|
|
|
|
|
2020-01-13 21:23:34 +01:00
|
|
|
Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
|
2017-03-22 19:22:59 +01:00
|
|
|
Module &Mod, const ModuleSummaryIndex &CombinedIndex,
|
2016-08-11 16:58:12 +02:00
|
|
|
const FunctionImporter::ImportMapTy &ImportList,
|
|
|
|
const GVSummaryMapTy &DefinedGlobals,
|
2020-09-14 19:45:00 +02:00
|
|
|
MapVector<StringRef, BitcodeModule> &ModuleMap,
|
2020-10-28 20:08:26 +01:00
|
|
|
const std::vector<uint8_t> &CmdArgs) {
|
2016-08-16 02:44:46 +02:00
|
|
|
Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
|
2016-08-11 16:58:12 +02:00
|
|
|
if (!TOrErr)
|
|
|
|
return TOrErr.takeError();
|
|
|
|
|
2017-05-22 23:11:35 +02:00
|
|
|
std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-05-03 22:24:12 +02:00
|
|
|
// Setup optimization remarks.
|
2019-10-28 22:53:31 +01:00
|
|
|
auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
|
2019-03-12 22:22:27 +01:00
|
|
|
Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
|
2020-11-17 19:37:59 +01:00
|
|
|
Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold,
|
|
|
|
Task);
|
2018-05-03 22:24:12 +02:00
|
|
|
if (!DiagFileOrErr)
|
|
|
|
return DiagFileOrErr.takeError();
|
|
|
|
auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
|
|
|
|
|
2020-04-09 01:06:25 +02:00
|
|
|
// Set the partial sample profile ratio in the profile summary module flag of
|
|
|
|
// the module, if applicable.
|
|
|
|
Mod.setPartialSampleProfileRatio(CombinedIndex);
|
|
|
|
|
2016-08-22 08:25:41 +02:00
|
|
|
if (Conf.CodeGenOnly) {
|
2020-06-02 10:19:57 +02:00
|
|
|
codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
|
2018-05-03 22:24:12 +02:00
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
2016-08-22 08:25:41 +02:00
|
|
|
}
|
|
|
|
|
2016-08-16 02:44:46 +02:00
|
|
|
if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
|
2018-05-03 22:24:12 +02:00
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2020-09-16 21:08:15 +02:00
|
|
|
auto OptimizeAndCodegen =
|
|
|
|
[&](Module &Mod, TargetMachine *TM,
|
|
|
|
std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
|
|
|
|
if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
|
|
|
|
/*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
|
|
|
|
CmdArgs))
|
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
|
|
|
|
|
|
|
codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
|
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
|
|
|
};
|
|
|
|
|
|
|
|
if (ThinLTOAssumeMerged)
|
|
|
|
return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
|
|
|
|
|
2020-02-16 02:23:18 +01:00
|
|
|
// When linking an ELF shared object, dso_local should be dropped. We
|
|
|
|
// conservatively do this for -fpic.
|
|
|
|
bool ClearDSOLocalOnDeclarations =
|
|
|
|
TM->getTargetTriple().isOSBinFormatELF() &&
|
|
|
|
TM->getRelocationModel() != Reloc::Static &&
|
|
|
|
Mod.getPIELevel() == PIELevel::Default;
|
|
|
|
renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-01-29 09:03:30 +01:00
|
|
|
dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
|
|
|
|
|
[LTO] Drop non-prevailing definitions only if linkage is not local or appending
Summary:
This fixes PR 37422
In ELF, non-weak symbols can also be non-prevailing. In this particular
PR, the __llvm_profile_* symbols are non-prevailing but weren't getting
dropped - causing multiply-defined errors with lld.
Also add a test, strong_non_prevailing.ll, to ensure that multiple
copies of a strong symbol are dropped.
To fix the test regressions exposed by this fix,
- do not mark prevailing copies for symbols with 'appending' linkage.
There's no one prevailing copy for such symbols.
- fix the prevailing version in dead-strip-fulllto.ll
- explicitly pass exported symbols to llvm-lto in fumcimport.ll and
funcimport_var.ll
Reviewers: tejohnson, pcc
Subscribers: mehdi_amini, inglorion, eraman, steven_wu, dexonsmith,
dang, srhines, llvm-commits
Differential Revision: https://reviews.llvm.org/D54125
llvm-svn: 346436
2018-11-08 21:10:07 +01:00
|
|
|
thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
|
2016-08-18 02:59:24 +02:00
|
|
|
|
2016-08-16 02:44:46 +02:00
|
|
|
if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
|
2018-05-03 22:24:12 +02:00
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
if (!DefinedGlobals.empty())
|
2016-08-16 02:44:46 +02:00
|
|
|
thinLTOInternalizeModule(Mod, DefinedGlobals);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-08-16 02:44:46 +02:00
|
|
|
if (Conf.PostInternalizeModuleHook &&
|
|
|
|
!Conf.PostInternalizeModuleHook(Task, Mod))
|
2018-05-03 22:24:12 +02:00
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
auto ModuleLoader = [&](StringRef Identifier) {
|
2016-08-23 18:53:34 +02:00
|
|
|
assert(Mod.getContext().isODRUniquingDebugTypes() &&
|
2016-09-14 20:48:43 +02:00
|
|
|
"ODR Type uniquing should be enabled on the context");
|
2016-12-14 02:17:59 +01:00
|
|
|
auto I = ModuleMap.find(Identifier);
|
|
|
|
assert(I != ModuleMap.end());
|
|
|
|
return I->second.getLazyModule(Mod.getContext(),
|
2016-12-16 22:25:01 +01:00
|
|
|
/*ShouldLazyLoadMetadata=*/true,
|
|
|
|
/*IsImporting*/ true);
|
2016-08-11 16:58:12 +02:00
|
|
|
};
|
|
|
|
|
2020-02-16 02:23:18 +01:00
|
|
|
FunctionImporter Importer(CombinedIndex, ModuleLoader,
|
|
|
|
ClearDSOLocalOnDeclarations);
|
2016-11-09 18:49:19 +01:00
|
|
|
if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
|
|
|
|
return Err;
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-08-16 02:44:46 +02:00
|
|
|
if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
|
2018-05-03 22:24:12 +02:00
|
|
|
return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2020-09-16 21:08:15 +02:00
|
|
|
return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
|
|
|
|
}
|
|
|
|
|
|
|
|
BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
|
|
|
|
if (ThinLTOAssumeMerged && BMs.size() == 1)
|
|
|
|
return BMs.begin();
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2020-09-16 21:08:15 +02:00
|
|
|
for (BitcodeModule &BM : BMs) {
|
|
|
|
Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
|
|
|
|
if (LTOInfo && LTOInfo->IsThinLTO)
|
|
|
|
return &BM;
|
|
|
|
}
|
|
|
|
return nullptr;
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
2020-09-16 21:08:15 +02:00
|
|
|
|
|
|
|
Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
|
|
|
|
Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
|
|
|
|
if (!BMsOrErr)
|
|
|
|
return BMsOrErr.takeError();
|
|
|
|
|
|
|
|
// The bitcode file may contain multiple modules, we want the one that is
|
|
|
|
// marked as being the ThinLTO module.
|
|
|
|
if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
|
|
|
|
return *Bm;
|
|
|
|
|
|
|
|
return make_error<StringError>("Could not find module summary",
|
|
|
|
inconvertibleErrorCode());
|
|
|
|
}
|
|
|
|
|
|
|
|
bool lto::loadReferencedModules(
|
|
|
|
const Module &M, const ModuleSummaryIndex &CombinedIndex,
|
|
|
|
FunctionImporter::ImportMapTy &ImportList,
|
|
|
|
MapVector<llvm::StringRef, llvm::BitcodeModule> &ModuleMap,
|
|
|
|
std::vector<std::unique_ptr<llvm::MemoryBuffer>>
|
|
|
|
&OwnedImportsLifetimeManager) {
|
|
|
|
if (ThinLTOAssumeMerged)
|
|
|
|
return true;
|
|
|
|
// We can simply import the values mentioned in the combined index, since
|
|
|
|
// we should only invoke this using the individual indexes written out
|
|
|
|
// via a WriteIndexesThinBackend.
|
|
|
|
for (const auto &GlobalList : CombinedIndex) {
|
|
|
|
// Ignore entries for undefined references.
|
|
|
|
if (GlobalList.second.SummaryList.empty())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
auto GUID = GlobalList.first;
|
|
|
|
for (const auto &Summary : GlobalList.second.SummaryList) {
|
|
|
|
// Skip the summaries for the importing module. These are included to
|
|
|
|
// e.g. record required linkage changes.
|
|
|
|
if (Summary->modulePath() == M.getModuleIdentifier())
|
|
|
|
continue;
|
|
|
|
// Add an entry to provoke importing by thinBackend.
|
|
|
|
ImportList[Summary->modulePath()].insert(GUID);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for (auto &I : ImportList) {
|
|
|
|
ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
|
|
|
|
llvm::MemoryBuffer::getFile(I.first());
|
|
|
|
if (!MBOrErr) {
|
|
|
|
errs() << "Error loading imported file '" << I.first()
|
|
|
|
<< "': " << MBOrErr.getError().message() << "\n";
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
|
|
|
|
if (!BMOrErr) {
|
|
|
|
handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
|
|
|
|
errs() << "Error loading imported file '" << I.first()
|
|
|
|
<< "': " << EIB.message() << '\n';
|
|
|
|
});
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
ModuleMap.insert({I.first(), *BMOrErr});
|
|
|
|
OwnedImportsLifetimeManager.push_back(std::move(*MBOrErr));
|
|
|
|
}
|
|
|
|
return true;
|
2020-10-29 23:43:31 +01:00
|
|
|
}
|