2016-05-24 00:54:06 +02:00
|
|
|
//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
|
|
|
|
//
|
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-05-24 00:54:06 +02:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file implements functions and classes used to support LTO.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "llvm/LTO/LTO.h"
|
2021-03-18 23:32:29 +01:00
|
|
|
#include "llvm/ADT/SmallSet.h"
|
2018-04-20 12:18:36 +02:00
|
|
|
#include "llvm/ADT/Statistic.h"
|
2021-03-18 23:32:29 +01:00
|
|
|
#include "llvm/ADT/StringExtras.h"
|
2020-01-29 02:13:12 +01:00
|
|
|
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
|
2020-06-05 10:11:35 +02:00
|
|
|
#include "llvm/Analysis/StackSafetyAnalysis.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"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/CodeGen/Analysis.h"
|
2018-04-30 16:59:11 +02:00
|
|
|
#include "llvm/Config/llvm-config.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/IR/AutoUpgrade.h"
|
|
|
|
#include "llvm/IR/DiagnosticPrinter.h"
|
2019-02-14 22:22:50 +01:00
|
|
|
#include "llvm/IR/Intrinsics.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"
|
2017-02-03 00:00:49 +01:00
|
|
|
#include "llvm/IR/Mangler.h"
|
|
|
|
#include "llvm/IR/Metadata.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/LTO/LTOBackend.h"
|
2018-12-13 20:54:27 +01:00
|
|
|
#include "llvm/LTO/SummaryBasedOptimizations.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Linker/IRMover.h"
|
2017-03-29 01:35:34 +02:00
|
|
|
#include "llvm/Object/IRObjectFile.h"
|
2019-11-15 00:15:48 +01:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2017-02-03 00:00:49 +01:00
|
|
|
#include "llvm/Support/Error.h"
|
2021-04-21 16:00:30 +02:00
|
|
|
#include "llvm/Support/FileSystem.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Support/ManagedStatic.h"
|
2016-05-24 00:54:06 +02:00
|
|
|
#include "llvm/Support/MemoryBuffer.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Support/Path.h"
|
2016-08-23 23:30:12 +02:00
|
|
|
#include "llvm/Support/SHA1.h"
|
2016-05-24 00:54:06 +02:00
|
|
|
#include "llvm/Support/SourceMgr.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Support/TargetRegistry.h"
|
|
|
|
#include "llvm/Support/ThreadPool.h"
|
2016-10-19 19:35:01 +02:00
|
|
|
#include "llvm/Support/Threading.h"
|
2020-01-28 17:05:13 +01:00
|
|
|
#include "llvm/Support/TimeProfiler.h"
|
2017-04-13 03:26:12 +02:00
|
|
|
#include "llvm/Support/VCSRevision.h"
|
2016-05-24 00:54:06 +02:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Target/TargetMachine.h"
|
|
|
|
#include "llvm/Target/TargetOptions.h"
|
|
|
|
#include "llvm/Transforms/IPO.h"
|
|
|
|
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
|
2019-08-02 15:10:52 +02:00
|
|
|
#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
|
2018-12-13 20:54:27 +01:00
|
|
|
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
|
2016-08-11 16:58:12 +02:00
|
|
|
#include "llvm/Transforms/Utils/SplitModule.h"
|
2016-05-24 00:54:06 +02:00
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
#include <set>
|
|
|
|
|
|
|
|
using namespace llvm;
|
|
|
|
using namespace lto;
|
|
|
|
using namespace object;
|
2016-05-24 00:54:06 +02:00
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
#define DEBUG_TYPE "lto"
|
|
|
|
|
2018-02-19 16:14:50 +01:00
|
|
|
static cl::opt<bool>
|
|
|
|
DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
|
|
|
|
cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
|
|
|
|
|
2018-11-05 16:49:46 +01:00
|
|
|
/// Enable global value internalization in LTO.
|
|
|
|
cl::opt<bool> EnableLTOInternalization(
|
|
|
|
"enable-lto-internalization", cl::init(true), cl::Hidden,
|
|
|
|
cl::desc("Enable global value internalization in LTO"));
|
|
|
|
|
[ThinLTO] Consolidate cache key computation between new/old LTO APIs
Summary:
The old legacy LTO API had a separate cache key computation, which was
a subset of the cache key computation in the new LTO API (from what I
can tell this is largely just because certain features such as CFI,
dsoLocal, etc are only utilized via the new LTO API). However, having
separate computations is unnecessary (much of the code is duplicated),
and can lead to bugs when adding new optimizations if both cache
computation algorithms aren't updated properly - it's much easier to
maintain if we have a single facility.
This patch refactors the old LTO API code to use the cache key
computation from the new LTO API. To do this, we set up an lto::Config
object and fill in the fields that the old LTO was hashing (the others
will just use the defaults).
There are two notable changes:
- I added a Freestanding flag to the LTO Config. Currently this is only
used by the legacy LTO API. In the patch that added it (D30791) I had
asked about adding it to the new LTO API, but it looks like that was not
addressed. This should probably be discussed as a follow up to this
change, as it is orthogonal.
- The legacy LTO API had some code that was hashing the GUID of all
preserved symbols defined in the module. I looked back at the history of
this (which was added with the original hashing in the legacy LTO API in
D18494), and there is a comment in the review thread that it was added
in preparation for future internalization. We now do the internalization
of course, and that is handled in the new LTO API cache key computation
by hashing the recorded linkage type of all defined globals. Therefore I
didn't try to move over and keep the preserved symbols handling.
Reviewers: steven_wu, pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D54635
llvm-svn: 347592
2018-11-26 21:40:37 +01:00
|
|
|
// Computes a unique hash for the Module considering the current list of
|
2016-08-23 23:30:12 +02:00
|
|
|
// export/import and other global analysis results.
|
|
|
|
// The hash is produced in \p Key.
|
[ThinLTO] Consolidate cache key computation between new/old LTO APIs
Summary:
The old legacy LTO API had a separate cache key computation, which was
a subset of the cache key computation in the new LTO API (from what I
can tell this is largely just because certain features such as CFI,
dsoLocal, etc are only utilized via the new LTO API). However, having
separate computations is unnecessary (much of the code is duplicated),
and can lead to bugs when adding new optimizations if both cache
computation algorithms aren't updated properly - it's much easier to
maintain if we have a single facility.
This patch refactors the old LTO API code to use the cache key
computation from the new LTO API. To do this, we set up an lto::Config
object and fill in the fields that the old LTO was hashing (the others
will just use the defaults).
There are two notable changes:
- I added a Freestanding flag to the LTO Config. Currently this is only
used by the legacy LTO API. In the patch that added it (D30791) I had
asked about adding it to the new LTO API, but it looks like that was not
addressed. This should probably be discussed as a follow up to this
change, as it is orthogonal.
- The legacy LTO API had some code that was hashing the GUID of all
preserved symbols defined in the module. I looked back at the history of
this (which was added with the original hashing in the legacy LTO API in
D18494), and there is a comment in the review thread that it was added
in preparation for future internalization. We now do the internalization
of course, and that is handled in the new LTO API cache key computation
by hashing the recorded linkage type of all defined globals. Therefore I
didn't try to move over and keep the preserved symbols handling.
Reviewers: steven_wu, pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D54635
llvm-svn: 347592
2018-11-26 21:40:37 +01:00
|
|
|
void llvm::computeLTOCacheKey(
|
2016-12-08 06:28:30 +01:00
|
|
|
SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
|
|
|
|
StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
|
2016-08-23 23:30:12 +02:00
|
|
|
const FunctionImporter::ExportSetTy &ExportList,
|
|
|
|
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
|
2017-03-10 22:35:17 +01:00
|
|
|
const GVSummaryMapTy &DefinedGlobals,
|
2017-08-10 01:24:07 +02:00
|
|
|
const std::set<GlobalValue::GUID> &CfiFunctionDefs,
|
|
|
|
const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
|
2016-08-23 23:30:12 +02:00
|
|
|
// Compute the unique hash for this entry.
|
|
|
|
// This is based on the current compiler version, the module itself, the
|
|
|
|
// export list, the hash for every single module in the import list, the
|
|
|
|
// list of ResolvedODR for the module, and the list of preserved symbols.
|
|
|
|
SHA1 Hasher;
|
|
|
|
|
|
|
|
// Start with the compiler revision
|
|
|
|
Hasher.update(LLVM_VERSION_STRING);
|
2017-04-13 03:26:12 +02:00
|
|
|
#ifdef LLVM_REVISION
|
2016-08-23 23:30:12 +02:00
|
|
|
Hasher.update(LLVM_REVISION);
|
|
|
|
#endif
|
|
|
|
|
2016-12-08 06:28:30 +01:00
|
|
|
// Include the parts of the LTO configuration that affect code generation.
|
|
|
|
auto AddString = [&](StringRef Str) {
|
|
|
|
Hasher.update(Str);
|
|
|
|
Hasher.update(ArrayRef<uint8_t>{0});
|
|
|
|
};
|
|
|
|
auto AddUnsigned = [&](unsigned I) {
|
|
|
|
uint8_t Data[4];
|
2020-04-06 13:23:27 +02:00
|
|
|
support::endian::write32le(Data, I);
|
2016-12-08 06:28:30 +01:00
|
|
|
Hasher.update(ArrayRef<uint8_t>{Data, 4});
|
|
|
|
};
|
2017-03-03 21:25:30 +01:00
|
|
|
auto AddUint64 = [&](uint64_t I) {
|
|
|
|
uint8_t Data[8];
|
2020-04-06 13:23:27 +02:00
|
|
|
support::endian::write64le(Data, I);
|
2017-03-03 21:25:30 +01:00
|
|
|
Hasher.update(ArrayRef<uint8_t>{Data, 8});
|
|
|
|
};
|
2016-12-08 06:28:30 +01:00
|
|
|
AddString(Conf.CPU);
|
|
|
|
// FIXME: Hash more of Options. For now all clients initialize Options from
|
|
|
|
// command-line flags (which is unsupported in production), but may set
|
|
|
|
// RelaxELFRelocations. The clang driver can also pass FunctionSections,
|
|
|
|
// DataSections and DebuggerTuning via command line flags.
|
|
|
|
AddUnsigned(Conf.Options.RelaxELFRelocations);
|
|
|
|
AddUnsigned(Conf.Options.FunctionSections);
|
|
|
|
AddUnsigned(Conf.Options.DataSections);
|
|
|
|
AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
|
|
|
|
for (auto &A : Conf.MAttrs)
|
|
|
|
AddString(A);
|
2017-05-22 23:11:35 +02:00
|
|
|
if (Conf.RelocModel)
|
|
|
|
AddUnsigned(*Conf.RelocModel);
|
|
|
|
else
|
|
|
|
AddUnsigned(-1);
|
2017-08-03 04:16:21 +02:00
|
|
|
if (Conf.CodeModel)
|
|
|
|
AddUnsigned(*Conf.CodeModel);
|
|
|
|
else
|
|
|
|
AddUnsigned(-1);
|
2016-12-08 06:28:30 +01:00
|
|
|
AddUnsigned(Conf.CGOptLevel);
|
2017-02-15 21:36:36 +01:00
|
|
|
AddUnsigned(Conf.CGFileType);
|
2016-12-08 06:28:30 +01:00
|
|
|
AddUnsigned(Conf.OptLevel);
|
[ThinLTO] Move -lto-use-new-pm to llvm-lto2, and change it to -use-new-pm.
Summary:
As we teach Clang to use ThinkLTO + new PM, it's good for the users to
inject through Config, instead of setting a flag in the LTOBackend
library. Move the flag to llvm-lto2.
As it moves to llvm-lto2, a new name -use-new-pm seems simpler and as
clear.
Reviewers: davide, tejohnson
Subscribers: mehdi_amini, Prazek, inglorion, eraman, chandlerc, llvm-commits
Differential Revision: https://reviews.llvm.org/D33799
llvm-svn: 304492
2017-06-02 01:13:44 +02:00
|
|
|
AddUnsigned(Conf.UseNewPM);
|
[ThinLTO] Consolidate cache key computation between new/old LTO APIs
Summary:
The old legacy LTO API had a separate cache key computation, which was
a subset of the cache key computation in the new LTO API (from what I
can tell this is largely just because certain features such as CFI,
dsoLocal, etc are only utilized via the new LTO API). However, having
separate computations is unnecessary (much of the code is duplicated),
and can lead to bugs when adding new optimizations if both cache
computation algorithms aren't updated properly - it's much easier to
maintain if we have a single facility.
This patch refactors the old LTO API code to use the cache key
computation from the new LTO API. To do this, we set up an lto::Config
object and fill in the fields that the old LTO was hashing (the others
will just use the defaults).
There are two notable changes:
- I added a Freestanding flag to the LTO Config. Currently this is only
used by the legacy LTO API. In the patch that added it (D30791) I had
asked about adding it to the new LTO API, but it looks like that was not
addressed. This should probably be discussed as a follow up to this
change, as it is orthogonal.
- The legacy LTO API had some code that was hashing the GUID of all
preserved symbols defined in the module. I looked back at the history of
this (which was added with the original hashing in the legacy LTO API in
D18494), and there is a comment in the review thread that it was added
in preparation for future internalization. We now do the internalization
of course, and that is handled in the new LTO API cache key computation
by hashing the recorded linkage type of all defined globals. Therefore I
didn't try to move over and keep the preserved symbols handling.
Reviewers: steven_wu, pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D54635
llvm-svn: 347592
2018-11-26 21:40:37 +01:00
|
|
|
AddUnsigned(Conf.Freestanding);
|
2016-12-08 06:28:30 +01:00
|
|
|
AddString(Conf.OptPipeline);
|
|
|
|
AddString(Conf.AAPipeline);
|
|
|
|
AddString(Conf.OverrideTriple);
|
|
|
|
AddString(Conf.DefaultTriple);
|
2018-04-13 07:03:28 +02:00
|
|
|
AddString(Conf.DwoDir);
|
2016-12-08 06:28:30 +01:00
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
// Include the hash for the current module
|
|
|
|
auto ModHash = Index.getModuleHash(ModuleID);
|
|
|
|
Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
|
2020-06-09 22:46:28 +02:00
|
|
|
|
|
|
|
std::vector<uint64_t> ExportsGUID;
|
|
|
|
ExportsGUID.reserve(ExportList.size());
|
2019-11-15 14:13:19 +01:00
|
|
|
for (const auto &VI : ExportList) {
|
|
|
|
auto GUID = VI.getGUID();
|
2020-06-09 22:46:28 +02:00
|
|
|
ExportsGUID.push_back(GUID);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sort the export list elements GUIDs.
|
|
|
|
llvm::sort(ExportsGUID);
|
|
|
|
for (uint64_t GUID : ExportsGUID) {
|
2016-08-23 23:30:12 +02:00
|
|
|
// The export list can impact the internalization, be conservative here
|
2019-11-15 14:13:19 +01:00
|
|
|
Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
|
|
|
|
}
|
2016-08-23 23:30:12 +02:00
|
|
|
|
2017-03-03 21:25:30 +01:00
|
|
|
// Include the hash for every module we import functions from. The set of
|
|
|
|
// imported symbols for each module may affect code generation and is
|
|
|
|
// sensitive to link order, so include that as well.
|
2020-06-09 22:46:28 +02:00
|
|
|
using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator;
|
|
|
|
std::vector<ImportMapIteratorTy> ImportModulesVector;
|
|
|
|
ImportModulesVector.reserve(ImportList.size());
|
|
|
|
|
|
|
|
for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end();
|
|
|
|
++It) {
|
|
|
|
ImportModulesVector.push_back(It);
|
|
|
|
}
|
|
|
|
llvm::sort(ImportModulesVector,
|
|
|
|
[](const ImportMapIteratorTy &Lhs, const ImportMapIteratorTy &Rhs)
|
|
|
|
-> bool { return Lhs->getKey() < Rhs->getKey(); });
|
|
|
|
for (const ImportMapIteratorTy &EntryIt : ImportModulesVector) {
|
|
|
|
auto ModHash = Index.getModuleHash(EntryIt->first());
|
2016-08-23 23:30:12 +02:00
|
|
|
Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
|
2017-03-03 21:25:30 +01:00
|
|
|
|
2020-06-09 22:46:28 +02:00
|
|
|
AddUint64(EntryIt->second.size());
|
|
|
|
for (auto &Fn : EntryIt->second)
|
Restore "[ThinLTO] Ensure we always select the same function copy to import"
This reverts commit r337081, therefore restoring r337050 (and fix in
r337059), with test fix for bot failure described after the original
description below.
In order to always import the same copy of a linkonce function,
even when encountering it with different thresholds (a higher one then a
lower one), keep track of the summary we decided to import.
This ensures that the backend only gets a single definition to import
for each GUID, so that it doesn't need to choose one.
Move the largest threshold the GUID was considered for import into the
current module out of the ImportMap (which is part of a larger map
maintained across the whole index), and into a new map just maintained
for the current module we are computing imports for. This saves some
memory since we no longer have the thresholds maintained across the
whole index (and throughout the in-process backends when doing a normal
non-distributed ThinLTO build), at the cost of some additional
information being maintained for each invocation of ComputeImportForModule
(the selected summary pointer for each import).
There is an additional map lookup for each callee being considered for
importing, however, this was able to subsume a map lookup in the
Worklist iteration that invokes computeImportForFunction. We also are
able to avoid calling selectCallee if we already failed to import at the
same or higher threshold.
I compared the run time and peak memory for the SPEC2006 471.omnetpp
benchmark (running in-process ThinLTO backends), as well as for a large
internal benchmark with a distributed ThinLTO build (so just looking at
the thin link time/memory). Across a number of runs with and without
this change there was no significant change in the time and memory.
(I tried a few other variations of the change but they also didn't
improve time or peak memory).
The new commit removes a test that no longer makes sense
(Transforms/FunctionImport/hotness_based_import2.ll), as exposed by the
reverse-iteration bot. The test depends on the order of processing the
summary call edges, and actually depended on the old problematic
behavior of selecting more than one summary for a given GUID when
encountered with different thresholds. There was no guarantee even
before that we would eventually pick the linkonce copy with the hottest
call edges, it just happened to work with the test and the old code, and
there was no guarantee that we would end up importing the selected
version of the copy that had the hottest call edges (since the backend
would effectively import only one of the selected copies).
Reviewers: davidxl
Subscribers: mehdi_amini, inglorion, llvm-commits
Differential Revision: https://reviews.llvm.org/D48670
llvm-svn: 337184
2018-07-16 17:30:27 +02:00
|
|
|
AddUint64(Fn);
|
2016-08-23 23:30:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Include the hash for the resolved ODR.
|
|
|
|
for (auto &Entry : ResolvedODR) {
|
|
|
|
Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
|
|
|
|
sizeof(GlobalValue::GUID)));
|
|
|
|
Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
|
|
|
|
sizeof(GlobalValue::LinkageTypes)));
|
|
|
|
}
|
|
|
|
|
2017-08-10 01:24:07 +02:00
|
|
|
// Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
|
|
|
|
// defined in this module.
|
|
|
|
std::set<GlobalValue::GUID> UsedCfiDefs;
|
|
|
|
std::set<GlobalValue::GUID> UsedCfiDecls;
|
|
|
|
|
|
|
|
// Typeids used in this module.
|
2017-03-10 22:35:17 +01:00
|
|
|
std::set<GlobalValue::GUID> UsedTypeIds;
|
|
|
|
|
2017-08-10 01:24:07 +02:00
|
|
|
auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
|
|
|
|
if (CfiFunctionDefs.count(ValueGUID))
|
|
|
|
UsedCfiDefs.insert(ValueGUID);
|
|
|
|
if (CfiFunctionDecls.count(ValueGUID))
|
|
|
|
UsedCfiDecls.insert(ValueGUID);
|
|
|
|
};
|
|
|
|
|
|
|
|
auto AddUsedThings = [&](GlobalValueSummary *GS) {
|
|
|
|
if (!GS) return;
|
2021-01-27 19:43:51 +01:00
|
|
|
AddUnsigned(GS->getVisibility());
|
2018-02-09 06:58:55 +01:00
|
|
|
AddUnsigned(GS->isLive());
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
AddUnsigned(GS->canAutoHide());
|
2018-02-05 18:17:51 +01:00
|
|
|
for (const ValueInfo &VI : GS->refs()) {
|
2021-02-10 06:14:43 +01:00
|
|
|
AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
|
2017-08-10 01:24:07 +02:00
|
|
|
AddUsedCfiGlobal(VI.getGUID());
|
2018-02-05 18:17:51 +01:00
|
|
|
}
|
2019-07-05 17:25:05 +02:00
|
|
|
if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
|
|
|
|
AddUnsigned(GVS->maybeReadOnly());
|
|
|
|
AddUnsigned(GVS->maybeWriteOnly());
|
|
|
|
}
|
2017-08-10 01:24:07 +02:00
|
|
|
if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
|
|
|
|
for (auto &TT : FS->type_tests())
|
|
|
|
UsedTypeIds.insert(TT);
|
|
|
|
for (auto &TT : FS->type_test_assume_vcalls())
|
|
|
|
UsedTypeIds.insert(TT.GUID);
|
|
|
|
for (auto &TT : FS->type_checked_load_vcalls())
|
|
|
|
UsedTypeIds.insert(TT.GUID);
|
|
|
|
for (auto &TT : FS->type_test_assume_const_vcalls())
|
|
|
|
UsedTypeIds.insert(TT.VFunc.GUID);
|
|
|
|
for (auto &TT : FS->type_checked_load_const_vcalls())
|
|
|
|
UsedTypeIds.insert(TT.VFunc.GUID);
|
2018-02-06 00:46:32 +01:00
|
|
|
for (auto &ET : FS->calls()) {
|
2021-02-10 06:14:43 +01:00
|
|
|
AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
|
2017-08-10 01:24:07 +02:00
|
|
|
AddUsedCfiGlobal(ET.first.getGUID());
|
2018-02-06 00:46:32 +01:00
|
|
|
}
|
2017-08-10 01:24:07 +02:00
|
|
|
}
|
2017-03-10 22:35:17 +01:00
|
|
|
};
|
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
// Include the hash for the linkage type to reflect internalization and weak
|
2017-03-10 22:35:17 +01:00
|
|
|
// resolution, and collect any used type identifier resolutions.
|
2016-08-23 23:30:12 +02:00
|
|
|
for (auto &GS : DefinedGlobals) {
|
|
|
|
GlobalValue::LinkageTypes Linkage = GS.second->linkage();
|
|
|
|
Hasher.update(
|
|
|
|
ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
|
2017-08-10 01:24:07 +02:00
|
|
|
AddUsedCfiGlobal(GS.first);
|
|
|
|
AddUsedThings(GS.second);
|
2017-03-10 22:35:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Imported functions may introduce new uses of type identifier resolutions,
|
|
|
|
// so we need to collect their used resolutions as well.
|
|
|
|
for (auto &ImpM : ImportList)
|
2018-12-04 01:02:33 +01:00
|
|
|
for (auto &ImpF : ImpM.second) {
|
|
|
|
GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
|
|
|
|
AddUsedThings(S);
|
|
|
|
// If this is an alias, we also care about any types/etc. that the aliasee
|
|
|
|
// may reference.
|
|
|
|
if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
|
|
|
|
AddUsedThings(AS->getBaseObject());
|
|
|
|
}
|
2017-03-10 22:35:17 +01:00
|
|
|
|
|
|
|
auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
|
|
|
|
AddString(TId);
|
|
|
|
|
|
|
|
AddUnsigned(S.TTRes.TheKind);
|
|
|
|
AddUnsigned(S.TTRes.SizeM1BitWidth);
|
2017-03-10 22:37:10 +01:00
|
|
|
|
2017-09-12 00:49:10 +02:00
|
|
|
AddUint64(S.TTRes.AlignLog2);
|
|
|
|
AddUint64(S.TTRes.SizeM1);
|
|
|
|
AddUint64(S.TTRes.BitMask);
|
|
|
|
AddUint64(S.TTRes.InlineBits);
|
|
|
|
|
2017-03-10 22:37:10 +01:00
|
|
|
AddUint64(S.WPDRes.size());
|
|
|
|
for (auto &WPD : S.WPDRes) {
|
|
|
|
AddUnsigned(WPD.first);
|
|
|
|
AddUnsigned(WPD.second.TheKind);
|
|
|
|
AddString(WPD.second.SingleImplName);
|
|
|
|
|
|
|
|
AddUint64(WPD.second.ResByArg.size());
|
|
|
|
for (auto &ByArg : WPD.second.ResByArg) {
|
|
|
|
AddUint64(ByArg.first.size());
|
|
|
|
for (uint64_t Arg : ByArg.first)
|
|
|
|
AddUint64(Arg);
|
|
|
|
AddUnsigned(ByArg.second.TheKind);
|
|
|
|
AddUint64(ByArg.second.Info);
|
2017-09-12 00:34:42 +02:00
|
|
|
AddUnsigned(ByArg.second.Byte);
|
|
|
|
AddUnsigned(ByArg.second.Bit);
|
2017-03-10 22:37:10 +01:00
|
|
|
}
|
|
|
|
}
|
2017-03-10 22:35:17 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// Include the hash for all type identifiers used by this module.
|
|
|
|
for (GlobalValue::GUID TId : UsedTypeIds) {
|
[ThinLTO] Efficiency fix for writing type id records in per-module indexes
Summary:
In D49565/r337503, the type id record writing was fixed so that only
referenced type ids were emitted into each per-module index for ThinLTO
distributed builds. However, this still left an efficiency issue: each
per-module index checked all type ids for membership in the referenced
set, yielding O(M*N) performance (M indexes and N type ids).
Change the TypeIdMap in the summary to be indexed by GUID, to facilitate
correlating with type identifier GUIDs referenced in the function
summary TypeIdInfo structures. This allowed simplifying other
places where a map from type id GUID to type id map entry was previously
being used to aid this correlation.
Also fix AsmWriter code to handle the rare case of type id GUID
collision.
For a large internal application, this reduced the thin link time by
almost 15%.
Reviewers: pcc, vitalybuka
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51330
llvm-svn: 343021
2018-09-25 22:14:40 +02:00
|
|
|
auto TidIter = Index.typeIds().equal_range(TId);
|
|
|
|
for (auto It = TidIter.first; It != TidIter.second; ++It)
|
|
|
|
AddTypeIdSummary(It->second.first, It->second.second);
|
2016-08-23 23:30:12 +02:00
|
|
|
}
|
|
|
|
|
2017-08-10 01:24:07 +02:00
|
|
|
AddUnsigned(UsedCfiDefs.size());
|
|
|
|
for (auto &V : UsedCfiDefs)
|
|
|
|
AddUint64(V);
|
|
|
|
|
|
|
|
AddUnsigned(UsedCfiDecls.size());
|
|
|
|
for (auto &V : UsedCfiDecls)
|
|
|
|
AddUint64(V);
|
|
|
|
|
2016-12-16 17:48:46 +01:00
|
|
|
if (!Conf.SampleProfile.empty()) {
|
|
|
|
auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
|
Add a flag to remap manglings when reading profile data information.
This can be used to preserve profiling information across codebase
changes that have widespread impact on mangled names, but across which
most profiling data should still be usable. For example, when switching
from libstdc++ to libc++, or from the old libstdc++ ABI to the new ABI,
or even from a 32-bit to a 64-bit build.
The user can provide a remapping file specifying parts of mangled names
that should be treated as equivalent (eg, std::__1 should be treated as
equivalent to std::__cxx11), and profile data will be treated as
applying to a particular function if its name is equivalent to the name
of a function in the profile data under the provided equivalences. See
the documentation change for a description of how this is configured.
Remapping is supported for both sample-based profiling and instruction
profiling. We do not support remapping indirect branch target
information, but all other profile data should be remapped
appropriately.
Support is only added for the new pass manager. If someone wants to also
add support for this for the old pass manager, doing so should be
straightforward.
This is the LLVM side of Clang r344199.
Reviewers: davidxl, tejohnson, dlj, erik.pilkington
Subscribers: mehdi_amini, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51249
llvm-svn: 344200
2018-10-11 01:13:47 +02:00
|
|
|
if (FileOrErr) {
|
2016-12-16 17:48:46 +01:00
|
|
|
Hasher.update(FileOrErr.get()->getBuffer());
|
Add a flag to remap manglings when reading profile data information.
This can be used to preserve profiling information across codebase
changes that have widespread impact on mangled names, but across which
most profiling data should still be usable. For example, when switching
from libstdc++ to libc++, or from the old libstdc++ ABI to the new ABI,
or even from a 32-bit to a 64-bit build.
The user can provide a remapping file specifying parts of mangled names
that should be treated as equivalent (eg, std::__1 should be treated as
equivalent to std::__cxx11), and profile data will be treated as
applying to a particular function if its name is equivalent to the name
of a function in the profile data under the provided equivalences. See
the documentation change for a description of how this is configured.
Remapping is supported for both sample-based profiling and instruction
profiling. We do not support remapping indirect branch target
information, but all other profile data should be remapped
appropriately.
Support is only added for the new pass manager. If someone wants to also
add support for this for the old pass manager, doing so should be
straightforward.
This is the LLVM side of Clang r344199.
Reviewers: davidxl, tejohnson, dlj, erik.pilkington
Subscribers: mehdi_amini, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51249
llvm-svn: 344200
2018-10-11 01:13:47 +02:00
|
|
|
|
|
|
|
if (!Conf.ProfileRemapping.empty()) {
|
|
|
|
FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
|
|
|
|
if (FileOrErr)
|
|
|
|
Hasher.update(FileOrErr.get()->getBuffer());
|
|
|
|
}
|
|
|
|
}
|
2016-12-16 17:48:46 +01:00
|
|
|
}
|
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
Key = toHex(Hasher.result());
|
|
|
|
}
|
|
|
|
|
[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
|
|
|
static void thinLTOResolvePrevailingGUID(
|
2021-01-27 19:43:51 +01:00
|
|
|
const Config &C, ValueInfo VI,
|
|
|
|
DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
|
2016-06-12 18:13:55 +02:00
|
|
|
function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
|
2016-05-25 16:03:11 +02:00
|
|
|
isPrevailing,
|
2016-06-12 18:13:55 +02:00
|
|
|
function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
recordNewLinkage,
|
|
|
|
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
|
2021-01-27 19:43:51 +01:00
|
|
|
GlobalValue::VisibilityTypes Visibility =
|
|
|
|
C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
|
|
|
|
: GlobalValue::DefaultVisibility;
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
for (auto &S : VI.getSummaryList()) {
|
2016-05-25 16:03:11 +02:00
|
|
|
GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
|
[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
|
|
|
// Ignore local and appending linkage values since the linker
|
|
|
|
// doesn't resolve them.
|
|
|
|
if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
|
|
|
|
GlobalValue::isAppendingLinkage(S->linkage()))
|
2016-05-25 16:03:11 +02:00
|
|
|
continue;
|
2016-07-07 20:31:51 +02:00
|
|
|
// We need to emit only one of these. The prevailing module will keep it,
|
2016-05-25 16:03:11 +02:00
|
|
|
// but turned into a weak, while the others will drop it when possible.
|
2016-10-30 06:15:23 +01:00
|
|
|
// This is both a compile-time optimization and a correctness
|
|
|
|
// transformation. This is necessary for correctness when we have exported
|
|
|
|
// a reference - we need to convert the linkonce to weak to
|
|
|
|
// ensure a copy is kept to satisfy the exported reference.
|
|
|
|
// FIXME: We may want to split the compile time and correctness
|
|
|
|
// aspects into separate routines.
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
if (isPrevailing(VI.getGUID(), S.get())) {
|
|
|
|
if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
|
2016-05-26 16:16:52 +02:00
|
|
|
S->setLinkage(GlobalValue::getWeakLinkage(
|
|
|
|
GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
// The kept copy is eligible for auto-hiding (hidden visibility) if all
|
|
|
|
// copies were (i.e. they were all linkonce_odr global unnamed addr).
|
|
|
|
// If any copy is not (e.g. it was originally weak_odr), then the symbol
|
|
|
|
// must remain externally available (e.g. a weak_odr from an explicitly
|
|
|
|
// instantiated template). Additionally, if it is in the
|
|
|
|
// GUIDPreservedSymbols set, that means that it is visibile outside
|
|
|
|
// the summary (e.g. in a native object or a bitcode file without
|
|
|
|
// summary), and in that case we cannot hide it as it isn't possible to
|
|
|
|
// check all copies.
|
|
|
|
S->setCanAutoHide(VI.canAutoHide() &&
|
|
|
|
!GUIDPreservedSymbols.count(VI.getGUID()));
|
|
|
|
}
|
2021-01-27 19:43:51 +01:00
|
|
|
if (C.VisibilityScheme == Config::FromPrevailing)
|
|
|
|
Visibility = S->getVisibility();
|
2016-05-25 16:03:11 +02:00
|
|
|
}
|
2016-10-30 06:15:23 +01:00
|
|
|
// Alias and aliasee can't be turned into available_externally.
|
2016-05-25 16:03:11 +02:00
|
|
|
else if (!isa<AliasSummary>(S.get()) &&
|
2017-01-20 22:54:58 +01:00
|
|
|
!GlobalInvolvedWithAlias.count(S.get()))
|
2016-05-25 16:03:11 +02:00
|
|
|
S->setLinkage(GlobalValue::AvailableExternallyLinkage);
|
2021-01-27 19:43:51 +01:00
|
|
|
|
|
|
|
// For ELF, set visibility to the computed visibility from summaries. We
|
|
|
|
// don't track visibility from declarations so this may be more relaxed than
|
|
|
|
// the most constraining one.
|
|
|
|
if (C.VisibilityScheme == Config::ELF)
|
|
|
|
S->setVisibility(Visibility);
|
|
|
|
|
2016-05-25 16:03:11 +02:00
|
|
|
if (S->linkage() != OriginalLinkage)
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
|
2016-05-25 16:03:11 +02:00
|
|
|
}
|
2021-01-27 19:43:51 +01:00
|
|
|
|
|
|
|
if (C.VisibilityScheme == Config::FromPrevailing) {
|
|
|
|
for (auto &S : VI.getSummaryList()) {
|
|
|
|
GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
|
|
|
|
if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
|
|
|
|
GlobalValue::isAppendingLinkage(S->linkage()))
|
|
|
|
continue;
|
|
|
|
S->setVisibility(Visibility);
|
|
|
|
}
|
|
|
|
}
|
2016-05-25 16:03:11 +02:00
|
|
|
}
|
|
|
|
|
[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
|
|
|
/// Resolve linkage for prevailing symbols in the \p Index.
|
2016-05-25 16:03:11 +02:00
|
|
|
//
|
|
|
|
// We'd like to drop these functions if they are no longer referenced in the
|
|
|
|
// current module. However there is a chance that another module is still
|
|
|
|
// referencing them because of the import. We make sure we always emit at least
|
|
|
|
// one copy.
|
[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
|
|
|
void llvm::thinLTOResolvePrevailingInIndex(
|
2021-01-27 19:43:51 +01:00
|
|
|
const Config &C, ModuleSummaryIndex &Index,
|
2016-06-12 18:13:55 +02:00
|
|
|
function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
|
2016-05-25 16:03:11 +02:00
|
|
|
isPrevailing,
|
2016-06-12 18:13:55 +02:00
|
|
|
function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
recordNewLinkage,
|
|
|
|
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
|
2016-05-25 16:03:11 +02:00
|
|
|
// We won't optimize the globals that are referenced by an alias for now
|
|
|
|
// Ideally we should turn the alias into a global and duplicate the definition
|
|
|
|
// when needed.
|
|
|
|
DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
|
|
|
|
for (auto &I : Index)
|
2017-05-04 20:03:25 +02:00
|
|
|
for (auto &S : I.second.SummaryList)
|
2016-05-25 16:03:11 +02:00
|
|
|
if (auto AS = dyn_cast<AliasSummary>(S.get()))
|
|
|
|
GlobalInvolvedWithAlias.insert(&AS->getAliasee());
|
|
|
|
|
|
|
|
for (auto &I : Index)
|
2021-01-27 19:43:51 +01:00
|
|
|
thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
|
|
|
|
GlobalInvolvedWithAlias, isPrevailing,
|
|
|
|
recordNewLinkage, GUIDPreservedSymbols);
|
2016-05-25 16:03:11 +02:00
|
|
|
}
|
|
|
|
|
2019-07-05 17:25:05 +02:00
|
|
|
static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) {
|
2019-05-13 13:53:05 +02:00
|
|
|
if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
|
2019-07-05 17:25:05 +02:00
|
|
|
return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
|
2019-05-13 13:53:05 +02:00
|
|
|
(VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
|
|
|
|
VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2016-05-25 16:03:11 +02:00
|
|
|
static void thinLTOInternalizeAndPromoteGUID(
|
2019-11-19 13:51:25 +01:00
|
|
|
ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
|
[ThinLTO] Fix handling of weak interposable symbols
Summary:
Keep aliasees alive if their alias is live, otherwise we end up with an
alias to a declaration, which is invalid. This can happen when the
aliasee is weak and non-prevailing.
This fix exposed the fact that we were then attempting to internalize
the weak symbol, which was not exported as it was not prevailing. We
should not internalize interposable symbols in general, unless this is
the prevailing copy, since it can lead to incorrect inlining and other
optimizations. Most of the changes in this patch are due to the
restructuring required to pass down the prevailing callback.
Finally, while implementing the test cases, I found that in the case of
a weak aliasee that is still marked not live because its alias isn't
live, after dropping the definition we incorrectly marked the
declaration with weak linkage when resolving prevailing symbols in the
module. This was due to some special case handling for symbols marked
WeakLinkage in the summary located before instead of after a subsequent
check for the symbol being a declaration. It turns out that we don't
actually need this special case handling any more (looking back at the
history, when that was added the code was structured quite differently)
- we will correctly mark with weak linkage further below when the
definition hasn't been dropped.
Fixes PR42542.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, dang, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D66264
llvm-svn: 369766
2019-08-23 17:18:58 +02:00
|
|
|
function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
|
|
|
|
isPrevailing) {
|
2019-11-19 13:51:25 +01:00
|
|
|
for (auto &S : VI.getSummaryList()) {
|
2019-11-15 14:13:19 +01:00
|
|
|
if (isExported(S->modulePath(), VI)) {
|
2016-05-25 16:03:11 +02:00
|
|
|
if (GlobalValue::isLocalLinkage(S->linkage()))
|
|
|
|
S->setLinkage(GlobalValue::ExternalLinkage);
|
2018-11-05 16:49:46 +01:00
|
|
|
} else if (EnableLTOInternalization &&
|
[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
|
|
|
// Ignore local and appending linkage values since the linker
|
|
|
|
// doesn't resolve them.
|
|
|
|
!GlobalValue::isLocalLinkage(S->linkage()) &&
|
[ThinLTO] Fix handling of weak interposable symbols
Summary:
Keep aliasees alive if their alias is live, otherwise we end up with an
alias to a declaration, which is invalid. This can happen when the
aliasee is weak and non-prevailing.
This fix exposed the fact that we were then attempting to internalize
the weak symbol, which was not exported as it was not prevailing. We
should not internalize interposable symbols in general, unless this is
the prevailing copy, since it can lead to incorrect inlining and other
optimizations. Most of the changes in this patch are due to the
restructuring required to pass down the prevailing callback.
Finally, while implementing the test cases, I found that in the case of
a weak aliasee that is still marked not live because its alias isn't
live, after dropping the definition we incorrectly marked the
declaration with weak linkage when resolving prevailing symbols in the
module. This was due to some special case handling for symbols marked
WeakLinkage in the summary located before instead of after a subsequent
check for the symbol being a declaration. It turns out that we don't
actually need this special case handling any more (looking back at the
history, when that was added the code was structured quite differently)
- we will correctly mark with weak linkage further below when the
definition hasn't been dropped.
Fixes PR42542.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, dang, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D66264
llvm-svn: 369766
2019-08-23 17:18:58 +02:00
|
|
|
(!GlobalValue::isInterposableLinkage(S->linkage()) ||
|
2019-11-15 14:13:19 +01:00
|
|
|
isPrevailing(VI.getGUID(), S.get())) &&
|
2018-12-05 01:09:36 +01:00
|
|
|
S->linkage() != GlobalValue::AppendingLinkage &&
|
|
|
|
// We can't internalize available_externally globals because this
|
|
|
|
// can break function pointer equality.
|
2019-05-13 13:53:05 +02:00
|
|
|
S->linkage() != GlobalValue::AvailableExternallyLinkage &&
|
2019-07-05 17:25:05 +02:00
|
|
|
// Functions and read-only variables with linkonce_odr and
|
|
|
|
// weak_odr linkage can be internalized. We can't internalize
|
|
|
|
// linkonce_odr and weak_odr variables which are both modified
|
|
|
|
// and read somewhere in the program because reads and writes
|
|
|
|
// will become inconsistent.
|
|
|
|
!isWeakObjectWithRWAccess(S.get()))
|
2016-05-25 16:03:11 +02:00
|
|
|
S->setLinkage(GlobalValue::InternalLinkage);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the linkages in the given \p Index to mark exported values
|
|
|
|
// as external and non-exported values as internal.
|
2016-08-11 16:58:12 +02:00
|
|
|
void llvm::thinLTOInternalizeAndPromoteInIndex(
|
2016-05-25 16:03:11 +02:00
|
|
|
ModuleSummaryIndex &Index,
|
2019-11-15 14:13:19 +01:00
|
|
|
function_ref<bool(StringRef, ValueInfo)> isExported,
|
[ThinLTO] Fix handling of weak interposable symbols
Summary:
Keep aliasees alive if their alias is live, otherwise we end up with an
alias to a declaration, which is invalid. This can happen when the
aliasee is weak and non-prevailing.
This fix exposed the fact that we were then attempting to internalize
the weak symbol, which was not exported as it was not prevailing. We
should not internalize interposable symbols in general, unless this is
the prevailing copy, since it can lead to incorrect inlining and other
optimizations. Most of the changes in this patch are due to the
restructuring required to pass down the prevailing callback.
Finally, while implementing the test cases, I found that in the case of
a weak aliasee that is still marked not live because its alias isn't
live, after dropping the definition we incorrectly marked the
declaration with weak linkage when resolving prevailing symbols in the
module. This was due to some special case handling for symbols marked
WeakLinkage in the summary located before instead of after a subsequent
check for the symbol being a declaration. It turns out that we don't
actually need this special case handling any more (looking back at the
history, when that was added the code was structured quite differently)
- we will correctly mark with weak linkage further below when the
definition hasn't been dropped.
Fixes PR42542.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, dang, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D66264
llvm-svn: 369766
2019-08-23 17:18:58 +02:00
|
|
|
function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
|
|
|
|
isPrevailing) {
|
2016-05-25 16:03:11 +02:00
|
|
|
for (auto &I : Index)
|
2019-11-19 13:51:25 +01:00
|
|
|
thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
|
|
|
|
isPrevailing);
|
2016-05-25 16:03:11 +02:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
// Requires a destructor for std::vector<InputModule>.
|
|
|
|
InputFile::~InputFile() = default;
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
|
|
|
|
std::unique_ptr<InputFile> File(new InputFile);
|
2016-11-13 08:00:17 +01:00
|
|
|
|
2017-06-08 03:26:14 +02:00
|
|
|
Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
|
|
|
|
if (!FOrErr)
|
|
|
|
return FOrErr.takeError();
|
2017-03-31 06:47:07 +02:00
|
|
|
|
2017-06-08 03:26:14 +02:00
|
|
|
File->TargetTriple = FOrErr->TheReader.getTargetTriple();
|
|
|
|
File->SourceFileName = FOrErr->TheReader.getSourceFileName();
|
|
|
|
File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
|
[ELF] Implement Dependent Libraries Feature
This patch implements a limited form of autolinking primarily designed to allow
either the --dependent-library compiler option, or "comment lib" pragmas (
https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=vs-2017) in
C/C++ e.g. #pragma comment(lib, "foo"), to cause an ELF linker to automatically
add the specified library to the link when processing the input file generated
by the compiler.
Currently this extension is unique to LLVM and LLD. However, care has been taken
to design this feature so that it could be supported by other ELF linkers.
The design goals were to provide:
- A simple linking model for developers to reason about.
- The ability to to override autolinking from the linker command line.
- Source code compatibility, where possible, with "comment lib" pragmas in other
environments (MSVC in particular).
Dependent library support is implemented differently for ELF platforms than on
the other platforms. Primarily this difference is that on ELF we pass the
dependent library specifiers directly to the linker without manipulating them.
This is in contrast to other platforms where they are mapped to a specific
linker option by the compiler. This difference is a result of the greater
variety of ELF linkers and the fact that ELF linkers tend to handle libraries in
a more complicated fashion than on other platforms. This forces us to defer
handling the specifiers to the linker.
In order to achieve a level of source code compatibility with other platforms
we have restricted this feature to work with libraries that meet the following
"reasonable" requirements:
1. There are no competing defined symbols in a given set of libraries, or
if they exist, the program owner doesn't care which is linked to their
program.
2. There may be circular dependencies between libraries.
The binary representation is a mergeable string section (SHF_MERGE,
SHF_STRINGS), called .deplibs, with custom type SHT_LLVM_DEPENDENT_LIBRARIES
(0x6fff4c04). The compiler forms this section by concatenating the arguments of
the "comment lib" pragmas and --dependent-library options in the order they are
encountered. Partial (-r, -Ur) links are handled by concatenating .deplibs
sections with the normal mergeable string section rules. As an example, #pragma
comment(lib, "foo") would result in:
.section ".deplibs","MS",@llvm_dependent_libraries,1
.asciz "foo"
For LTO, equivalent information to the contents of a the .deplibs section can be
retrieved by the LLD for bitcode input files.
LLD processes the dependent library specifiers in the following way:
1. Dependent libraries which are found from the specifiers in .deplibs sections
of relocatable object files are added when the linker decides to include that
file (which could itself be in a library) in the link. Dependent libraries
behave as if they were appended to the command line after all other options. As
a consequence the set of dependent libraries are searched last to resolve
symbols.
2. It is an error if a file cannot be found for a given specifier.
3. Any command line options in effect at the end of the command line parsing apply
to the dependent libraries, e.g. --whole-archive.
4. The linker tries to add a library or relocatable object file from each of the
strings in a .deplibs section by; first, handling the string as if it was
specified on the command line; second, by looking for the string in each of the
library search paths in turn; third, by looking for a lib<string>.a or
lib<string>.so (depending on the current mode of the linker) in each of the
library search paths.
5. A new command line option --no-dependent-libraries tells LLD to ignore the
dependent libraries.
Rationale for the above points:
1. Adding the dependent libraries last makes the process simple to understand
from a developers perspective. All linkers are able to implement this scheme.
2. Error-ing for libraries that are not found seems like better behavior than
failing the link during symbol resolution.
3. It seems useful for the user to be able to apply command line options which
will affect all of the dependent libraries. There is a potential problem of
surprise for developers, who might not realize that these options would apply
to these "invisible" input files; however, despite the potential for surprise,
this is easy for developers to reason about and gives developers the control
that they may require.
4. This algorithm takes into account all of the different ways that ELF linkers
find input files. The different search methods are tried by the linker in most
obvious to least obvious order.
5. I considered adding finer grained control over which dependent libraries were
ignored (e.g. MSVC has /nodefaultlib:<library>); however, I concluded that this
is not necessary: if finer control is required developers can fall back to using
the command line directly.
RFC thread: http://lists.llvm.org/pipermail/llvm-dev/2019-March/131004.html.
Differential Revision: https://reviews.llvm.org/D60274
llvm-svn: 360984
2019-05-17 05:44:15 +02:00
|
|
|
File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
|
2017-06-08 03:26:14 +02:00
|
|
|
File->ComdatTable = FOrErr->TheReader.getComdatTable();
|
2017-03-31 06:47:07 +02:00
|
|
|
|
2017-06-08 03:26:14 +02:00
|
|
|
for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
|
2017-03-31 06:47:07 +02:00
|
|
|
size_t Begin = File->Symbols.size();
|
2017-06-08 03:26:14 +02:00
|
|
|
for (const irsymtab::Reader::SymbolRef &Sym :
|
|
|
|
FOrErr->TheReader.module_symbols(I))
|
2017-03-31 06:47:07 +02:00
|
|
|
// Skip symbols that are irrelevant to LTO. Note that this condition needs
|
|
|
|
// to match the one in Skip() in LTO::addRegularLTO().
|
|
|
|
if (Sym.isGlobal() && !Sym.isFormatSpecific())
|
|
|
|
File->Symbols.push_back(Sym);
|
|
|
|
File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
|
2017-03-31 04:44:50 +02:00
|
|
|
}
|
|
|
|
|
2017-06-08 03:26:14 +02:00
|
|
|
File->Mods = FOrErr->Mods;
|
|
|
|
File->Strtab = std::move(FOrErr->Strtab);
|
2020-02-10 16:06:45 +01:00
|
|
|
return std::move(File);
|
2017-03-31 04:44:50 +02:00
|
|
|
}
|
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
StringRef InputFile::getName() const {
|
2017-03-31 06:47:07 +02:00
|
|
|
return Mods[0].getModuleIdentifier();
|
2016-12-14 02:17:59 +01:00
|
|
|
}
|
|
|
|
|
[ThinLTO] Fix ThinLTOCodegenerator to export llvm.used symbols
Summary:
Reapply r357931 with fixes to ThinLTO testcases and llvm-lto tool.
ThinLTOCodeGenerator currently does not preserve llvm.used symbols and
it can internalize them. In order to pass the necessary information to the
legacy ThinLTOCodeGenerator, the input to the code generator is
rewritten to be based on lto::InputFile.
Now ThinLTO using the legacy LTO API will requires data layout in
Module.
"internalize" thinlto action in llvm-lto is updated to run both
"promote" and "internalize" with the same configuration as
ThinLTOCodeGenerator. The old "promote" + "internalize" option does not
produce the same output as ThinLTOCodeGenerator.
This fixes: PR41236
rdar://problem/49293439
Reviewers: tejohnson, pcc, kromanova, dexonsmith
Reviewed By: tejohnson
Subscribers: ormris, bd1976llvm, mehdi_amini, inglorion, eraman, hiraditya, jkorous, dexonsmith, arphaman, dang, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D60421
llvm-svn: 358601
2019-04-17 19:38:09 +02:00
|
|
|
BitcodeModule &InputFile::getSingleBitcodeModule() {
|
|
|
|
assert(Mods.size() == 1 && "Expect only one bitcode module");
|
|
|
|
return Mods[0];
|
|
|
|
}
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
|
2020-01-13 21:23:34 +01:00
|
|
|
const Config &Conf)
|
2016-08-11 16:58:12 +02:00
|
|
|
: ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
|
2019-08-15 17:54:37 +02:00
|
|
|
Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
|
|
|
|
Mover(std::make_unique<IRMover>(*CombinedModule)) {}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-01-22 14:35:40 +01:00
|
|
|
LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
|
2018-06-07 00:22:01 +02:00
|
|
|
: Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
|
2016-08-11 16:58:12 +02:00
|
|
|
if (!Backend)
|
2020-03-27 15:20:39 +01:00
|
|
|
this->Backend =
|
|
|
|
createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
LTO::LTO(Config Conf, ThinBackend Backend,
|
|
|
|
unsigned ParallelCodeGenParallelismLevel)
|
|
|
|
: Conf(std::move(Conf)),
|
|
|
|
RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
|
2016-08-19 07:56:37 +02:00
|
|
|
ThinLTO(std::move(Backend)) {}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
// Requires a destructor for MapVector<BitcodeModule>.
|
|
|
|
LTO::~LTO() = default;
|
|
|
|
|
2017-06-15 19:26:13 +02:00
|
|
|
// Add the symbols in the given module to the GlobalResolutions map, and resolve
|
|
|
|
// their partitions.
|
|
|
|
void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
|
|
|
|
ArrayRef<SymbolResolution> Res,
|
|
|
|
unsigned Partition, bool InSummary) {
|
|
|
|
auto *ResI = Res.begin();
|
|
|
|
auto *ResE = Res.end();
|
2017-06-15 19:41:32 +02:00
|
|
|
(void)ResE;
|
2017-06-15 19:26:13 +02:00
|
|
|
for (const InputFile::Symbol &Sym : Syms) {
|
|
|
|
assert(ResI != ResE);
|
|
|
|
SymbolResolution Res = *ResI++;
|
|
|
|
|
2018-07-24 00:33:57 +02:00
|
|
|
StringRef Name = Sym.getName();
|
|
|
|
Triple TT(RegularLTO.CombinedModule->getTargetTriple());
|
|
|
|
// Strip the __imp_ prefix from COFF dllimport symbols (similar to the
|
|
|
|
// way they are handled by lld), otherwise we can end up with two
|
|
|
|
// global resolutions (one with and one for a copy of the symbol without).
|
|
|
|
if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
|
|
|
|
Name = Name.substr(strlen("__imp_"));
|
|
|
|
auto &GlobalRes = GlobalResolutions[Name];
|
2017-06-15 19:26:13 +02:00
|
|
|
GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
|
2017-12-15 10:18:21 +01:00
|
|
|
if (Res.Prevailing) {
|
2018-01-25 18:23:27 +01:00
|
|
|
assert(!GlobalRes.Prevailing &&
|
2017-12-15 17:27:33 +01:00
|
|
|
"Multiple prevailing defs are not allowed");
|
2018-01-25 18:23:27 +01:00
|
|
|
GlobalRes.Prevailing = true;
|
2020-01-28 20:23:46 +01:00
|
|
|
GlobalRes.IRName = std::string(Sym.getIRName());
|
2018-01-29 09:03:30 +01:00
|
|
|
} else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
|
|
|
|
// Sometimes it can be two copies of symbol in a module and prevailing
|
|
|
|
// symbol can have no IR name. That might happen if symbol is defined in
|
|
|
|
// module level inline asm block. In case we have multiple modules with
|
|
|
|
// the same symbol we want to use IR name of the prevailing symbol.
|
|
|
|
// Otherwise, if we haven't seen a prevailing symbol, set the name so that
|
|
|
|
// we can later use it to check if there is any prevailing copy in IR.
|
2020-01-28 20:23:46 +01:00
|
|
|
GlobalRes.IRName = std::string(Sym.getIRName());
|
2017-12-15 10:18:21 +01:00
|
|
|
}
|
2017-06-15 19:26:13 +02:00
|
|
|
|
|
|
|
// Set the partition to external if we know it is re-defined by the linker
|
|
|
|
// with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
|
2021-03-04 01:22:30 +01:00
|
|
|
// regular object, is referenced from llvm.compiler.used/llvm.used, or was
|
|
|
|
// already recorded as being referenced from a different partition.
|
2017-06-15 19:26:13 +02:00
|
|
|
if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
|
|
|
|
(GlobalRes.Partition != GlobalResolution::Unknown &&
|
|
|
|
GlobalRes.Partition != Partition)) {
|
|
|
|
GlobalRes.Partition = GlobalResolution::External;
|
|
|
|
} else
|
|
|
|
// First recorded reference, save the current partition.
|
|
|
|
GlobalRes.Partition = Partition;
|
|
|
|
|
|
|
|
// Flag as visible outside of summary if visible from a regular object or
|
|
|
|
// from a module that does not have a summary.
|
|
|
|
GlobalRes.VisibleOutsideSummary |=
|
|
|
|
(Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
|
2020-12-31 00:56:53 +01:00
|
|
|
|
|
|
|
GlobalRes.ExportDynamic |= Res.ExportDynamic;
|
2017-06-15 19:26:13 +02:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2016-08-26 22:19:35 +02:00
|
|
|
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
|
|
|
|
ArrayRef<SymbolResolution> Res) {
|
2016-12-14 02:17:59 +01:00
|
|
|
StringRef Path = Input->getName();
|
2016-08-26 22:19:35 +02:00
|
|
|
OS << Path << '\n';
|
2016-08-11 16:58:12 +02:00
|
|
|
auto ResI = Res.begin();
|
|
|
|
for (const InputFile::Symbol &Sym : Input->symbols()) {
|
|
|
|
assert(ResI != Res.end());
|
|
|
|
SymbolResolution Res = *ResI++;
|
|
|
|
|
2016-08-26 22:19:35 +02:00
|
|
|
OS << "-r=" << Path << ',' << Sym.getName() << ',';
|
2016-08-11 16:58:12 +02:00
|
|
|
if (Res.Prevailing)
|
2016-08-26 22:19:35 +02:00
|
|
|
OS << 'p';
|
2016-08-11 16:58:12 +02:00
|
|
|
if (Res.FinalDefinitionInLinkageUnit)
|
2016-08-26 22:19:35 +02:00
|
|
|
OS << 'l';
|
2016-08-11 16:58:12 +02:00
|
|
|
if (Res.VisibleToRegularObj)
|
2016-08-26 22:19:35 +02:00
|
|
|
OS << 'x';
|
2017-06-05 18:24:25 +02:00
|
|
|
if (Res.LinkerRedefined)
|
|
|
|
OS << 'r';
|
2016-08-26 22:19:35 +02:00
|
|
|
OS << '\n';
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
2017-01-20 00:10:14 +01:00
|
|
|
OS.flush();
|
2016-08-11 16:58:12 +02:00
|
|
|
assert(ResI == Res.end());
|
|
|
|
}
|
|
|
|
|
|
|
|
Error LTO::add(std::unique_ptr<InputFile> Input,
|
|
|
|
ArrayRef<SymbolResolution> Res) {
|
|
|
|
assert(!CalledGetMaxTasks);
|
|
|
|
|
|
|
|
if (Conf.ResolutionFile)
|
2016-08-26 22:19:35 +02:00
|
|
|
writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2021-01-27 19:43:51 +01:00
|
|
|
if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
|
2017-12-16 03:10:00 +01:00
|
|
|
RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
|
2021-01-27 19:43:51 +01:00
|
|
|
if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
|
|
|
|
Conf.VisibilityScheme = Config::ELF;
|
|
|
|
}
|
2017-12-16 03:10:00 +01:00
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
const SymbolResolution *ResI = Res.begin();
|
2017-03-31 06:47:07 +02:00
|
|
|
for (unsigned I = 0; I != Input->Mods.size(); ++I)
|
|
|
|
if (Error Err = addModule(*Input, I, ResI, Res.end()))
|
2016-12-14 02:17:59 +01:00
|
|
|
return Err;
|
|
|
|
|
|
|
|
assert(ResI == Res.end());
|
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
2017-03-31 06:47:07 +02:00
|
|
|
Error LTO::addModule(InputFile &Input, unsigned ModI,
|
2016-12-14 02:17:59 +01:00
|
|
|
const SymbolResolution *&ResI,
|
|
|
|
const SymbolResolution *ResE) {
|
2017-06-15 19:26:13 +02:00
|
|
|
Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
|
|
|
|
if (!LTOInfo)
|
|
|
|
return LTOInfo.takeError();
|
2016-08-11 16:58:12 +02:00
|
|
|
|
[LTO] Record whether LTOUnit splitting is enabled in index
Summary:
Records in the module summary index whether the bitcode was compiled
with the option necessary to enable splitting the LTO unit
(e.g. -fsanitize=cfi, -fwhole-program-vtables, or -fsplit-lto-unit).
The information is passed down to the ModuleSummaryIndex builder via a
new module flag "EnableSplitLTOUnit", which is propagated onto a flag
on the summary index.
This is then used during the LTO link to check whether all linked
summaries were built with the same value of this flag. If not, an error
is issued when we detect a situation requiring whole program visibility
of the class hierarchy. This is the case when both of the following
conditions are met:
1) We are performing LowerTypeTests or Whole Program Devirtualization.
2) There are type tests or type checked loads in the code.
Note I have also changed the ThinLTOBitcodeWriter to also gate the
module splitting on the value of this flag.
Reviewers: pcc
Subscribers: ormris, mehdi_amini, Prazek, inglorion, eraman, steven_wu, dexonsmith, arphaman, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D53890
llvm-svn: 350948
2019-01-11 19:31:57 +01:00
|
|
|
if (EnableSplitLTOUnit.hasValue()) {
|
|
|
|
// If only some modules were split, flag this in the index so that
|
|
|
|
// we can skip or error on optimizations that need consistently split
|
|
|
|
// modules (whole program devirt and lower type tests).
|
|
|
|
if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit)
|
|
|
|
ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
|
|
|
|
} else
|
|
|
|
EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
|
|
|
|
|
2017-06-15 19:26:13 +02:00
|
|
|
BitcodeModule BM = Input.Mods[ModI];
|
2017-03-31 06:47:07 +02:00
|
|
|
auto ModSyms = Input.module_symbols(ModI);
|
2017-06-15 19:26:13 +02:00
|
|
|
addModuleToGlobalRes(ModSyms, {ResI, ResE},
|
|
|
|
LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
|
|
|
|
LTOInfo->HasSummary);
|
|
|
|
|
|
|
|
if (LTOInfo->IsThinLTO)
|
|
|
|
return addThinLTO(BM, ModSyms, ResI, ResE);
|
|
|
|
|
[LTO] Suppress emission of empty combined module by default
Summary:
That unless the user requested an output object (--lto-obj-path), the an
unused empty combined module is not emitted.
This changed is helpful for some target (ex. RISCV-V) which encoded the
ABI info in IR module flags (target-abi). Empty unused module has no ABI
info so the linker would get the linking error during merging
incompatible ABIs.
Reviewers: tejohnson, espindola, MaskRay
Subscribers: emaste, inglorion, arichardson, hiraditya, simoncook, MaskRay, steven_wu, dexonsmith, PkmX, dang, lenary, s.egerton, luismarques, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D78988
2020-04-28 05:04:36 +02:00
|
|
|
RegularLTO.EmptyCombinedModule = false;
|
2017-06-15 19:26:13 +02:00
|
|
|
Expected<RegularLTOState::AddedModule> ModOrErr =
|
|
|
|
addRegularLTO(BM, ModSyms, ResI, ResE);
|
|
|
|
if (!ModOrErr)
|
|
|
|
return ModOrErr.takeError();
|
|
|
|
|
|
|
|
if (!LTOInfo->HasSummary)
|
|
|
|
return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
|
|
|
|
|
|
|
|
// Regular LTO module summaries are added to a dummy module that represents
|
|
|
|
// the combined regular LTO module.
|
|
|
|
if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
|
|
|
|
return Err;
|
|
|
|
RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
|
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2017-06-30 16:03:24 +02:00
|
|
|
// Checks whether the given global value is in a non-prevailing comdat
|
|
|
|
// (comdat containing values the linker indicated were not prevailing,
|
|
|
|
// which we then dropped to available_externally), and if so, removes
|
|
|
|
// it from the comdat. This is called for all global values to ensure the
|
|
|
|
// comdat is empty rather than leaving an incomplete comdat. It is needed for
|
|
|
|
// regular LTO modules, in case we are in a mixed-LTO mode (both regular
|
|
|
|
// and thin LTO modules) compilation. Since the regular LTO module will be
|
|
|
|
// linked first in the final native link, we want to make sure the linker
|
|
|
|
// doesn't select any of these incomplete comdats that would be left
|
|
|
|
// in the regular LTO module without this cleanup.
|
|
|
|
static void
|
|
|
|
handleNonPrevailingComdat(GlobalValue &GV,
|
|
|
|
std::set<const Comdat *> &NonPrevailingComdats) {
|
|
|
|
Comdat *C = GV.getComdat();
|
|
|
|
if (!C)
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (!NonPrevailingComdats.count(C))
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Additionally need to drop externally visible global values from the comdat
|
|
|
|
// to available_externally, so that there aren't multiply defined linker
|
|
|
|
// errors.
|
|
|
|
if (!GV.hasLocalLinkage())
|
|
|
|
GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
|
|
|
|
|
|
|
|
if (auto GO = dyn_cast<GlobalObject>(&GV))
|
|
|
|
GO->setComdat(nullptr);
|
|
|
|
}
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
// Add a regular LTO object to the link.
|
2017-06-15 19:26:13 +02:00
|
|
|
// The resulting module needs to be linked into the combined LTO module with
|
|
|
|
// linkRegularLTO.
|
|
|
|
Expected<LTO::RegularLTOState::AddedModule>
|
|
|
|
LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
|
|
|
|
const SymbolResolution *&ResI,
|
|
|
|
const SymbolResolution *ResE) {
|
|
|
|
RegularLTOState::AddedModule Mod;
|
2016-12-13 20:43:49 +01:00
|
|
|
Expected<std::unique_ptr<Module>> MOrErr =
|
2016-12-16 22:25:01 +01:00
|
|
|
BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
|
|
|
|
/*IsImporting*/ false);
|
2016-12-13 20:43:49 +01:00
|
|
|
if (!MOrErr)
|
|
|
|
return MOrErr.takeError();
|
|
|
|
Module &M = **MOrErr;
|
2017-06-15 19:26:13 +02:00
|
|
|
Mod.M = std::move(*MOrErr);
|
|
|
|
|
2016-11-09 18:49:19 +01:00
|
|
|
if (Error Err = M.materializeMetadata())
|
2020-02-10 16:06:45 +01:00
|
|
|
return std::move(Err);
|
2016-08-11 16:58:12 +02:00
|
|
|
UpgradeDebugInfo(M);
|
|
|
|
|
2016-12-13 20:43:49 +01:00
|
|
|
ModuleSymbolTable SymTab;
|
|
|
|
SymTab.addModule(&M);
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
for (GlobalVariable &GV : M.globals())
|
|
|
|
if (GV.hasAppendingLinkage())
|
2017-06-15 19:26:13 +02:00
|
|
|
Mod.Keep.push_back(&GV);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2017-02-02 06:22:42 +01:00
|
|
|
DenseSet<GlobalObject *> AliasedGlobals;
|
|
|
|
for (auto &GA : M.aliases())
|
|
|
|
if (GlobalObject *GO = GA.getBaseObject())
|
|
|
|
AliasedGlobals.insert(GO);
|
|
|
|
|
2017-03-31 06:47:07 +02:00
|
|
|
// In this function we need IR GlobalValues matching the symbols in Syms
|
|
|
|
// (which is not backed by a module), so we need to enumerate them in the same
|
|
|
|
// order. The symbol enumeration order of a ModuleSymbolTable intentionally
|
|
|
|
// matches the order of an irsymtab, but when we read the irsymtab in
|
|
|
|
// InputFile::create we omit some symbols that are irrelevant to LTO. The
|
|
|
|
// Skip() function skips the same symbols from the module as InputFile does
|
|
|
|
// from the symbol table.
|
|
|
|
auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
|
|
|
|
auto Skip = [&]() {
|
|
|
|
while (MsymI != MsymE) {
|
|
|
|
auto Flags = SymTab.getSymbolFlags(*MsymI);
|
|
|
|
if ((Flags & object::BasicSymbolRef::SF_Global) &&
|
|
|
|
!(Flags & object::BasicSymbolRef::SF_FormatSpecific))
|
|
|
|
return;
|
|
|
|
++MsymI;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Skip();
|
|
|
|
|
2017-06-30 16:03:24 +02:00
|
|
|
std::set<const Comdat *> NonPrevailingComdats;
|
2021-03-18 23:32:29 +01:00
|
|
|
SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
|
2017-03-31 06:47:07 +02:00
|
|
|
for (const InputFile::Symbol &Sym : Syms) {
|
2016-12-14 02:17:59 +01:00
|
|
|
assert(ResI != ResE);
|
2016-08-11 16:58:12 +02:00
|
|
|
SymbolResolution Res = *ResI++;
|
|
|
|
|
2017-03-31 06:47:07 +02:00
|
|
|
assert(MsymI != MsymE);
|
|
|
|
ModuleSymbolTable::Symbol Msym = *MsymI++;
|
|
|
|
Skip();
|
|
|
|
|
|
|
|
if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
|
2017-02-02 06:12:15 +01:00
|
|
|
if (Res.Prevailing) {
|
2017-03-29 00:31:35 +02:00
|
|
|
if (Sym.isUndefined())
|
2017-02-02 06:12:15 +01:00
|
|
|
continue;
|
2017-06-15 19:26:13 +02:00
|
|
|
Mod.Keep.push_back(GV);
|
2017-06-05 18:24:25 +02:00
|
|
|
// For symbols re-defined with linker -wrap and -defsym options,
|
|
|
|
// set the linkage to weak to inhibit IPO. The linkage will be
|
|
|
|
// restored by the linker.
|
|
|
|
if (Res.LinkerRedefined)
|
|
|
|
GV->setLinkage(GlobalValue::WeakAnyLinkage);
|
|
|
|
|
2017-05-26 23:56:14 +02:00
|
|
|
GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
|
|
|
|
if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
|
|
|
|
GV->setLinkage(GlobalValue::getWeakLinkage(
|
|
|
|
GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
|
2017-02-02 06:22:42 +01:00
|
|
|
} else if (isa<GlobalObject>(GV) &&
|
|
|
|
(GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
|
|
|
|
GV->hasAvailableExternallyLinkage()) &&
|
|
|
|
!AliasedGlobals.count(cast<GlobalObject>(GV))) {
|
2017-06-15 19:26:13 +02:00
|
|
|
// Any of the above three types of linkage indicates that the
|
2017-02-02 06:22:42 +01:00
|
|
|
// chosen prevailing symbol will have the same semantics as this copy of
|
2017-06-15 19:26:13 +02:00
|
|
|
// the symbol, so we may be able to link it with available_externally
|
|
|
|
// linkage. We will decide later whether to do that when we link this
|
|
|
|
// module (in linkRegularLTO), based on whether it is undefined.
|
|
|
|
Mod.Keep.push_back(GV);
|
|
|
|
GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
|
2017-06-30 16:03:24 +02:00
|
|
|
if (GV->hasComdat())
|
|
|
|
NonPrevailingComdats.insert(GV->getComdat());
|
2017-06-15 19:26:13 +02:00
|
|
|
cast<GlobalObject>(GV)->setComdat(nullptr);
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
2017-11-04 18:04:39 +01:00
|
|
|
|
|
|
|
// Set the 'local' flag based on the linker resolution for this symbol.
|
[ThinLTO] Remove dllimport attribute from locally defined symbols
Summary:
The LTO/ThinLTO driver currently creates invalid bitcode by setting
symbols marked dllimport as dso_local. The compiler often has access
to the definition (often dllexport) and the declaration (often
dllimport) of an object at link-time, leading to a conflicting
declaration. This patch resolves the inconsistency by removing the
dllimport attribute.
Reviewers: tejohnson, pcc, rnk, echristo
Reviewed By: rnk
Subscribers: dmikulin, wristow, mehdi_amini, inglorion, eraman, steven_wu, dexonsmith, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D55627
llvm-svn: 349667
2018-12-19 20:07:45 +01:00
|
|
|
if (Res.FinalDefinitionInLinkageUnit) {
|
2018-01-24 20:11:24 +01:00
|
|
|
GV->setDSOLocal(true);
|
[ThinLTO] Remove dllimport attribute from locally defined symbols
Summary:
The LTO/ThinLTO driver currently creates invalid bitcode by setting
symbols marked dllimport as dso_local. The compiler often has access
to the definition (often dllexport) and the declaration (often
dllimport) of an object at link-time, leading to a conflicting
declaration. This patch resolves the inconsistency by removing the
dllimport attribute.
Reviewers: tejohnson, pcc, rnk, echristo
Reviewed By: rnk
Subscribers: dmikulin, wristow, mehdi_amini, inglorion, eraman, steven_wu, dexonsmith, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D55627
llvm-svn: 349667
2018-12-19 20:07:45 +01:00
|
|
|
if (GV->hasDLLImportStorageClass())
|
|
|
|
GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
|
|
|
|
DefaultStorageClass);
|
|
|
|
}
|
2021-03-18 23:32:29 +01:00
|
|
|
} else if (auto *AS = Msym.dyn_cast<ModuleSymbolTable::AsmSymbol *>()) {
|
|
|
|
// Collect non-prevailing symbols.
|
|
|
|
if (!Res.Prevailing)
|
|
|
|
NonPrevailingAsmSymbols.insert(AS->first);
|
|
|
|
} else {
|
|
|
|
llvm_unreachable("unknown symbol type");
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
2021-03-18 23:32:29 +01:00
|
|
|
|
2016-09-14 23:05:04 +02:00
|
|
|
// Common resolution: collect the maximum size/alignment over all commons.
|
|
|
|
// We also record if we see an instance of a common as prevailing, so that
|
|
|
|
// if none is prevailing we can ignore it later.
|
2017-03-29 00:31:35 +02:00
|
|
|
if (Sym.isCommon()) {
|
2016-12-01 03:51:12 +01:00
|
|
|
// FIXME: We should figure out what to do about commons defined by asm.
|
|
|
|
// For now they aren't reported correctly by ModuleSymbolTable.
|
2020-01-28 20:23:46 +01:00
|
|
|
auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
|
2016-08-22 08:25:46 +02:00
|
|
|
CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
|
2020-05-23 06:45:09 +02:00
|
|
|
MaybeAlign SymAlign(Sym.getCommonAlignment());
|
|
|
|
if (SymAlign)
|
|
|
|
CommonRes.Align = max(*SymAlign, CommonRes.Align);
|
2016-09-14 23:05:04 +02:00
|
|
|
CommonRes.Prevailing |= Res.Prevailing;
|
2016-08-22 08:25:46 +02:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
2021-03-18 23:32:29 +01:00
|
|
|
|
2017-06-30 16:03:24 +02:00
|
|
|
if (!M.getComdatSymbolTable().empty())
|
|
|
|
for (GlobalValue &GV : M.global_values())
|
|
|
|
handleNonPrevailingComdat(GV, NonPrevailingComdats);
|
2021-03-18 23:32:29 +01:00
|
|
|
|
|
|
|
// Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
|
|
|
|
// block.
|
|
|
|
if (!M.getModuleInlineAsm().empty()) {
|
|
|
|
std::string NewIA = ".lto_discard";
|
|
|
|
if (!NonPrevailingAsmSymbols.empty()) {
|
|
|
|
// Don't dicard a symbol if there is a live .symver for it.
|
|
|
|
ModuleSymbolTable::CollectAsmSymvers(
|
|
|
|
M, [&](StringRef Name, StringRef Alias) {
|
|
|
|
if (!NonPrevailingAsmSymbols.count(Alias))
|
|
|
|
NonPrevailingAsmSymbols.erase(Name);
|
|
|
|
});
|
|
|
|
NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
|
|
|
|
}
|
|
|
|
NewIA += "\n";
|
|
|
|
M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
|
|
|
|
}
|
|
|
|
|
2017-03-31 06:47:07 +02:00
|
|
|
assert(MsymI == MsymE);
|
2020-02-10 16:06:45 +01:00
|
|
|
return std::move(Mod);
|
2017-06-15 19:26:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
|
|
|
|
bool LivenessFromIndex) {
|
|
|
|
std::vector<GlobalValue *> Keep;
|
|
|
|
for (GlobalValue *GV : Mod.Keep) {
|
2020-01-29 02:13:12 +01:00
|
|
|
if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
|
|
|
|
if (Function *F = dyn_cast<Function>(GV)) {
|
2020-08-25 19:42:54 +02:00
|
|
|
OptimizationRemarkEmitter ORE(F, nullptr);
|
2020-01-29 02:13:12 +01:00
|
|
|
ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
|
|
|
|
<< ore::NV("Function", F)
|
|
|
|
<< " not added to the combined module ");
|
|
|
|
}
|
2017-06-15 19:26:13 +02:00
|
|
|
continue;
|
2020-01-29 02:13:12 +01:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2017-06-15 19:26:13 +02:00
|
|
|
if (!GV->hasAvailableExternallyLinkage()) {
|
|
|
|
Keep.push_back(GV);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only link available_externally definitions if we don't already have a
|
|
|
|
// definition.
|
|
|
|
GlobalValue *CombinedGV =
|
|
|
|
RegularLTO.CombinedModule->getNamedValue(GV->getName());
|
|
|
|
if (CombinedGV && !CombinedGV->isDeclaration())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
Keep.push_back(GV);
|
|
|
|
}
|
|
|
|
|
|
|
|
return RegularLTO.Mover->move(std::move(Mod.M), Keep,
|
2016-10-12 20:39:29 +02:00
|
|
|
[](GlobalValue &, IRMover::ValueAdder) {},
|
2016-12-12 17:09:30 +01:00
|
|
|
/* IsPerformingImport */ false);
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2017-06-15 19:26:13 +02:00
|
|
|
// Add a ThinLTO module to the link.
|
|
|
|
Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
|
2016-12-14 02:17:59 +01:00
|
|
|
const SymbolResolution *&ResI,
|
|
|
|
const SymbolResolution *ResE) {
|
2017-05-02 00:04:36 +02:00
|
|
|
if (Error Err =
|
2017-06-15 19:26:13 +02:00
|
|
|
BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
|
|
|
|
ThinLTO.ModuleMap.size()))
|
2017-05-02 00:04:36 +02:00
|
|
|
return Err;
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
for (const InputFile::Symbol &Sym : Syms) {
|
|
|
|
assert(ResI != ResE);
|
2016-08-11 16:58:12 +02:00
|
|
|
SymbolResolution Res = *ResI++;
|
|
|
|
|
2017-11-04 18:04:39 +01:00
|
|
|
if (!Sym.getIRName().empty()) {
|
|
|
|
auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
|
|
|
|
Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
|
|
|
|
if (Res.Prevailing) {
|
2017-03-31 06:47:07 +02:00
|
|
|
ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
|
2017-07-06 21:58:26 +02:00
|
|
|
|
|
|
|
// For linker redefined symbols (via --wrap or --defsym) we want to
|
|
|
|
// switch the linkage to `weak` to prevent IPOs from happening.
|
|
|
|
// Find the summary in the module for this very GV and record the new
|
|
|
|
// linkage so that we can switch it when we import the GV.
|
|
|
|
if (Res.LinkerRedefined)
|
|
|
|
if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
|
|
|
|
GUID, BM.getModuleIdentifier()))
|
|
|
|
S->setLinkage(GlobalValue::WeakAnyLinkage);
|
2017-03-31 06:47:07 +02:00
|
|
|
}
|
2017-11-04 18:04:39 +01:00
|
|
|
|
|
|
|
// If the linker resolved the symbol to a local definition then mark it
|
|
|
|
// as local in the summary for the module we are adding.
|
|
|
|
if (Res.FinalDefinitionInLinkageUnit) {
|
|
|
|
if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
|
|
|
|
GUID, BM.getModuleIdentifier())) {
|
|
|
|
S->setDSOLocal(true);
|
|
|
|
}
|
|
|
|
}
|
2017-03-31 06:47:07 +02:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
|
|
|
|
return make_error<StringError>(
|
|
|
|
"Expected at most one ThinLTO module per bitcode file",
|
|
|
|
inconvertibleErrorCode());
|
|
|
|
|
2020-05-21 22:19:44 +02:00
|
|
|
if (!Conf.ThinLTOModulesToCompile.empty()) {
|
|
|
|
if (!ThinLTO.ModulesToCompile)
|
|
|
|
ThinLTO.ModulesToCompile = ModuleMapType();
|
|
|
|
// This is a fuzzy name matching where only modules with name containing the
|
|
|
|
// specified switch values are going to be compiled.
|
|
|
|
for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
|
|
|
|
if (BM.getModuleIdentifier().contains(Name)) {
|
|
|
|
ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
|
|
|
|
llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
|
|
|
|
<< " to compile\n";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2016-08-11 22:38:39 +02:00
|
|
|
unsigned LTO::getMaxTasks() const {
|
2016-08-11 16:58:12 +02:00
|
|
|
CalledGetMaxTasks = true;
|
2020-05-21 22:19:44 +02:00
|
|
|
auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
|
|
|
|
: ThinLTO.ModuleMap.size();
|
|
|
|
return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2019-02-14 22:22:50 +01:00
|
|
|
// If only some of the modules were split, we cannot correctly handle
|
|
|
|
// code that contains type tests or type checked loads.
|
|
|
|
Error LTO::checkPartiallySplit() {
|
|
|
|
if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
|
|
|
|
return Error::success();
|
|
|
|
|
|
|
|
Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
|
|
|
|
Intrinsic::getName(Intrinsic::type_test));
|
|
|
|
Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
|
|
|
|
Intrinsic::getName(Intrinsic::type_checked_load));
|
|
|
|
|
|
|
|
// First check if there are type tests / type checked loads in the
|
|
|
|
// merged regular LTO module IR.
|
|
|
|
if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
|
|
|
|
(TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
|
|
|
|
return make_error<StringError>(
|
|
|
|
"inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
|
|
|
|
inconvertibleErrorCode());
|
|
|
|
|
|
|
|
// Otherwise check if there are any recorded in the combined summary from the
|
|
|
|
// ThinLTO modules.
|
|
|
|
for (auto &P : ThinLTO.CombinedIndex) {
|
|
|
|
for (auto &S : P.second.SummaryList) {
|
|
|
|
auto *FS = dyn_cast<FunctionSummary>(S.get());
|
|
|
|
if (!FS)
|
|
|
|
continue;
|
|
|
|
if (!FS->type_test_assume_vcalls().empty() ||
|
|
|
|
!FS->type_checked_load_vcalls().empty() ||
|
|
|
|
!FS->type_test_assume_const_vcalls().empty() ||
|
|
|
|
!FS->type_checked_load_const_vcalls().empty() ||
|
|
|
|
!FS->type_tests().empty())
|
|
|
|
return make_error<StringError>(
|
|
|
|
"inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
|
|
|
|
inconvertibleErrorCode());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
2016-09-23 23:33:43 +02:00
|
|
|
Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
|
2017-06-02 20:24:17 +02:00
|
|
|
// Compute "dead" symbols, we don't want to import/export these!
|
|
|
|
DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
|
2018-01-29 09:03:30 +01:00
|
|
|
DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
|
|
|
|
for (auto &Res : GlobalResolutions) {
|
|
|
|
// Normally resolution have IR name of symbol. We can do nothing here
|
|
|
|
// otherwise. See comments in GlobalResolution struct for more details.
|
|
|
|
if (Res.second.IRName.empty())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
GlobalValue::GUID GUID = GlobalValue::getGUID(
|
|
|
|
GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
|
|
|
|
|
2018-01-25 18:23:27 +01:00
|
|
|
if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
|
2019-09-11 09:38:21 +02:00
|
|
|
GUIDPreservedSymbols.insert(GUID);
|
2017-06-02 20:24:17 +02:00
|
|
|
|
2020-12-31 00:56:53 +01:00
|
|
|
if (Res.second.ExportDynamic)
|
|
|
|
DynamicExportSymbols.insert(GUID);
|
|
|
|
|
2018-01-29 09:03:30 +01:00
|
|
|
GUIDPrevailingResolutions[GUID] =
|
|
|
|
Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto isPrevailing = [&](GlobalValue::GUID G) {
|
|
|
|
auto It = GUIDPrevailingResolutions.find(G);
|
|
|
|
if (It == GUIDPrevailingResolutions.end())
|
|
|
|
return PrevailingType::Unknown;
|
|
|
|
return It->second;
|
|
|
|
};
|
2018-11-16 08:08:00 +01:00
|
|
|
computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
|
|
|
|
isPrevailing, Conf.OptLevel > 0);
|
2017-06-02 20:24:17 +02:00
|
|
|
|
2018-04-20 12:18:36 +02:00
|
|
|
// Setup output file to emit statistics.
|
2019-04-19 14:36:41 +02:00
|
|
|
auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
|
|
|
|
if (!StatsFileOrErr)
|
|
|
|
return StatsFileOrErr.takeError();
|
|
|
|
std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
|
2018-04-20 12:18:36 +02:00
|
|
|
|
|
|
|
Error Result = runRegularLTO(AddStream);
|
|
|
|
if (!Result)
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
|
2018-04-20 12:18:36 +02:00
|
|
|
|
|
|
|
if (StatsFile)
|
|
|
|
PrintStatisticsJSON(StatsFile->os());
|
|
|
|
|
|
|
|
return Result;
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2016-09-23 23:33:43 +02:00
|
|
|
Error LTO::runRegularLTO(AddStreamFn AddStream) {
|
2020-01-29 02:13:12 +01:00
|
|
|
// Setup optimization remarks.
|
2019-10-28 22:53:31 +01:00
|
|
|
auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
|
2020-01-29 02:13:12 +01:00
|
|
|
RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
|
2020-11-17 19:37:59 +01:00
|
|
|
Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
|
|
|
|
Conf.RemarksHotnessThreshold);
|
2020-01-29 02:13:12 +01:00
|
|
|
if (!DiagFileOrErr)
|
|
|
|
return DiagFileOrErr.takeError();
|
|
|
|
|
|
|
|
// Finalize linking of regular LTO modules containing summaries now that
|
|
|
|
// we have computed liveness information.
|
|
|
|
for (auto &M : RegularLTO.ModsWithSummaries)
|
|
|
|
if (Error Err = linkRegularLTO(std::move(M),
|
|
|
|
/*LivenessFromIndex=*/true))
|
|
|
|
return Err;
|
|
|
|
|
|
|
|
// Ensure we don't have inconsistently split LTO units with type tests.
|
|
|
|
// FIXME: this checks both LTO and ThinLTO. It happens to work as we take
|
|
|
|
// this path both cases but eventually this should be split into two and
|
|
|
|
// do the ThinLTO checks in `runThinLTO`.
|
|
|
|
if (Error Err = checkPartiallySplit())
|
|
|
|
return Err;
|
|
|
|
|
2016-08-22 08:25:46 +02:00
|
|
|
// Make sure commons have the right size/alignment: we kept the largest from
|
|
|
|
// all the prevailing when adding the inputs, and we apply it here.
|
2016-08-27 06:41:22 +02:00
|
|
|
const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
|
2016-08-22 08:25:46 +02:00
|
|
|
for (auto &I : RegularLTO.Commons) {
|
2016-09-14 23:05:04 +02:00
|
|
|
if (!I.second.Prevailing)
|
|
|
|
// Don't do anything if no instance of this common was prevailing.
|
|
|
|
continue;
|
2016-08-22 08:25:46 +02:00
|
|
|
GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
|
2016-08-27 06:41:22 +02:00
|
|
|
if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
|
2016-08-22 08:25:46 +02:00
|
|
|
// Don't create a new global if the type is already correct, just make
|
|
|
|
// sure the alignment is correct.
|
|
|
|
OldGV->setAlignment(I.second.Align);
|
|
|
|
continue;
|
|
|
|
}
|
2016-08-27 06:41:22 +02:00
|
|
|
ArrayType *Ty =
|
|
|
|
ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
|
2016-08-22 08:25:46 +02:00
|
|
|
auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
|
|
|
|
GlobalValue::CommonLinkage,
|
|
|
|
ConstantAggregateZero::get(Ty), "");
|
|
|
|
GV->setAlignment(I.second.Align);
|
|
|
|
if (OldGV) {
|
|
|
|
OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
|
|
|
|
GV->takeName(OldGV);
|
|
|
|
OldGV->eraseFromParent();
|
|
|
|
} else {
|
|
|
|
GV->setName(I.first);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-24 21:24:18 +01:00
|
|
|
// If allowed, upgrade public vcall visibility metadata to linkage unit
|
|
|
|
// visibility before whole program devirtualization in the optimizer.
|
|
|
|
updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
|
2020-12-31 00:56:53 +01:00
|
|
|
Conf.HasWholeProgramVisibility,
|
|
|
|
DynamicExportSymbols);
|
2020-01-24 21:24:18 +01:00
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
if (Conf.PreOptModuleHook &&
|
|
|
|
!Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-08-22 08:25:41 +02:00
|
|
|
if (!Conf.CodeGenOnly) {
|
|
|
|
for (const auto &R : GlobalResolutions) {
|
2018-01-29 09:03:30 +01:00
|
|
|
if (!R.second.isPrevailingIRSymbol())
|
2016-08-22 08:25:41 +02:00
|
|
|
continue;
|
|
|
|
if (R.second.Partition != 0 &&
|
|
|
|
R.second.Partition != GlobalResolution::External)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
GlobalValue *GV =
|
|
|
|
RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
|
|
|
|
// Ignore symbols defined in other partitions.
|
2018-07-27 07:40:29 +02:00
|
|
|
// Also skip declarations, which are not allowed to have internal linkage.
|
|
|
|
if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
|
2016-08-22 08:25:41 +02:00
|
|
|
continue;
|
|
|
|
GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
|
|
|
|
: GlobalValue::UnnamedAddr::None);
|
2018-11-05 16:49:46 +01:00
|
|
|
if (EnableLTOInternalization && R.second.Partition == 0)
|
2016-08-22 08:25:41 +02:00
|
|
|
GV->setLinkage(GlobalValue::InternalLinkage);
|
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
Reland: Dead Virtual Function Elimination
Remove dead virtual functions from vtables with
replaceNonMetadataUsesWith, so that CGProfile metadata gets cleaned up
correctly.
Original commit message:
Currently, it is hard for the compiler to remove unused C++ virtual
functions, because they are all referenced from vtables, which are referenced
by constructors. This means that if the constructor is called from any live
code, then we keep every virtual function in the final link, even if there
are no call sites which can use it.
This patch allows unused virtual functions to be removed during LTO (and
regular compilation in limited circumstances) by using type metadata to match
virtual function call sites to the vtable slots they might load from. This
information can then be used in the global dead code elimination pass instead
of the references from vtables to virtual functions, to more accurately
determine which functions are reachable.
To make this transformation safe, I have changed clang's code-generation to
always load virtual function pointers using the llvm.type.checked.load
intrinsic, instead of regular load instructions. I originally tried writing
this using clang's existing code-generation, which uses the llvm.type.test
and llvm.assume intrinsics after doing a normal load. However, it is possible
for optimisations to obscure the relationship between the GEP, load and
llvm.type.test, causing GlobalDCE to fail to find virtual function call
sites.
The existing linkage and visibility types don't accurately describe the scope
in which a virtual call could be made which uses a given vtable. This is
wider than the visibility of the type itself, because a virtual function call
could be made using a more-visible base class. I've added a new
!vcall_visibility metadata type to represent this, described in
TypeMetadata.rst. The internalization pass and libLTO have been updated to
change this metadata when linking is performed.
This doesn't currently work with ThinLTO, because it needs to see every call
to llvm.type.checked.load in the linkage unit. It might be possible to
extend this optimisation to be able to use the ThinLTO summary, as was done
for devirtualization, but until then that combination is rejected in the
clang driver.
To test this, I've written a fuzzer which generates random C++ programs with
complex class inheritance graphs, and virtual functions called through object
and function pointers of different types. The programs are spread across
multiple translation units and DSOs to test the different visibility
restrictions.
I've also tried doing bootstrap builds of LLVM to test this. This isn't
ideal, because only classes in anonymous namespaces can be optimised with
-fvisibility=default, and some parts of LLVM (plugins and bugpoint) do not
work correctly with -fvisibility=hidden. However, there are only 12 test
failures when building with -fvisibility=hidden (and an unmodified compiler),
and this change does not cause any new failures for either value of
-fvisibility.
On the 7 C++ sub-benchmarks of SPEC2006, this gives a geomean code-size
reduction of ~6%, over a baseline compiled with "-O2 -flto
-fvisibility=hidden -fwhole-program-vtables". The best cases are reductions
of ~14% in 450.soplex and 483.xalancbmk, and there are no code size
increases.
I've also run this on a set of 8 mbed-os examples compiled for Armv7M, which
show a geomean size reduction of ~3%, again with no size increases.
I had hoped that this would have no effect on performance, which would allow
it to awlays be enabled (when using -fwhole-program-vtables). However, the
changes in clang to use the llvm.type.checked.load intrinsic are causing ~1%
performance regression in the C++ parts of SPEC2006. It should be possible to
recover some of this perf loss by teaching optimisations about the
llvm.type.checked.load intrinsic, which would make it worth turning this on
by default (though it's still dependent on -fwhole-program-vtables).
Differential revision: https://reviews.llvm.org/D63932
llvm-svn: 375094
2019-10-17 11:58:57 +02:00
|
|
|
RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
|
|
|
|
|
2016-08-22 08:25:41 +02:00
|
|
|
if (Conf.PostInternalizeModuleHook &&
|
|
|
|
!Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
[LTO] Suppress emission of empty combined module by default
Summary:
That unless the user requested an output object (--lto-obj-path), the an
unused empty combined module is not emitted.
This changed is helpful for some target (ex. RISCV-V) which encoded the
ABI info in IR module flags (target-abi). Empty unused module has no ABI
info so the linker would get the linking error during merging
incompatible ABIs.
Reviewers: tejohnson, espindola, MaskRay
Subscribers: emaste, inglorion, arichardson, hiraditya, simoncook, MaskRay, steven_wu, dexonsmith, PkmX, dang, lenary, s.egerton, luismarques, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D78988
2020-04-28 05:04:36 +02:00
|
|
|
|
|
|
|
if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
|
2021-01-29 11:20:54 +01:00
|
|
|
if (Error Err =
|
|
|
|
backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
|
|
|
|
*RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
|
[LTO] Suppress emission of empty combined module by default
Summary:
That unless the user requested an output object (--lto-obj-path), the an
unused empty combined module is not emitted.
This changed is helpful for some target (ex. RISCV-V) which encoded the
ABI info in IR module flags (target-abi). Empty unused module has no ABI
info so the linker would get the linking error during merging
incompatible ABIs.
Reviewers: tejohnson, espindola, MaskRay
Subscribers: emaste, inglorion, arichardson, hiraditya, simoncook, MaskRay, steven_wu, dexonsmith, PkmX, dang, lenary, s.egerton, luismarques, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D78988
2020-04-28 05:04:36 +02:00
|
|
|
return Err;
|
|
|
|
}
|
2020-01-29 02:13:12 +01:00
|
|
|
|
|
|
|
return finalizeOptimizationRemarks(std::move(*DiagFileOrErr));
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
[LTO][Legacy] Add new C inferface to query libcall functions
Summary:
This is needed to implemented the same approach as lld (implemented in r338434)
for how to handling symbols that can be generated by LTO code generator
but not present in the symbol table for linker that uses legacy C APIs.
libLTO is in charge of providing the list of symbols. Linker is in
charge of implementing the eager loading from static libraries using
the list of symbols.
rdar://problem/52853974
Reviewers: tejohnson, bd1976llvm, deadalnix, espindola
Reviewed By: tejohnson
Subscribers: emaste, arichardson, hiraditya, MaskRay, dang, kledzik, mehdi_amini, inglorion, jkorous, dexonsmith, ributzka, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D67568
llvm-svn: 372021
2019-09-16 20:49:54 +02:00
|
|
|
static const char *libcallRoutineNames[] = {
|
|
|
|
#define HANDLE_LIBCALL(code, name) name,
|
|
|
|
#include "llvm/IR/RuntimeLibcalls.def"
|
|
|
|
#undef HANDLE_LIBCALL
|
|
|
|
};
|
|
|
|
|
|
|
|
ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
|
|
|
|
return makeArrayRef(libcallRoutineNames);
|
|
|
|
}
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
/// This class defines the interface to the ThinLTO backend.
|
|
|
|
class lto::ThinBackendProc {
|
|
|
|
protected:
|
2020-01-13 21:23:34 +01:00
|
|
|
const Config &Conf;
|
2016-08-11 16:58:12 +02:00
|
|
|
ModuleSummaryIndex &CombinedIndex;
|
2016-09-06 05:23:45 +02:00
|
|
|
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
public:
|
2020-01-13 21:23:34 +01:00
|
|
|
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
|
2016-09-06 05:23:45 +02:00
|
|
|
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
|
2016-08-19 08:10:03 +02:00
|
|
|
: Conf(Conf), CombinedIndex(CombinedIndex),
|
2016-08-11 16:58:12 +02:00
|
|
|
ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
|
|
|
|
|
|
|
|
virtual ~ThinBackendProc() {}
|
2016-08-23 23:30:12 +02:00
|
|
|
virtual Error start(
|
2016-12-14 02:17:59 +01:00
|
|
|
unsigned Task, BitcodeModule BM,
|
2016-08-23 23:30:12 +02:00
|
|
|
const FunctionImporter::ImportMapTy &ImportList,
|
|
|
|
const FunctionImporter::ExportSetTy &ExportList,
|
|
|
|
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
|
2016-12-14 02:17:59 +01:00
|
|
|
MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
|
2016-08-11 16:58:12 +02:00
|
|
|
virtual Error wait() = 0;
|
Re-land [ThinLTO] Re-order modules for optimal multi-threaded processing
This reverts 9b5b3050237db3642ed7ab1bdb3ffa2202511b99 and fixes the unwanted re-ordering when generating ThinLTO indexes.
The goal of this patch is to better balance thread utilization during ThinLTO in-process linking (in llvm-lto2 or in LLD). Before this patch, large modules would often be scheduled late during execution, taking a long time to complete, thus starving the thread pool.
We now sort modules in descending order, based on each module's bitcode size, so that larger modules are processed first. By doing so, smaller modules have a better chance to keep the thread pool active, and thus avoid starvation when the bitcode compilation is almost complete.
In our case (on dual Intel Xeon Gold 6140, Windows 10 version 2004, two-stage build), this saves 15 sec when linking `clang.exe` with LLD & -flto=thin, /opt:lldltojobs=all, no ThinLTO cache, -DLLVM_INTEGRATED_CRT_ALLOC=d:\git\rpmalloc.
Before patch: 100 sec
After patch: 85 sec
Inspired by the work done by David Callahan in D60495.
Differential Revision: https://reviews.llvm.org/D87966
2020-10-14 03:54:00 +02:00
|
|
|
virtual unsigned getThreadCount() = 0;
|
2016-08-11 16:58:12 +02:00
|
|
|
};
|
|
|
|
|
2016-11-19 21:44:26 +01:00
|
|
|
namespace {
|
2016-08-11 16:58:12 +02:00
|
|
|
class InProcessThinBackend : public ThinBackendProc {
|
|
|
|
ThreadPool BackendThreadPool;
|
2016-09-23 23:33:43 +02:00
|
|
|
AddStreamFn AddStream;
|
|
|
|
NativeObjectCache Cache;
|
2017-08-10 01:24:07 +02:00
|
|
|
std::set<GlobalValue::GUID> CfiFunctionDefs;
|
|
|
|
std::set<GlobalValue::GUID> CfiFunctionDecls;
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
Optional<Error> Err;
|
|
|
|
std::mutex ErrMu;
|
|
|
|
|
|
|
|
public:
|
2016-09-06 05:23:45 +02:00
|
|
|
InProcessThinBackend(
|
2020-01-13 21:23:34 +01:00
|
|
|
const Config &Conf, ModuleSummaryIndex &CombinedIndex,
|
2020-03-27 15:20:39 +01:00
|
|
|
ThreadPoolStrategy ThinLTOParallelism,
|
2016-09-06 05:23:45 +02:00
|
|
|
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
|
2016-09-23 23:33:43 +02:00
|
|
|
AddStreamFn AddStream, NativeObjectCache Cache)
|
2016-08-19 08:10:03 +02:00
|
|
|
: ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
|
2020-03-27 15:20:39 +01:00
|
|
|
BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
|
|
|
|
Cache(std::move(Cache)) {
|
2017-08-10 01:24:07 +02:00
|
|
|
for (auto &Name : CombinedIndex.cfiFunctionDefs())
|
|
|
|
CfiFunctionDefs.insert(
|
|
|
|
GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
|
|
|
|
for (auto &Name : CombinedIndex.cfiFunctionDecls())
|
|
|
|
CfiFunctionDecls.insert(
|
|
|
|
GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
|
2017-03-10 22:35:17 +01:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
Error runThinLTOBackendThread(
|
2016-09-23 23:33:43 +02:00
|
|
|
AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
|
2016-12-14 02:17:59 +01:00
|
|
|
BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
|
2016-08-23 23:30:12 +02:00
|
|
|
const FunctionImporter::ImportMapTy &ImportList,
|
|
|
|
const FunctionImporter::ExportSetTy &ExportList,
|
|
|
|
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
|
|
|
|
const GVSummaryMapTy &DefinedGlobals,
|
[ThinLTO] Efficiency fix for writing type id records in per-module indexes
Summary:
In D49565/r337503, the type id record writing was fixed so that only
referenced type ids were emitted into each per-module index for ThinLTO
distributed builds. However, this still left an efficiency issue: each
per-module index checked all type ids for membership in the referenced
set, yielding O(M*N) performance (M indexes and N type ids).
Change the TypeIdMap in the summary to be indexed by GUID, to facilitate
correlating with type identifier GUIDs referenced in the function
summary TypeIdInfo structures. This allowed simplifying other
places where a map from type id GUID to type id map entry was previously
being used to aid this correlation.
Also fix AsmWriter code to handle the rare case of type id GUID
collision.
For a large internal application, this reduced the thin link time by
almost 15%.
Reviewers: pcc, vitalybuka
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51330
llvm-svn: 343021
2018-09-25 22:14:40 +02:00
|
|
|
MapVector<StringRef, BitcodeModule> &ModuleMap) {
|
2016-09-23 23:33:43 +02:00
|
|
|
auto RunThinBackend = [&](AddStreamFn AddStream) {
|
|
|
|
LTOLLVMContext BackendContext(Conf);
|
2016-12-14 02:17:59 +01:00
|
|
|
Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
|
2016-11-13 08:00:17 +01:00
|
|
|
if (!MOrErr)
|
|
|
|
return MOrErr.takeError();
|
2016-09-23 23:33:43 +02:00
|
|
|
|
|
|
|
return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
|
2021-03-30 00:04:28 +02:00
|
|
|
ImportList, DefinedGlobals, &ModuleMap);
|
2016-09-23 23:33:43 +02:00
|
|
|
};
|
2016-08-23 23:30:12 +02:00
|
|
|
|
2016-12-14 02:17:59 +01:00
|
|
|
auto ModuleID = BM.getModuleIdentifier();
|
2016-10-08 06:44:23 +02:00
|
|
|
|
|
|
|
if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
|
|
|
|
all_of(CombinedIndex.getModuleHash(ModuleID),
|
|
|
|
[](uint32_t V) { return V == 0; }))
|
|
|
|
// Cache disabled or no entry for this module in the combined index or
|
|
|
|
// no module hash.
|
2016-09-23 23:33:43 +02:00
|
|
|
return RunThinBackend(AddStream);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-09-23 23:33:43 +02:00
|
|
|
SmallString<40> Key;
|
|
|
|
// The module may be cached, this helps handling it.
|
[ThinLTO] Consolidate cache key computation between new/old LTO APIs
Summary:
The old legacy LTO API had a separate cache key computation, which was
a subset of the cache key computation in the new LTO API (from what I
can tell this is largely just because certain features such as CFI,
dsoLocal, etc are only utilized via the new LTO API). However, having
separate computations is unnecessary (much of the code is duplicated),
and can lead to bugs when adding new optimizations if both cache
computation algorithms aren't updated properly - it's much easier to
maintain if we have a single facility.
This patch refactors the old LTO API code to use the cache key
computation from the new LTO API. To do this, we set up an lto::Config
object and fill in the fields that the old LTO was hashing (the others
will just use the defaults).
There are two notable changes:
- I added a Freestanding flag to the LTO Config. Currently this is only
used by the legacy LTO API. In the patch that added it (D30791) I had
asked about adding it to the new LTO API, but it looks like that was not
addressed. This should probably be discussed as a follow up to this
change, as it is orthogonal.
- The legacy LTO API had some code that was hashing the GUID of all
preserved symbols defined in the module. I looked back at the history of
this (which was added with the original hashing in the legacy LTO API in
D18494), and there is a comment in the review thread that it was added
in preparation for future internalization. We now do the internalization
of course, and that is handled in the new LTO API cache key computation
by hashing the recorded linkage type of all defined globals. Therefore I
didn't try to move over and keep the preserved symbols handling.
Reviewers: steven_wu, pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, dang, llvm-commits
Differential Revision: https://reviews.llvm.org/D54635
llvm-svn: 347592
2018-11-26 21:40:37 +01:00
|
|
|
computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
|
|
|
|
ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
|
|
|
|
CfiFunctionDecls);
|
2016-09-23 23:33:43 +02:00
|
|
|
if (AddStreamFn CacheAddStream = Cache(Task, Key))
|
|
|
|
return RunThinBackend(CacheAddStream);
|
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
|
|
|
}
|
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
Error start(
|
2016-12-14 02:17:59 +01:00
|
|
|
unsigned Task, BitcodeModule BM,
|
2016-08-23 23:30:12 +02:00
|
|
|
const FunctionImporter::ImportMapTy &ImportList,
|
|
|
|
const FunctionImporter::ExportSetTy &ExportList,
|
|
|
|
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
|
2016-12-14 02:17:59 +01:00
|
|
|
MapVector<StringRef, BitcodeModule> &ModuleMap) override {
|
|
|
|
StringRef ModulePath = BM.getModuleIdentifier();
|
2016-09-06 05:23:45 +02:00
|
|
|
assert(ModuleToDefinedGVSummaries.count(ModulePath));
|
|
|
|
const GVSummaryMapTy &DefinedGlobals =
|
|
|
|
ModuleToDefinedGVSummaries.find(ModulePath)->second;
|
2016-08-11 16:58:12 +02:00
|
|
|
BackendThreadPool.async(
|
2016-12-14 02:17:59 +01:00
|
|
|
[=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
|
2016-08-11 16:58:12 +02:00
|
|
|
const FunctionImporter::ImportMapTy &ImportList,
|
2016-08-23 23:30:12 +02:00
|
|
|
const FunctionImporter::ExportSetTy &ExportList,
|
|
|
|
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
|
|
|
|
&ResolvedODR,
|
2016-09-06 05:23:45 +02:00
|
|
|
const GVSummaryMapTy &DefinedGlobals,
|
[ThinLTO] Efficiency fix for writing type id records in per-module indexes
Summary:
In D49565/r337503, the type id record writing was fixed so that only
referenced type ids were emitted into each per-module index for ThinLTO
distributed builds. However, this still left an efficiency issue: each
per-module index checked all type ids for membership in the referenced
set, yielding O(M*N) performance (M indexes and N type ids).
Change the TypeIdMap in the summary to be indexed by GUID, to facilitate
correlating with type identifier GUIDs referenced in the function
summary TypeIdInfo structures. This allowed simplifying other
places where a map from type id GUID to type id map entry was previously
being used to aid this correlation.
Also fix AsmWriter code to handle the rare case of type id GUID
collision.
For a large internal application, this reduced the thin link time by
almost 15%.
Reviewers: pcc, vitalybuka
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51330
llvm-svn: 343021
2018-09-25 22:14:40 +02:00
|
|
|
MapVector<StringRef, BitcodeModule> &ModuleMap) {
|
2020-01-28 17:05:13 +01:00
|
|
|
if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
|
|
|
|
timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
|
|
|
|
"thin backend");
|
2016-08-23 23:30:12 +02:00
|
|
|
Error E = runThinLTOBackendThread(
|
2017-03-10 22:35:17 +01:00
|
|
|
AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
|
[ThinLTO] Efficiency fix for writing type id records in per-module indexes
Summary:
In D49565/r337503, the type id record writing was fixed so that only
referenced type ids were emitted into each per-module index for ThinLTO
distributed builds. However, this still left an efficiency issue: each
per-module index checked all type ids for membership in the referenced
set, yielding O(M*N) performance (M indexes and N type ids).
Change the TypeIdMap in the summary to be indexed by GUID, to facilitate
correlating with type identifier GUIDs referenced in the function
summary TypeIdInfo structures. This allowed simplifying other
places where a map from type id GUID to type id map entry was previously
being used to aid this correlation.
Also fix AsmWriter code to handle the rare case of type id GUID
collision.
For a large internal application, this reduced the thin link time by
almost 15%.
Reviewers: pcc, vitalybuka
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51330
llvm-svn: 343021
2018-09-25 22:14:40 +02:00
|
|
|
ResolvedODR, DefinedGlobals, ModuleMap);
|
2016-08-11 16:58:12 +02:00
|
|
|
if (E) {
|
|
|
|
std::unique_lock<std::mutex> L(ErrMu);
|
|
|
|
if (Err)
|
|
|
|
Err = joinErrors(std::move(*Err), std::move(E));
|
|
|
|
else
|
|
|
|
Err = std::move(E);
|
|
|
|
}
|
2020-01-28 17:05:13 +01:00
|
|
|
if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
|
|
|
|
timeTraceProfilerFinishThread();
|
2016-08-11 16:58:12 +02:00
|
|
|
},
|
2017-03-10 22:35:17 +01:00
|
|
|
BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
|
[ThinLTO] Efficiency fix for writing type id records in per-module indexes
Summary:
In D49565/r337503, the type id record writing was fixed so that only
referenced type ids were emitted into each per-module index for ThinLTO
distributed builds. However, this still left an efficiency issue: each
per-module index checked all type ids for membership in the referenced
set, yielding O(M*N) performance (M indexes and N type ids).
Change the TypeIdMap in the summary to be indexed by GUID, to facilitate
correlating with type identifier GUIDs referenced in the function
summary TypeIdInfo structures. This allowed simplifying other
places where a map from type id GUID to type id map entry was previously
being used to aid this correlation.
Also fix AsmWriter code to handle the rare case of type id GUID
collision.
For a large internal application, this reduced the thin link time by
almost 15%.
Reviewers: pcc, vitalybuka
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, llvm-commits
Differential Revision: https://reviews.llvm.org/D51330
llvm-svn: 343021
2018-09-25 22:14:40 +02:00
|
|
|
std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
Error wait() override {
|
|
|
|
BackendThreadPool.wait();
|
|
|
|
if (Err)
|
|
|
|
return std::move(*Err);
|
|
|
|
else
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
Re-land [ThinLTO] Re-order modules for optimal multi-threaded processing
This reverts 9b5b3050237db3642ed7ab1bdb3ffa2202511b99 and fixes the unwanted re-ordering when generating ThinLTO indexes.
The goal of this patch is to better balance thread utilization during ThinLTO in-process linking (in llvm-lto2 or in LLD). Before this patch, large modules would often be scheduled late during execution, taking a long time to complete, thus starving the thread pool.
We now sort modules in descending order, based on each module's bitcode size, so that larger modules are processed first. By doing so, smaller modules have a better chance to keep the thread pool active, and thus avoid starvation when the bitcode compilation is almost complete.
In our case (on dual Intel Xeon Gold 6140, Windows 10 version 2004, two-stage build), this saves 15 sec when linking `clang.exe` with LLD & -flto=thin, /opt:lldltojobs=all, no ThinLTO cache, -DLLVM_INTEGRATED_CRT_ALLOC=d:\git\rpmalloc.
Before patch: 100 sec
After patch: 85 sec
Inspired by the work done by David Callahan in D60495.
Differential Revision: https://reviews.llvm.org/D87966
2020-10-14 03:54:00 +02:00
|
|
|
|
|
|
|
unsigned getThreadCount() override {
|
|
|
|
return BackendThreadPool.getThreadCount();
|
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
};
|
2016-11-19 21:44:26 +01:00
|
|
|
} // end anonymous namespace
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2020-03-27 15:20:39 +01:00
|
|
|
ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism) {
|
2020-01-13 21:23:34 +01:00
|
|
|
return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
|
2016-09-06 05:23:45 +02:00
|
|
|
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
|
2016-09-23 23:33:43 +02:00
|
|
|
AddStreamFn AddStream, NativeObjectCache Cache) {
|
2019-08-15 17:54:37 +02:00
|
|
|
return std::make_unique<InProcessThinBackend>(
|
2020-03-27 15:20:39 +01:00
|
|
|
Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream,
|
|
|
|
Cache);
|
2016-08-11 16:58:12 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2016-09-21 21:12:05 +02:00
|
|
|
// Given the original \p Path to an output file, replace any path
|
|
|
|
// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
|
|
|
|
// resulting directory if it does not yet exist.
|
|
|
|
std::string lto::getThinLTOOutputFile(const std::string &Path,
|
|
|
|
const std::string &OldPrefix,
|
|
|
|
const std::string &NewPrefix) {
|
|
|
|
if (OldPrefix.empty() && NewPrefix.empty())
|
|
|
|
return Path;
|
|
|
|
SmallString<128> NewPath(Path);
|
|
|
|
llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
|
|
|
|
StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
|
|
|
|
if (!ParentPath.empty()) {
|
|
|
|
// Make sure the new directory exists, creating it if necessary.
|
|
|
|
if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
|
|
|
|
llvm::errs() << "warning: could not create directory '" << ParentPath
|
|
|
|
<< "': " << EC.message() << '\n';
|
|
|
|
}
|
2020-01-28 20:23:46 +01:00
|
|
|
return std::string(NewPath.str());
|
2016-09-21 21:12:05 +02:00
|
|
|
}
|
|
|
|
|
2016-11-19 21:44:26 +01:00
|
|
|
namespace {
|
2016-08-11 16:58:12 +02:00
|
|
|
class WriteIndexesThinBackend : public ThinBackendProc {
|
|
|
|
std::string OldPrefix, NewPrefix;
|
|
|
|
bool ShouldEmitImportsFiles;
|
2018-02-22 20:06:15 +01:00
|
|
|
raw_fd_ostream *LinkedObjectsFile;
|
2018-01-30 22:19:26 +01:00
|
|
|
lto::IndexWriteCallback OnWrite;
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
public:
|
2016-09-06 05:23:45 +02:00
|
|
|
WriteIndexesThinBackend(
|
2020-01-13 21:23:34 +01:00
|
|
|
const Config &Conf, ModuleSummaryIndex &CombinedIndex,
|
2016-09-06 05:23:45 +02:00
|
|
|
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
|
|
|
|
std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
|
2018-02-22 20:06:15 +01:00
|
|
|
raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
|
2016-08-19 08:10:03 +02:00
|
|
|
: ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
|
2016-08-11 16:58:12 +02:00
|
|
|
OldPrefix(OldPrefix), NewPrefix(NewPrefix),
|
|
|
|
ShouldEmitImportsFiles(ShouldEmitImportsFiles),
|
2018-02-22 20:06:15 +01:00
|
|
|
LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2016-08-23 23:30:12 +02:00
|
|
|
Error start(
|
2016-12-14 02:17:59 +01:00
|
|
|
unsigned Task, BitcodeModule BM,
|
2016-08-23 23:30:12 +02:00
|
|
|
const FunctionImporter::ImportMapTy &ImportList,
|
|
|
|
const FunctionImporter::ExportSetTy &ExportList,
|
|
|
|
const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
|
2016-12-14 02:17:59 +01:00
|
|
|
MapVector<StringRef, BitcodeModule> &ModuleMap) override {
|
|
|
|
StringRef ModulePath = BM.getModuleIdentifier();
|
2016-08-11 16:58:12 +02:00
|
|
|
std::string NewModulePath =
|
2020-01-28 20:23:46 +01:00
|
|
|
getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-02-22 20:06:15 +01:00
|
|
|
if (LinkedObjectsFile)
|
2016-08-11 16:58:12 +02:00
|
|
|
*LinkedObjectsFile << NewModulePath << '\n';
|
|
|
|
|
|
|
|
std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
|
|
|
|
gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
|
2016-08-16 07:46:05 +02:00
|
|
|
ImportList, ModuleToSummariesForIndex);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-02-22 20:06:15 +01:00
|
|
|
std::error_code EC;
|
2016-08-11 16:58:12 +02:00
|
|
|
raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
|
2019-08-05 07:43:48 +02:00
|
|
|
sys::fs::OpenFlags::OF_None);
|
2016-08-11 16:58:12 +02:00
|
|
|
if (EC)
|
|
|
|
return errorCodeToError(EC);
|
|
|
|
WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
|
|
|
|
|
2018-01-30 22:19:26 +01:00
|
|
|
if (ShouldEmitImportsFiles) {
|
2018-07-10 22:06:04 +02:00
|
|
|
EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
|
|
|
|
ModuleToSummariesForIndex);
|
2018-01-30 22:19:26 +01:00
|
|
|
if (EC)
|
|
|
|
return errorCodeToError(EC);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (OnWrite)
|
2020-01-28 20:23:46 +01:00
|
|
|
OnWrite(std::string(ModulePath));
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
}
|
|
|
|
|
2016-11-11 05:28:40 +01:00
|
|
|
Error wait() override { return Error::success(); }
|
Re-land [ThinLTO] Re-order modules for optimal multi-threaded processing
This reverts 9b5b3050237db3642ed7ab1bdb3ffa2202511b99 and fixes the unwanted re-ordering when generating ThinLTO indexes.
The goal of this patch is to better balance thread utilization during ThinLTO in-process linking (in llvm-lto2 or in LLD). Before this patch, large modules would often be scheduled late during execution, taking a long time to complete, thus starving the thread pool.
We now sort modules in descending order, based on each module's bitcode size, so that larger modules are processed first. By doing so, smaller modules have a better chance to keep the thread pool active, and thus avoid starvation when the bitcode compilation is almost complete.
In our case (on dual Intel Xeon Gold 6140, Windows 10 version 2004, two-stage build), this saves 15 sec when linking `clang.exe` with LLD & -flto=thin, /opt:lldltojobs=all, no ThinLTO cache, -DLLVM_INTEGRATED_CRT_ALLOC=d:\git\rpmalloc.
Before patch: 100 sec
After patch: 85 sec
Inspired by the work done by David Callahan in D60495.
Differential Revision: https://reviews.llvm.org/D87966
2020-10-14 03:54:00 +02:00
|
|
|
|
|
|
|
// WriteIndexesThinBackend should always return 1 to prevent module
|
|
|
|
// re-ordering and avoid non-determinism in the final link.
|
|
|
|
unsigned getThreadCount() override { return 1; }
|
2016-08-11 16:58:12 +02:00
|
|
|
};
|
2016-11-19 21:44:26 +01:00
|
|
|
} // end anonymous namespace
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-02-22 20:06:15 +01:00
|
|
|
ThinBackend lto::createWriteIndexesThinBackend(
|
|
|
|
std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
|
|
|
|
raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
|
2020-01-13 21:23:34 +01:00
|
|
|
return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
|
2016-09-06 05:23:45 +02:00
|
|
|
const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
|
2016-09-23 23:33:43 +02:00
|
|
|
AddStreamFn AddStream, NativeObjectCache Cache) {
|
2019-08-15 17:54:37 +02:00
|
|
|
return std::make_unique<WriteIndexesThinBackend>(
|
2016-08-19 08:10:03 +02:00
|
|
|
Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
|
2018-01-30 22:19:26 +01:00
|
|
|
ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
|
2016-08-11 16:58:12 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
|
|
|
|
const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
|
2016-08-11 16:58:12 +02:00
|
|
|
if (ThinLTO.ModuleMap.empty())
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2020-05-21 22:19:44 +02:00
|
|
|
if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
|
|
|
|
llvm::errs() << "warning: [ThinLTO] No module compiled\n";
|
|
|
|
return Error::success();
|
|
|
|
}
|
|
|
|
|
2019-12-18 16:33:15 +01:00
|
|
|
if (Conf.CombinedIndexHook &&
|
|
|
|
!Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
|
2016-11-11 05:28:40 +01:00
|
|
|
return Error::success();
|
2016-08-11 16:58:12 +02:00
|
|
|
|
|
|
|
// Collect for each module the list of function it defines (GUID ->
|
|
|
|
// Summary).
|
2017-07-10 22:12:54 +02:00
|
|
|
StringMap<GVSummaryMapTy>
|
2016-08-11 16:58:12 +02:00
|
|
|
ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
|
|
|
|
ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
|
|
|
|
ModuleToDefinedGVSummaries);
|
2016-09-21 01:07:17 +02:00
|
|
|
// Create entries for any modules that didn't have any GV summaries
|
|
|
|
// (either they didn't have any GVs to start with, or we suppressed
|
|
|
|
// generation of the summaries because they e.g. had inline assembly
|
|
|
|
// uses that couldn't be promoted/renamed on export). This is so
|
|
|
|
// InProcessThinBackend::start can still launch a backend thread, which
|
|
|
|
// is passed the map of summaries for the module, without any special
|
|
|
|
// handling for this case.
|
|
|
|
for (auto &Mod : ThinLTO.ModuleMap)
|
|
|
|
if (!ModuleToDefinedGVSummaries.count(Mod.first))
|
|
|
|
ModuleToDefinedGVSummaries.try_emplace(Mod.first);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-12-13 20:54:27 +01:00
|
|
|
// Synthesize entry counts for functions in the CombinedIndex.
|
|
|
|
computeSyntheticCounts(ThinLTO.CombinedIndex);
|
|
|
|
|
2016-08-11 16:58:12 +02:00
|
|
|
StringMap<FunctionImporter::ImportMapTy> ImportLists(
|
|
|
|
ThinLTO.ModuleMap.size());
|
|
|
|
StringMap<FunctionImporter::ExportSetTy> ExportLists(
|
|
|
|
ThinLTO.ModuleMap.size());
|
2016-10-31 23:12:21 +01:00
|
|
|
StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2018-02-19 16:14:50 +01:00
|
|
|
if (DumpThinCGSCCs)
|
|
|
|
ThinLTO.CombinedIndex.dumpSCCs(outs());
|
|
|
|
|
2019-08-02 15:10:52 +02:00
|
|
|
std::set<GlobalValue::GUID> ExportedGUIDs;
|
|
|
|
|
2020-01-24 21:24:18 +01:00
|
|
|
// If allowed, upgrade public vcall visibility to linkage unit visibility in
|
|
|
|
// the summaries before whole program devirtualization below.
|
|
|
|
updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
|
2020-12-31 00:56:53 +01:00
|
|
|
Conf.HasWholeProgramVisibility,
|
|
|
|
DynamicExportSymbols);
|
2020-01-24 21:24:18 +01:00
|
|
|
|
2019-08-02 15:10:52 +02:00
|
|
|
// Perform index-based WPD. This will return immediately if there are
|
|
|
|
// no index entries in the typeIdMetadata map (e.g. if we are instead
|
|
|
|
// performing IR-based WPD in hybrid regular/thin LTO mode).
|
|
|
|
std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
|
|
|
|
runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
|
|
|
|
LocalWPDTargetsMap);
|
|
|
|
|
2017-11-01 18:58:39 +01:00
|
|
|
if (Conf.OptLevel > 0)
|
2016-10-31 23:12:21 +01:00
|
|
|
ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
|
2017-06-01 22:30:06 +02:00
|
|
|
ImportLists, ExportLists);
|
2016-08-23 23:30:12 +02:00
|
|
|
|
2017-11-01 18:58:39 +01:00
|
|
|
// Figure out which symbols need to be internalized. This also needs to happen
|
|
|
|
// at -O0 because summary-based DCE is implemented using internalization, and
|
|
|
|
// we must apply DCE consistently with the full LTO module in order to avoid
|
|
|
|
// undefined references during the final link.
|
|
|
|
for (auto &Res : GlobalResolutions) {
|
2018-01-25 18:23:27 +01:00
|
|
|
// If the symbol does not have external references or it is not prevailing,
|
|
|
|
// then not need to mark it as exported from a ThinLTO partition.
|
|
|
|
if (Res.second.Partition != GlobalResolution::External ||
|
2018-01-29 09:03:30 +01:00
|
|
|
!Res.second.isPrevailingIRSymbol())
|
2017-11-01 18:58:39 +01:00
|
|
|
continue;
|
|
|
|
auto GUID = GlobalValue::getGUID(
|
|
|
|
GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
|
|
|
|
// Mark exported unless index-based analysis determined it to be dead.
|
|
|
|
if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
|
|
|
|
ExportedGUIDs.insert(GUID);
|
2016-10-31 23:12:21 +01:00
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2017-11-01 18:58:39 +01:00
|
|
|
// Any functions referenced by the jump table in the regular LTO object must
|
|
|
|
// be exported.
|
|
|
|
for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
|
|
|
|
ExportedGUIDs.insert(
|
|
|
|
GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
|
2021-06-08 23:57:32 +02:00
|
|
|
for (auto &Decl : ThinLTO.CombinedIndex.cfiFunctionDecls())
|
|
|
|
ExportedGUIDs.insert(
|
|
|
|
GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Decl)));
|
2017-11-01 18:58:39 +01:00
|
|
|
|
2019-11-15 14:13:19 +01:00
|
|
|
auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
|
2017-11-01 18:58:39 +01:00
|
|
|
const auto &ExportList = ExportLists.find(ModuleIdentifier);
|
2019-11-15 14:13:19 +01:00
|
|
|
return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
|
|
|
|
ExportedGUIDs.count(VI.getGUID());
|
2017-11-01 18:58:39 +01:00
|
|
|
};
|
2019-10-02 18:36:59 +02:00
|
|
|
|
|
|
|
// Update local devirtualized targets that were exported by cross-module
|
|
|
|
// importing or by other devirtualizations marked in the ExportedGUIDs set.
|
|
|
|
updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
|
|
|
|
LocalWPDTargetsMap);
|
|
|
|
|
2017-05-26 01:40:11 +02:00
|
|
|
auto isPrevailing = [&](GlobalValue::GUID GUID,
|
|
|
|
const GlobalValueSummary *S) {
|
|
|
|
return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
|
|
|
|
};
|
[ThinLTO] Fix handling of weak interposable symbols
Summary:
Keep aliasees alive if their alias is live, otherwise we end up with an
alias to a declaration, which is invalid. This can happen when the
aliasee is weak and non-prevailing.
This fix exposed the fact that we were then attempting to internalize
the weak symbol, which was not exported as it was not prevailing. We
should not internalize interposable symbols in general, unless this is
the prevailing copy, since it can lead to incorrect inlining and other
optimizations. Most of the changes in this patch are due to the
restructuring required to pass down the prevailing callback.
Finally, while implementing the test cases, I found that in the case of
a weak aliasee that is still marked not live because its alias isn't
live, after dropping the definition we incorrectly marked the
declaration with weak linkage when resolving prevailing symbols in the
module. This was due to some special case handling for symbols marked
WeakLinkage in the summary located before instead of after a subsequent
check for the symbol being a declaration. It turns out that we don't
actually need this special case handling any more (looking back at the
history, when that was added the code was structured quite differently)
- we will correctly mark with weak linkage further below when the
definition hasn't been dropped.
Fixes PR42542.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, steven_wu, dexonsmith, dang, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D66264
llvm-svn: 369766
2019-08-23 17:18:58 +02:00
|
|
|
thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
|
|
|
|
isPrevailing);
|
|
|
|
|
2017-05-26 01:40:11 +02:00
|
|
|
auto recordNewLinkage = [&](StringRef ModuleIdentifier,
|
|
|
|
GlobalValue::GUID GUID,
|
|
|
|
GlobalValue::LinkageTypes NewLinkage) {
|
|
|
|
ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
|
|
|
|
};
|
2021-01-27 19:43:51 +01:00
|
|
|
thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
|
[ThinLTO] Auto-hide prevailing linkonce_odr only when all copies eligible
Summary:
We hit undefined references building with ThinLTO when one source file
contained explicit instantiations of a template method (weak_odr) but
there were also implicit instantiations in another file (linkonce_odr),
and the latter was the prevailing copy. In this case the symbol was
marked hidden when the prevailing linkonce_odr copy was promoted to
weak_odr. It led to unsats when the resulting shared library was linked
with other code that contained a reference (expecting to be resolved due
to the explicit instantiation).
Add a CanAutoHide flag to the GV summary to allow the thin link to
identify when all copies are eligible for auto-hiding (because they were
all originally linkonce_odr global unnamed addr), and only do the
auto-hide in that case.
Most of the changes here are due to plumbing the new flag through the
bitcode and llvm assembly, and resulting test changes. I augmented the
existing auto-hide test to check for this situation.
Reviewers: pcc
Subscribers: mehdi_amini, inglorion, eraman, dexonsmith, arphaman, dang, llvm-commits, steven_wu, wmi
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59709
llvm-svn: 360466
2019-05-10 22:08:24 +02:00
|
|
|
recordNewLinkage, GUIDPreservedSymbols);
|
2017-05-26 01:40:11 +02:00
|
|
|
|
2020-06-05 10:11:35 +02:00
|
|
|
generateParamAccessSummary(ThinLTO.CombinedIndex);
|
|
|
|
|
2016-09-23 23:33:43 +02:00
|
|
|
std::unique_ptr<ThinBackendProc> BackendProc =
|
|
|
|
ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
|
|
|
|
AddStream, Cache);
|
2016-08-11 16:58:12 +02:00
|
|
|
|
2020-05-21 22:19:44 +02:00
|
|
|
auto &ModuleMap =
|
|
|
|
ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
|
|
|
|
|
Re-land [ThinLTO] Re-order modules for optimal multi-threaded processing
This reverts 9b5b3050237db3642ed7ab1bdb3ffa2202511b99 and fixes the unwanted re-ordering when generating ThinLTO indexes.
The goal of this patch is to better balance thread utilization during ThinLTO in-process linking (in llvm-lto2 or in LLD). Before this patch, large modules would often be scheduled late during execution, taking a long time to complete, thus starving the thread pool.
We now sort modules in descending order, based on each module's bitcode size, so that larger modules are processed first. By doing so, smaller modules have a better chance to keep the thread pool active, and thus avoid starvation when the bitcode compilation is almost complete.
In our case (on dual Intel Xeon Gold 6140, Windows 10 version 2004, two-stage build), this saves 15 sec when linking `clang.exe` with LLD & -flto=thin, /opt:lldltojobs=all, no ThinLTO cache, -DLLVM_INTEGRATED_CRT_ALLOC=d:\git\rpmalloc.
Before patch: 100 sec
After patch: 85 sec
Inspired by the work done by David Callahan in D60495.
Differential Revision: https://reviews.llvm.org/D87966
2020-10-14 03:54:00 +02:00
|
|
|
auto ProcessOneModule = [&](int I) -> Error {
|
|
|
|
auto &Mod = *(ModuleMap.begin() + I);
|
|
|
|
// Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
|
|
|
|
// combined module and parallel code generation partitions.
|
|
|
|
return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I,
|
|
|
|
Mod.second, ImportLists[Mod.first],
|
|
|
|
ExportLists[Mod.first], ResolvedODR[Mod.first],
|
|
|
|
ThinLTO.ModuleMap);
|
|
|
|
};
|
2016-08-11 16:58:12 +02:00
|
|
|
|
Re-land [ThinLTO] Re-order modules for optimal multi-threaded processing
This reverts 9b5b3050237db3642ed7ab1bdb3ffa2202511b99 and fixes the unwanted re-ordering when generating ThinLTO indexes.
The goal of this patch is to better balance thread utilization during ThinLTO in-process linking (in llvm-lto2 or in LLD). Before this patch, large modules would often be scheduled late during execution, taking a long time to complete, thus starving the thread pool.
We now sort modules in descending order, based on each module's bitcode size, so that larger modules are processed first. By doing so, smaller modules have a better chance to keep the thread pool active, and thus avoid starvation when the bitcode compilation is almost complete.
In our case (on dual Intel Xeon Gold 6140, Windows 10 version 2004, two-stage build), this saves 15 sec when linking `clang.exe` with LLD & -flto=thin, /opt:lldltojobs=all, no ThinLTO cache, -DLLVM_INTEGRATED_CRT_ALLOC=d:\git\rpmalloc.
Before patch: 100 sec
After patch: 85 sec
Inspired by the work done by David Callahan in D60495.
Differential Revision: https://reviews.llvm.org/D87966
2020-10-14 03:54:00 +02:00
|
|
|
if (BackendProc->getThreadCount() == 1) {
|
|
|
|
// Process the modules in the order they were provided on the command-line.
|
|
|
|
// It is important for this codepath to be used for WriteIndexesThinBackend,
|
|
|
|
// to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same
|
|
|
|
// order as the inputs, which otherwise would affect the final link order.
|
|
|
|
for (int I = 0, E = ModuleMap.size(); I != E; ++I)
|
|
|
|
if (Error E = ProcessOneModule(I))
|
|
|
|
return E;
|
|
|
|
} else {
|
|
|
|
// When executing in parallel, process largest bitsize modules first to
|
|
|
|
// improve parallelism, and avoid starving the thread pool near the end.
|
|
|
|
// This saves about 15 sec on a 36-core machine while link `clang.exe` (out
|
|
|
|
// of 100 sec).
|
|
|
|
std::vector<BitcodeModule *> ModulesVec;
|
|
|
|
ModulesVec.reserve(ModuleMap.size());
|
|
|
|
for (auto &Mod : ModuleMap)
|
|
|
|
ModulesVec.push_back(&Mod.second);
|
|
|
|
for (int I : generateModulesOrdering(ModulesVec))
|
|
|
|
if (Error E = ProcessOneModule(I))
|
|
|
|
return E;
|
|
|
|
}
|
2016-08-11 16:58:12 +02:00
|
|
|
return BackendProc->wait();
|
2016-05-24 00:54:06 +02:00
|
|
|
}
|
2017-02-11 00:49:38 +01:00
|
|
|
|
2019-10-28 22:53:31 +01:00
|
|
|
Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
|
|
|
|
LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
|
2020-11-17 19:37:59 +01:00
|
|
|
StringRef RemarksFormat, bool RemarksWithHotness,
|
|
|
|
Optional<uint64_t> RemarksHotnessThreshold, int Count) {
|
2020-01-28 20:23:46 +01:00
|
|
|
std::string Filename = std::string(RemarksFilename);
|
2019-12-02 22:02:48 +01:00
|
|
|
// For ThinLTO, file.opt.<format> becomes
|
|
|
|
// file.opt.<format>.thin.<num>.<format>.
|
2019-06-14 18:20:51 +02:00
|
|
|
if (!Filename.empty() && Count != -1)
|
2019-12-02 22:02:48 +01:00
|
|
|
Filename =
|
|
|
|
(Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
|
|
|
|
.str();
|
2017-02-11 00:49:38 +01:00
|
|
|
|
2019-10-28 22:53:31 +01:00
|
|
|
auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
|
2020-11-17 19:37:59 +01:00
|
|
|
Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
|
|
|
|
RemarksHotnessThreshold);
|
2019-06-14 18:20:51 +02:00
|
|
|
if (Error E = ResultOrErr.takeError())
|
2020-02-10 16:06:45 +01:00
|
|
|
return std::move(E);
|
2019-03-12 22:22:27 +01:00
|
|
|
|
2019-06-14 18:20:51 +02:00
|
|
|
if (*ResultOrErr)
|
|
|
|
(*ResultOrErr)->keep();
|
2019-03-12 22:22:27 +01:00
|
|
|
|
2019-06-14 18:20:51 +02:00
|
|
|
return ResultOrErr;
|
2017-02-11 00:49:38 +01:00
|
|
|
}
|
2019-04-19 14:36:41 +02:00
|
|
|
|
|
|
|
Expected<std::unique_ptr<ToolOutputFile>>
|
|
|
|
lto::setupStatsFile(StringRef StatsFilename) {
|
|
|
|
// Setup output file to emit statistics.
|
|
|
|
if (StatsFilename.empty())
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
llvm::EnableStatistics(false);
|
|
|
|
std::error_code EC;
|
|
|
|
auto StatsFile =
|
2019-08-15 17:54:37 +02:00
|
|
|
std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
|
2019-04-19 14:36:41 +02:00
|
|
|
if (EC)
|
|
|
|
return errorCodeToError(EC);
|
|
|
|
|
|
|
|
StatsFile->keep();
|
2020-02-10 16:06:45 +01:00
|
|
|
return std::move(StatsFile);
|
2019-04-19 14:36:41 +02:00
|
|
|
}
|
Re-land [ThinLTO] Re-order modules for optimal multi-threaded processing
This reverts 9b5b3050237db3642ed7ab1bdb3ffa2202511b99 and fixes the unwanted re-ordering when generating ThinLTO indexes.
The goal of this patch is to better balance thread utilization during ThinLTO in-process linking (in llvm-lto2 or in LLD). Before this patch, large modules would often be scheduled late during execution, taking a long time to complete, thus starving the thread pool.
We now sort modules in descending order, based on each module's bitcode size, so that larger modules are processed first. By doing so, smaller modules have a better chance to keep the thread pool active, and thus avoid starvation when the bitcode compilation is almost complete.
In our case (on dual Intel Xeon Gold 6140, Windows 10 version 2004, two-stage build), this saves 15 sec when linking `clang.exe` with LLD & -flto=thin, /opt:lldltojobs=all, no ThinLTO cache, -DLLVM_INTEGRATED_CRT_ALLOC=d:\git\rpmalloc.
Before patch: 100 sec
After patch: 85 sec
Inspired by the work done by David Callahan in D60495.
Differential Revision: https://reviews.llvm.org/D87966
2020-10-14 03:54:00 +02:00
|
|
|
|
|
|
|
// Compute the ordering we will process the inputs: the rough heuristic here
|
|
|
|
// is to sort them per size so that the largest module get schedule as soon as
|
|
|
|
// possible. This is purely a compile-time optimization.
|
|
|
|
std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
|
|
|
|
std::vector<int> ModulesOrdering;
|
|
|
|
ModulesOrdering.resize(R.size());
|
|
|
|
std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
|
|
|
|
llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
|
|
|
|
auto LSize = R[LeftIndex]->getBuffer().size();
|
|
|
|
auto RSize = R[RightIndex]->getBuffer().size();
|
|
|
|
return LSize > RSize;
|
|
|
|
});
|
|
|
|
return ModulesOrdering;
|
|
|
|
}
|