2015-10-14 15:35:14 -07:00
|
|
|
//===--- BinaryContext.cpp - Interface for machine-level context ---------===//
|
|
|
|
//
|
2021-03-15 18:04:18 -07: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
|
2015-10-14 15:35:14 -07:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "BinaryContext.h"
|
2020-03-06 15:06:37 -08:00
|
|
|
#include "BinaryEmitter.h"
|
Update subroutine address ranges in binary.
Summary:
[WIP] Update DWARF info for function address ranges.
This diff currently does not work for unknown reasons,
but I'm describing here what's the current state.
According to both llvm-dwarf and readelf our output seems correct,
but GDB does not interpret it as expected. All details go below in
hope I missed something.
I couldn't actually track the whole change that introduced support for
what we need in gdb yet, but I think I can get to it
(2007-12-04: Support
lexical bocks and function bodies that occupy non-contiguous address ranges). I have reasons to believe gdb at least at some
nges).
The set of introduced changes was basically this:
- After disassembly, iterate over the DIEs in .debug_info and find the
ones that correspond to each BinaryFunction.
- Refactor DebugArangesWriter to also write addresses of functions to
.debug_ranges and track the offsets of function address ranges there
- Add some infrastructure to facilitate patching the binary in
simple ways (BinaryPatcher.h)
- In RewriteInstance, after writing .debug_ranges already with
function address ranges, for each function do:
-- Find the abbreviation corresponding to the function
-- Patch .debug_abbrev to replace DW_AT_low_pc with DW_AT_ranges and
DW_AT_high_pc with DW_AT_producer (I'll explain this hack below).
Also patch the corresponding forms to DW_FORM_sec_offset and
DW_FORM_string (null-terminated in-place string).
-- Patch debug_info with the .debug_ranges offset in place of
the first 4 bytes of DW_AT_low_pc (DW_AT_ranges only occupies 4
bytes whereas low_pc occupies 8), and write an arbitrary string
in-place in the other 12 bytes that were the 4 MSB of low_pc
and the 8 bytes of high_pc before the patch. This depends on
low_pc and high_pc being put consecutively by the compiler, but
it serves to validate the idea. I tried another way of doing it
that does not rely on this but it didn't work either and I believe
the reason for either not working is the same (and still unknown,
but unrelated to them. I might be wrong though, and if I find yet
another way of doing it I may try it). The other way was to
use a form of DW_FORM_data8 for the section offset. This is
disallowed by the specification, but I doubt gdb validates this,
as it's just easier to store it as 64-bit anyway as this is even
necessary to support 64-bit DWARF (which is not what gcc generates
by default apparently).
I still need to make changes to the diff to make it production-ready,
but first I want to figure out why it doesn't work as expected.
By looking at the output of llvm-dwarfdump or readelf, all of
.debug_ranges, .debug_abbrev and .debug_info seem to have been
correctly updated. However, gdb seems to have serious problems with
what we write.
(In fact, readelf --debug-dump=Ranges shows some funny warning messages
of the form ("Warning: There is a hole [0x100 - 0x120] in .debug_ranges"),
but I played around with this and it seems it's just because no
compile unit was using these ranges. Changing .debug_info apparently
changes these warnings, so they seem to be unrelated to the section
itself. Also looking at the hex dump of the section doesn't help,
as everything seems fine. llvm-dwarfdump doesn't say anything.
So I think .debug_ranges is fine.)
The result is that gdb not only doesn't show the function name as we
wanted, but it also stops showing line number information.
Apparently it's not reading/interpreting the address ranges at all,
and so the functions now have no associated address ranges, only the
symbol value which allows one to put a breakpoint in the function,
but not to show source code.
As this left me without more ideas of what to try to feed gdb with,
I believe the most promising next trial is to try to debug gdb itself,
unless someone spots anything I missed.
I found where the interesting part of the code lies for this
case (gdb/dwarf2read.c and some other related files, but mainly that one).
It seems in some parts gdb uses DW_AT_ranges for only getting
its lowest and highest addresses and setting that as low_pc and
high_pc (see dwarf2_get_pc_bounds in gdb's code and where it's called).
I really hope this is not actually the case for
function address ranges. I'll investigate this further. Otherwise
I don't think any changes we make will make it work as initially
intended, as we'll simply need gdb to support it and in that case it
doesn't.
(cherry picked from FBD3073641)
2016-03-16 18:08:29 -07:00
|
|
|
#include "BinaryFunction.h"
|
2020-11-06 11:19:03 -08:00
|
|
|
#include "NameResolver.h"
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
#include "Utils.h"
|
2015-10-14 15:35:14 -07:00
|
|
|
#include "llvm/ADT/Twine.h"
|
2017-05-16 09:27:34 -07:00
|
|
|
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
|
2016-03-28 17:45:22 -07:00
|
|
|
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
|
2018-11-15 16:02:16 -08:00
|
|
|
#include "llvm/MC/MCAsmLayout.h"
|
2019-07-17 20:54:53 -07:00
|
|
|
#include "llvm/MC/MCAssembler.h"
|
2015-10-14 15:35:14 -07:00
|
|
|
#include "llvm/MC/MCContext.h"
|
2021-04-30 13:54:02 -07:00
|
|
|
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
|
|
|
|
#include "llvm/MC/MCInstPrinter.h"
|
2018-11-15 16:02:16 -08:00
|
|
|
#include "llvm/MC/MCObjectStreamer.h"
|
[BOLT rebase] Rebase fixes on top of LLVM Feb2018
Summary:
This commit includes all code necessary to make BOLT working again
after the rebase. This includes a redesign of the EHFrame work,
cherry-pick of the 3dnow disassembly work, compilation error fixes,
and port of the debug_info work. The macroop fusion feature is not
ported yet.
The rebased version has minor changes to the "executed instructions"
dynostats counter because REP prefixes are considered a part of the
instruction it applies to. Also, some X86 instructions had the "mayLoad"
tablegen property removed, which BOLT uses to identify and account
for loads, thus reducing the total number of loads reported by
dynostats. This was observed in X86::MOVDQUmr. TRAP instructions are
not terminators anymore, changing our CFG. This commit adds compensation
to preserve this old behavior and minimize tests changes. debug_info
sections are now slightly larger. The discriminator field in the line
table is slightly different due to a change upstream. New profiles
generated with the other bolt are incompatible with this version
because of different hash values calculated for functions, so they will
be considered 100% stale. This commit changes the corresponding test
to XFAIL so it can be updated. The hash function changes because it
relies on raw opcode values, which change according to the opcodes
described in the X86 tablegen files. When processing HHVM, bolt was
observed to be using about 800MB more memory in the rebased version
and being about 5% slower.
(cherry picked from FBD7078072)
2018-02-06 15:00:23 -08:00
|
|
|
#include "llvm/MC/MCObjectWriter.h"
|
2018-11-15 16:02:16 -08:00
|
|
|
#include "llvm/MC/MCSectionELF.h"
|
2017-02-21 16:15:15 -08:00
|
|
|
#include "llvm/MC/MCStreamer.h"
|
2015-10-14 15:35:14 -07:00
|
|
|
#include "llvm/MC/MCSymbol.h"
|
2016-07-23 08:01:53 -07:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2020-11-06 11:19:03 -08:00
|
|
|
#include "llvm/Support/Regex.h"
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
#include <functional>
|
2017-11-14 20:05:11 -08:00
|
|
|
#include <iterator>
|
2015-10-14 15:35:14 -07:00
|
|
|
|
2016-12-21 17:13:56 -08:00
|
|
|
using namespace llvm;
|
2015-10-14 15:35:14 -07:00
|
|
|
|
2018-02-01 16:33:43 -08:00
|
|
|
#undef DEBUG_TYPE
|
|
|
|
#define DEBUG_TYPE "bolt"
|
|
|
|
|
2016-07-23 08:01:53 -07:00
|
|
|
namespace opts {
|
|
|
|
|
2017-03-28 14:40:20 -07:00
|
|
|
extern cl::OptionCategory BoltCategory;
|
|
|
|
|
2019-06-28 09:21:27 -07:00
|
|
|
extern cl::opt<bool> AggregateOnly;
|
2020-06-18 11:10:41 -07:00
|
|
|
extern cl::opt<bool> HotText;
|
|
|
|
extern cl::opt<bool> HotData;
|
2019-06-28 09:21:27 -07:00
|
|
|
extern cl::opt<bool> StrictMode;
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
extern cl::opt<bool> UseOldText;
|
2018-06-11 17:17:25 -07:00
|
|
|
extern cl::opt<unsigned> Verbosity;
|
2020-07-27 18:07:18 -07:00
|
|
|
extern cl::opt<unsigned> ExecutionCountThreshold;
|
2018-06-11 17:17:25 -07:00
|
|
|
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
extern bool processAllFunctions();
|
|
|
|
|
2018-09-24 20:58:31 -07:00
|
|
|
cl::opt<bool>
|
|
|
|
NoHugePages("no-huge-pages",
|
|
|
|
cl::desc("use regular size pages for code alignment"),
|
|
|
|
cl::ZeroOrMore,
|
|
|
|
cl::Hidden,
|
|
|
|
cl::cat(BoltCategory));
|
|
|
|
|
2016-07-23 08:01:53 -07:00
|
|
|
static cl::opt<bool>
|
|
|
|
PrintDebugInfo("print-debug-info",
|
2017-03-28 14:40:20 -07:00
|
|
|
cl::desc("print debug info when printing functions"),
|
|
|
|
cl::Hidden,
|
2018-02-01 16:33:43 -08:00
|
|
|
cl::ZeroOrMore,
|
2017-03-28 14:40:20 -07:00
|
|
|
cl::cat(BoltCategory));
|
2016-07-23 08:01:53 -07:00
|
|
|
|
2018-02-01 16:33:43 -08:00
|
|
|
cl::opt<bool>
|
2017-10-20 12:11:34 -07:00
|
|
|
PrintRelocations("print-relocations",
|
2018-02-01 16:33:43 -08:00
|
|
|
cl::desc("print relocations when printing functions/objects"),
|
2017-10-20 12:11:34 -07:00
|
|
|
cl::Hidden,
|
2018-02-01 16:33:43 -08:00
|
|
|
cl::ZeroOrMore,
|
2017-10-20 12:11:34 -07:00
|
|
|
cl::cat(BoltCategory));
|
|
|
|
|
|
|
|
static cl::opt<bool>
|
|
|
|
PrintMemData("print-mem-data",
|
|
|
|
cl::desc("print memory data annotations when printing functions"),
|
|
|
|
cl::Hidden,
|
2018-02-01 16:33:43 -08:00
|
|
|
cl::ZeroOrMore,
|
2017-10-20 12:11:34 -07:00
|
|
|
cl::cat(BoltCategory));
|
|
|
|
|
2016-07-23 08:01:53 -07:00
|
|
|
} // namespace opts
|
|
|
|
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
namespace llvm {
|
|
|
|
namespace bolt {
|
|
|
|
|
2018-09-24 20:58:31 -07:00
|
|
|
BinaryContext::BinaryContext(std::unique_ptr<MCContext> Ctx,
|
|
|
|
std::unique_ptr<DWARFContext> DwCtx,
|
|
|
|
std::unique_ptr<Triple> TheTriple,
|
|
|
|
const Target *TheTarget,
|
|
|
|
std::string TripleName,
|
|
|
|
std::unique_ptr<MCCodeEmitter> MCE,
|
|
|
|
std::unique_ptr<MCObjectFileInfo> MOFI,
|
|
|
|
std::unique_ptr<const MCAsmInfo> AsmInfo,
|
|
|
|
std::unique_ptr<const MCInstrInfo> MII,
|
|
|
|
std::unique_ptr<const MCSubtargetInfo> STI,
|
|
|
|
std::unique_ptr<MCInstPrinter> InstPrinter,
|
|
|
|
std::unique_ptr<const MCInstrAnalysis> MIA,
|
|
|
|
std::unique_ptr<MCPlusBuilder> MIB,
|
|
|
|
std::unique_ptr<const MCRegisterInfo> MRI,
|
2020-05-07 23:00:29 -07:00
|
|
|
std::unique_ptr<MCDisassembler> DisAsm)
|
2018-09-24 20:58:31 -07:00
|
|
|
: Ctx(std::move(Ctx)),
|
|
|
|
DwCtx(std::move(DwCtx)),
|
|
|
|
TheTriple(std::move(TheTriple)),
|
|
|
|
TheTarget(TheTarget),
|
|
|
|
TripleName(TripleName),
|
|
|
|
MCE(std::move(MCE)),
|
|
|
|
MOFI(std::move(MOFI)),
|
|
|
|
AsmInfo(std::move(AsmInfo)),
|
|
|
|
MII(std::move(MII)),
|
|
|
|
STI(std::move(STI)),
|
|
|
|
InstPrinter(std::move(InstPrinter)),
|
|
|
|
MIA(std::move(MIA)),
|
|
|
|
MIB(std::move(MIB)),
|
|
|
|
MRI(std::move(MRI)),
|
2020-05-07 23:00:29 -07:00
|
|
|
DisAsm(std::move(DisAsm)) {
|
2018-09-24 20:58:31 -07:00
|
|
|
Relocation::Arch = this->TheTriple->getArch();
|
|
|
|
PageAlign = opts::NoHugePages ? RegularPageSize : HugePageSize;
|
|
|
|
}
|
|
|
|
|
2018-02-01 16:33:43 -08:00
|
|
|
BinaryContext::~BinaryContext() {
|
2021-04-08 00:19:26 -07:00
|
|
|
for (BinarySection *Section : Sections) {
|
2018-02-01 16:33:43 -08:00
|
|
|
delete Section;
|
|
|
|
}
|
2021-04-08 00:19:26 -07:00
|
|
|
for (BinaryFunction *InjectedFunction : InjectedBinaryFunctions) {
|
2018-07-08 12:14:08 -07:00
|
|
|
delete InjectedFunction;
|
|
|
|
}
|
2021-04-08 00:19:26 -07:00
|
|
|
for (std::pair<const uint64_t, JumpTable *> JTI : JumpTables) {
|
2019-06-28 09:21:27 -07:00
|
|
|
delete JTI.second;
|
|
|
|
}
|
2017-11-14 20:05:11 -08:00
|
|
|
clearBinaryData();
|
2018-02-01 16:33:43 -08:00
|
|
|
}
|
2016-03-28 17:45:22 -07:00
|
|
|
|
2020-01-15 15:23:45 -08:00
|
|
|
extern MCPlusBuilder *createX86MCPlusBuilder(const MCInstrAnalysis *,
|
|
|
|
const MCInstrInfo *,
|
|
|
|
const MCRegisterInfo *);
|
|
|
|
extern MCPlusBuilder *createAArch64MCPlusBuilder(const MCInstrAnalysis *,
|
|
|
|
const MCInstrInfo *,
|
|
|
|
const MCRegisterInfo *);
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
|
|
|
MCPlusBuilder *createMCPlusBuilder(const Triple::ArchType Arch,
|
|
|
|
const MCInstrAnalysis *Analysis,
|
|
|
|
const MCInstrInfo *Info,
|
|
|
|
const MCRegisterInfo *RegInfo) {
|
|
|
|
#ifdef X86_AVAILABLE
|
|
|
|
if (Arch == Triple::x86_64)
|
|
|
|
return createX86MCPlusBuilder(Analysis, Info, RegInfo);
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#ifdef AARCH64_AVAILABLE
|
|
|
|
if (Arch == Triple::aarch64)
|
|
|
|
return createAArch64MCPlusBuilder(Analysis, Info, RegInfo);
|
|
|
|
#endif
|
|
|
|
|
|
|
|
llvm_unreachable("architecture unsupport by MCPlusBuilder");
|
|
|
|
}
|
|
|
|
|
|
|
|
} // anonymous namespace
|
|
|
|
|
|
|
|
/// Create BinaryContext for a given architecture \p ArchName and
|
|
|
|
/// triple \p TripleName.
|
|
|
|
std::unique_ptr<BinaryContext>
|
2020-11-04 11:44:02 -08:00
|
|
|
BinaryContext::createBinaryContext(ObjectFile *File, bool IsPIC,
|
2020-01-15 15:23:45 -08:00
|
|
|
std::unique_ptr<DWARFContext> DwCtx) {
|
|
|
|
StringRef ArchName = "";
|
|
|
|
StringRef FeaturesStr = "";
|
|
|
|
switch (File->getArch()) {
|
|
|
|
case llvm::Triple::x86_64:
|
|
|
|
ArchName = "x86-64";
|
2020-02-19 16:13:58 -08:00
|
|
|
FeaturesStr = "+nopl";
|
2020-01-15 15:23:45 -08:00
|
|
|
break;
|
|
|
|
case llvm::Triple::aarch64:
|
|
|
|
ArchName = "aarch64";
|
|
|
|
FeaturesStr = "+fp-armv8,+neon,+crypto,+dotprod,+crc,+lse,+ras,+rdm,"
|
|
|
|
"+fullfp16,+spe,+fuse-aes,+rcpc";
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
errs() << "BOLT-ERROR: Unrecognized machine in ELF file.\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
auto TheTriple = std::make_unique<Triple>(File->makeTriple());
|
2020-10-30 15:11:52 -07:00
|
|
|
const std::string TripleName = TheTriple->str();
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
std::string Error;
|
|
|
|
const Target *TheTarget =
|
2020-12-01 16:29:39 -08:00
|
|
|
TargetRegistry::lookupTarget(std::string(ArchName), *TheTriple, Error);
|
2020-01-15 15:23:45 -08:00
|
|
|
if (!TheTarget) {
|
|
|
|
errs() << "BOLT-ERROR: " << Error;
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<const MCRegisterInfo> MRI(
|
|
|
|
TheTarget->createMCRegInfo(TripleName));
|
|
|
|
if (!MRI) {
|
|
|
|
errs() << "BOLT-ERROR: no register info for target " << TripleName << "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set up disassembler.
|
|
|
|
std::unique_ptr<const MCAsmInfo> AsmInfo(
|
2020-12-01 16:29:39 -08:00
|
|
|
TheTarget->createMCAsmInfo(*MRI, TripleName, MCTargetOptions()));
|
2020-01-15 15:23:45 -08:00
|
|
|
if (!AsmInfo) {
|
|
|
|
errs() << "BOLT-ERROR: no assembly info for target " << TripleName << "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<const MCSubtargetInfo> STI(
|
|
|
|
TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
|
|
|
|
if (!STI) {
|
|
|
|
errs() << "BOLT-ERROR: no subtarget info for target " << TripleName << "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
|
|
|
|
if (!MII) {
|
|
|
|
errs() << "BOLT-ERROR: no instruction info for target " << TripleName
|
|
|
|
<< "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
std::unique_ptr<MCContext> Ctx(
|
|
|
|
new MCContext(*TheTriple, AsmInfo.get(), MRI.get(), STI.get()));
|
|
|
|
std::unique_ptr<MCObjectFileInfo> MOFI(
|
|
|
|
TheTarget->createMCObjectFileInfo(*Ctx, IsPIC));
|
|
|
|
Ctx->setObjectFileInfo(MOFI.get());
|
|
|
|
// We do not support X86 Large code model. Change this in the future.
|
|
|
|
bool Large = false;
|
|
|
|
if (TheTriple->getArch() == llvm::Triple::aarch64)
|
|
|
|
Large = true;
|
|
|
|
unsigned LSDAEncoding =
|
|
|
|
Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
|
|
|
|
unsigned TTypeEncoding =
|
|
|
|
Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
|
|
|
|
if (IsPIC) {
|
|
|
|
LSDAEncoding = dwarf::DW_EH_PE_pcrel |
|
|
|
|
(Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
|
|
|
|
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
|
|
|
|
(Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
|
|
|
|
}
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
std::unique_ptr<MCDisassembler> DisAsm(
|
|
|
|
TheTarget->createMCDisassembler(*STI, *Ctx));
|
|
|
|
|
|
|
|
if (!DisAsm) {
|
|
|
|
errs() << "BOLT-ERROR: no disassembler for target " << TripleName << "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<const MCInstrAnalysis> MIA(
|
|
|
|
TheTarget->createMCInstrAnalysis(MII.get()));
|
|
|
|
if (!MIA) {
|
|
|
|
errs() << "BOLT-ERROR: failed to create instruction analysis for target"
|
|
|
|
<< TripleName << "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<MCPlusBuilder> MIB(createMCPlusBuilder(
|
|
|
|
TheTriple->getArch(), MIA.get(), MII.get(), MRI.get()));
|
|
|
|
if (!MIB) {
|
|
|
|
errs() << "BOLT-ERROR: failed to create instruction builder for target"
|
|
|
|
<< TripleName << "\n";
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
|
|
|
|
std::unique_ptr<MCInstPrinter> InstructionPrinter(
|
|
|
|
TheTarget->createMCInstPrinter(*TheTriple, AsmPrinterVariant, *AsmInfo,
|
|
|
|
*MII, *MRI));
|
|
|
|
if (!InstructionPrinter) {
|
|
|
|
errs() << "BOLT-ERROR: no instruction printer for target " << TripleName
|
|
|
|
<< '\n';
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
InstructionPrinter->setPrintImmHex(true);
|
|
|
|
|
|
|
|
std::unique_ptr<MCCodeEmitter> MCE(
|
|
|
|
TheTarget->createMCCodeEmitter(*MII, *MRI, *Ctx));
|
|
|
|
|
|
|
|
// Make sure we don't miss any output on core dumps.
|
|
|
|
outs().SetUnbuffered();
|
|
|
|
errs().SetUnbuffered();
|
|
|
|
dbgs().SetUnbuffered();
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
auto BC = std::make_unique<BinaryContext>(
|
2020-01-15 15:23:45 -08:00
|
|
|
std::move(Ctx), std::move(DwCtx), std::move(TheTriple), TheTarget,
|
2020-12-01 16:29:39 -08:00
|
|
|
std::string(TripleName), std::move(MCE), std::move(MOFI),
|
|
|
|
std::move(AsmInfo), std::move(MII), std::move(STI),
|
|
|
|
std::move(InstructionPrinter), std::move(MIA), std::move(MIB),
|
|
|
|
std::move(MRI), std::move(DisAsm));
|
|
|
|
|
|
|
|
BC->TTypeEncoding = TTypeEncoding;
|
|
|
|
BC->LSDAEncoding = LSDAEncoding;
|
2020-05-07 23:00:29 -07:00
|
|
|
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
BC->MAB = std::unique_ptr<MCAsmBackend>(
|
|
|
|
BC->TheTarget->createMCAsmBackend(*BC->STI, *BC->MRI, MCTargetOptions()));
|
|
|
|
|
2020-05-07 23:00:29 -07:00
|
|
|
BC->setFilename(File->getFileName());
|
2020-01-15 15:23:45 -08:00
|
|
|
|
2020-11-04 11:44:02 -08:00
|
|
|
BC->HasFixedLoadAddress = !IsPIC;
|
|
|
|
|
2020-01-15 15:23:45 -08:00
|
|
|
return BC;
|
|
|
|
}
|
|
|
|
|
2020-06-18 11:10:41 -07:00
|
|
|
bool BinaryContext::forceSymbolRelocations(StringRef SymbolName) const {
|
|
|
|
if (opts::HotText && (SymbolName == "__hot_start" ||
|
|
|
|
SymbolName == "__hot_end"))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (opts::HotData && (SymbolName == "__hot_data_start" ||
|
|
|
|
SymbolName == "__hot_data_end"))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (SymbolName == "_end")
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
[BOLT rebase] Rebase fixes on top of LLVM Feb2018
Summary:
This commit includes all code necessary to make BOLT working again
after the rebase. This includes a redesign of the EHFrame work,
cherry-pick of the 3dnow disassembly work, compilation error fixes,
and port of the debug_info work. The macroop fusion feature is not
ported yet.
The rebased version has minor changes to the "executed instructions"
dynostats counter because REP prefixes are considered a part of the
instruction it applies to. Also, some X86 instructions had the "mayLoad"
tablegen property removed, which BOLT uses to identify and account
for loads, thus reducing the total number of loads reported by
dynostats. This was observed in X86::MOVDQUmr. TRAP instructions are
not terminators anymore, changing our CFG. This commit adds compensation
to preserve this old behavior and minimize tests changes. debug_info
sections are now slightly larger. The discriminator field in the line
table is slightly different due to a change upstream. New profiles
generated with the other bolt are incompatible with this version
because of different hash values calculated for functions, so they will
be considered 100% stale. This commit changes the corresponding test
to XFAIL so it can be updated. The hash function changes because it
relies on raw opcode values, which change according to the opcodes
described in the X86 tablegen files. When processing HHVM, bolt was
observed to be using about 800MB more memory in the rebased version
and being about 5% slower.
(cherry picked from FBD7078072)
2018-02-06 15:00:23 -08:00
|
|
|
std::unique_ptr<MCObjectWriter>
|
|
|
|
BinaryContext::createObjectWriter(raw_pwrite_stream &OS) {
|
2017-05-16 09:27:34 -07:00
|
|
|
return MAB->createObjectWriter(OS);
|
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
bool BinaryContext::validateObjectNesting() const {
|
|
|
|
auto Itr = BinaryDataMap.begin();
|
|
|
|
auto End = BinaryDataMap.end();
|
|
|
|
bool Valid = true;
|
|
|
|
while (Itr != End) {
|
|
|
|
auto Next = std::next(Itr);
|
|
|
|
while (Next != End &&
|
|
|
|
Itr->second->getSection() == Next->second->getSection() &&
|
|
|
|
Itr->second->containsRange(Next->second->getAddress(),
|
|
|
|
Next->second->getSize())) {
|
|
|
|
if (Next->second->Parent != Itr->second) {
|
|
|
|
errs() << "BOLT-WARNING: object nesting incorrect for:\n"
|
|
|
|
<< "BOLT-WARNING: " << *Itr->second << "\n"
|
|
|
|
<< "BOLT-WARNING: " << *Next->second << "\n";
|
|
|
|
Valid = false;
|
|
|
|
}
|
|
|
|
++Next;
|
|
|
|
}
|
|
|
|
Itr = Next;
|
|
|
|
}
|
|
|
|
return Valid;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool BinaryContext::validateHoles() const {
|
|
|
|
bool Valid = true;
|
2021-04-08 00:19:26 -07:00
|
|
|
for (BinarySection &Section : sections()) {
|
|
|
|
for (const Relocation &Rel : Section.relocations()) {
|
|
|
|
uint64_t RelAddr = Rel.Offset + Section.getAddress();
|
|
|
|
const BinaryData *BD = getBinaryDataContainingAddress(RelAddr);
|
2017-11-14 20:05:11 -08:00
|
|
|
if (!BD) {
|
|
|
|
errs() << "BOLT-WARNING: no BinaryData found for relocation at address"
|
|
|
|
<< " 0x" << Twine::utohexstr(RelAddr) << " in "
|
|
|
|
<< Section.getName() << "\n";
|
|
|
|
Valid = false;
|
|
|
|
} else if (!BD->getAtomicRoot()) {
|
|
|
|
errs() << "BOLT-WARNING: no atomic BinaryData found for relocation at "
|
|
|
|
<< "address 0x" << Twine::utohexstr(RelAddr) << " in "
|
|
|
|
<< Section.getName() << "\n";
|
|
|
|
Valid = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Valid;
|
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::updateObjectNesting(BinaryDataMapType::iterator GAI) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t Address = GAI->second->getAddress();
|
|
|
|
const uint64_t Size = GAI->second->getSize();
|
2017-11-14 20:05:11 -08:00
|
|
|
|
|
|
|
auto fixParents =
|
|
|
|
[&](BinaryDataMapType::iterator Itr, BinaryData *NewParent) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *OldParent = Itr->second->Parent;
|
2018-06-06 03:17:32 -07:00
|
|
|
Itr->second->Parent = NewParent;
|
|
|
|
++Itr;
|
|
|
|
while (Itr != BinaryDataMap.end() && OldParent &&
|
|
|
|
Itr->second->Parent == OldParent) {
|
2017-11-14 20:05:11 -08:00
|
|
|
Itr->second->Parent = NewParent;
|
|
|
|
++Itr;
|
2018-06-06 03:17:32 -07:00
|
|
|
}
|
2017-11-14 20:05:11 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Check if the previous symbol contains the newly added symbol.
|
|
|
|
if (GAI != BinaryDataMap.begin()) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *Prev = std::prev(GAI)->second;
|
2017-11-14 20:05:11 -08:00
|
|
|
while (Prev) {
|
|
|
|
if (Prev->getSection() == GAI->second->getSection() &&
|
|
|
|
Prev->containsRange(Address, Size)) {
|
|
|
|
fixParents(GAI, Prev);
|
|
|
|
} else {
|
|
|
|
fixParents(GAI, nullptr);
|
|
|
|
}
|
|
|
|
Prev = Prev->Parent;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the newly added symbol contains any subsequent symbols.
|
|
|
|
if (Size != 0) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *BD = GAI->second->Parent ? GAI->second->Parent : GAI->second;
|
2017-11-14 20:05:11 -08:00
|
|
|
auto Itr = std::next(GAI);
|
|
|
|
while (Itr != BinaryDataMap.end() &&
|
|
|
|
BD->containsRange(Itr->second->getAddress(),
|
2018-07-30 16:30:18 -07:00
|
|
|
Itr->second->getSize())) {
|
2017-11-14 20:05:11 -08:00
|
|
|
Itr->second->Parent = BD;
|
|
|
|
++Itr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-20 20:03:31 -07:00
|
|
|
iterator_range<BinaryContext::binary_data_iterator>
|
|
|
|
BinaryContext::getSubBinaryData(BinaryData *BD) {
|
|
|
|
auto Start = std::next(BinaryDataMap.find(BD->getAddress()));
|
|
|
|
auto End = Start;
|
|
|
|
while (End != BinaryDataMap.end() &&
|
|
|
|
BD->isAncestorOf(End->second)) {
|
|
|
|
++End;
|
|
|
|
}
|
|
|
|
return make_range(Start, End);
|
|
|
|
}
|
|
|
|
|
2019-06-28 09:21:27 -07:00
|
|
|
std::pair<const MCSymbol *, uint64_t>
|
|
|
|
BinaryContext::handleAddressRef(uint64_t Address, BinaryFunction &BF,
|
|
|
|
bool IsPCRel) {
|
2019-06-04 15:30:22 -07:00
|
|
|
uint64_t Addend{0};
|
|
|
|
|
|
|
|
if (isAArch64()) {
|
|
|
|
// Check if this is an access to a constant island and create bookkeeping
|
|
|
|
// to keep track of it and emit it later as part of this function.
|
2019-06-28 09:21:27 -07:00
|
|
|
if (MCSymbol *IslandSym = BF.getOrCreateIslandAccess(Address))
|
2019-06-04 15:30:22 -07:00
|
|
|
return std::make_pair(IslandSym, Addend);
|
2019-06-28 09:21:27 -07:00
|
|
|
|
|
|
|
// Detect custom code written in assembly that refers to arbitrary
|
|
|
|
// constant islands from other functions. Write this reference so we
|
|
|
|
// can pull this constant island and emit it as part of this function
|
|
|
|
// too.
|
|
|
|
auto IslandIter = AddressToConstantIslandMap.lower_bound(Address);
|
|
|
|
if (IslandIter != AddressToConstantIslandMap.end()) {
|
2021-04-08 00:19:26 -07:00
|
|
|
if (MCSymbol *IslandSym =
|
2019-06-28 09:21:27 -07:00
|
|
|
IslandIter->second->getOrCreateProxyIslandAccess(Address, BF)) {
|
|
|
|
/// Make this function depend on IslandIter->second because we have
|
|
|
|
/// a reference to its constant island. When emitting this function,
|
|
|
|
/// we will also emit IslandIter->second's constants. This only
|
|
|
|
/// happens in custom AArch64 assembly code.
|
2020-03-06 15:06:37 -08:00
|
|
|
BF.Islands.Dependency.insert(IslandIter->second);
|
|
|
|
BF.Islands.ProxySymbols[IslandSym] = IslandIter->second;
|
2019-06-28 09:21:27 -07:00
|
|
|
return std::make_pair(IslandSym, Addend);
|
2019-06-04 15:30:22 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Note that the address does not necessarily have to reside inside
|
|
|
|
// a section, it could be an absolute address too.
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2019-06-04 15:30:22 -07:00
|
|
|
if (Section && Section->isText()) {
|
|
|
|
if (BF.containsAddress(Address, /*UseMaxSize=*/ isAArch64())) {
|
|
|
|
if (Address != BF.getAddress()) {
|
|
|
|
// The address could potentially escape. Mark it as another entry
|
|
|
|
// point into the function.
|
|
|
|
if (opts::Verbosity >= 1) {
|
|
|
|
outs() << "BOLT-INFO: potentially escaped address 0x"
|
|
|
|
<< Twine::utohexstr(Address) << " in function "
|
|
|
|
<< BF << '\n';
|
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
BF.HasInternalLabelReference = true;
|
2019-06-04 15:30:22 -07:00
|
|
|
return std::make_pair(
|
|
|
|
BF.addEntryPointAtOffset(Address - BF.getAddress()),
|
|
|
|
Addend);
|
|
|
|
}
|
|
|
|
} else {
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
BF.InterproceduralReferences.insert(Address);
|
2019-06-04 15:30:22 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-26 17:51:07 -07:00
|
|
|
// With relocations, catch jump table references outside of the basic block
|
|
|
|
// containing the indirect jump.
|
|
|
|
if (HasRelocations) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const MemoryContentsType MemType = analyzeMemoryAt(Address, BF);
|
2019-08-19 14:06:36 -07:00
|
|
|
if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE && IsPCRel) {
|
|
|
|
const MCSymbol *Symbol =
|
|
|
|
getOrCreateJumpTable(BF, Address, JumpTable::JTT_PIC);
|
|
|
|
|
|
|
|
return std::make_pair(Symbol, Addend);
|
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
}
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
if (BinaryData *BD = getBinaryDataContainingAddress(Address)) {
|
2019-06-04 15:30:22 -07:00
|
|
|
return std::make_pair(BD->getSymbol(), Address - BD->getAddress());
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: use DWARF info to get size/alignment here?
|
2021-04-08 00:19:26 -07:00
|
|
|
MCSymbol *TargetSymbol = getOrCreateGlobalSymbol(Address, "DATAat");
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "Created symbol " << TargetSymbol->getName() << '\n');
|
2019-06-04 15:30:22 -07:00
|
|
|
return std::make_pair(TargetSymbol, Addend);
|
|
|
|
}
|
|
|
|
|
2019-06-12 18:21:02 -07:00
|
|
|
MemoryContentsType
|
|
|
|
BinaryContext::analyzeMemoryAt(uint64_t Address, BinaryFunction &BF) {
|
|
|
|
if (!isX86())
|
|
|
|
return MemoryContentsType::UNKNOWN;
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2019-06-12 18:21:02 -07:00
|
|
|
if (!Section) {
|
|
|
|
// No section - possibly an absolute address. Since we don't allow
|
|
|
|
// internal function addresses to escape the function scope - we
|
|
|
|
// consider it a tail call.
|
|
|
|
if (opts::Verbosity > 1) {
|
|
|
|
errs() << "BOLT-WARNING: no section for address 0x"
|
|
|
|
<< Twine::utohexstr(Address) << " referenced from function "
|
|
|
|
<< BF << '\n';
|
|
|
|
}
|
|
|
|
return MemoryContentsType::UNKNOWN;
|
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
|
2019-06-12 18:21:02 -07:00
|
|
|
if (Section->isVirtual()) {
|
|
|
|
// The contents are filled at runtime.
|
|
|
|
return MemoryContentsType::UNKNOWN;
|
|
|
|
}
|
|
|
|
|
2019-06-28 09:21:27 -07:00
|
|
|
// No support for jump tables in code yet.
|
|
|
|
if (Section->isText())
|
|
|
|
return MemoryContentsType::UNKNOWN;
|
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
// Start with checking for PIC jump table. We expect non-PIC jump tables
|
|
|
|
// to have high 32 bits set to 0.
|
|
|
|
if (analyzeJumpTable(Address, JumpTable::JTT_PIC, BF))
|
|
|
|
return MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
if (analyzeJumpTable(Address, JumpTable::JTT_NORMAL, BF))
|
|
|
|
return MemoryContentsType::POSSIBLE_JUMP_TABLE;
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
return MemoryContentsType::UNKNOWN;
|
|
|
|
}
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
bool BinaryContext::analyzeJumpTable(const uint64_t Address,
|
|
|
|
const JumpTable::JumpTableType Type,
|
2020-11-06 11:19:03 -08:00
|
|
|
BinaryFunction &BF,
|
2019-08-19 14:06:36 -07:00
|
|
|
const uint64_t NextJTAddress,
|
|
|
|
JumpTable::OffsetsType *Offsets) {
|
|
|
|
// Is one of the targets __builtin_unreachable?
|
|
|
|
bool HasUnreachable{false};
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
// Number of targets other than __builtin_unreachable.
|
|
|
|
uint64_t NumRealEntries{0};
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2020-11-12 11:54:44 -08:00
|
|
|
constexpr uint64_t INVALID_OFFSET = std::numeric_limits<uint64_t>::max();
|
2019-08-19 14:06:36 -07:00
|
|
|
auto addOffset = [&](uint64_t Offset) {
|
|
|
|
if (Offsets)
|
|
|
|
Offsets->emplace_back(Offset);
|
|
|
|
};
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2020-11-12 11:54:51 -08:00
|
|
|
auto isFragment = [](BinaryFunction &Fragment,
|
|
|
|
BinaryFunction &Parent) -> bool {
|
|
|
|
// Check if <fragment restored name> == <parent restored name>.cold(.\d+)?
|
2021-04-08 00:19:26 -07:00
|
|
|
for (StringRef BFName : Parent.getNames()) {
|
|
|
|
std::string BFNamePrefix = Regex::escape(NameResolver::restore(BFName));
|
|
|
|
std::string BFNameRegex =
|
|
|
|
Twine(BFNamePrefix, "\\.cold(\\.[0-9]+)?").str();
|
2020-11-12 11:54:51 -08:00
|
|
|
if (Fragment.hasRestoredNameRegex(BFNameRegex))
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
2020-11-06 11:19:03 -08:00
|
|
|
auto doesBelongToFunction = [&](const uint64_t Addr,
|
|
|
|
BinaryFunction *TargetBF) -> bool {
|
|
|
|
if (BF.containsAddress(Addr))
|
|
|
|
return true;
|
2020-11-12 11:54:51 -08:00
|
|
|
// Nothing to do if we failed to identify the containing function.
|
|
|
|
if (!TargetBF)
|
2020-11-06 11:19:03 -08:00
|
|
|
return false;
|
2020-11-12 11:54:51 -08:00
|
|
|
// Case 1: check if BF is a fragment and TargetBF is its parent.
|
|
|
|
if (BF.isFragment()) {
|
|
|
|
// BF is a fragment, but parent function is not registered.
|
|
|
|
// This means there's no direct jump between parent and fragment.
|
|
|
|
// Set parent link here in jump table analysis, based on function name
|
|
|
|
// matching heuristic.
|
|
|
|
if (!BF.getParentFragment() && isFragment(BF, *TargetBF))
|
|
|
|
registerFragment(BF, *TargetBF);
|
|
|
|
return BF.getParentFragment() == TargetBF;
|
|
|
|
}
|
|
|
|
// Case 2: check if TargetBF is a fragment and BF is its parent.
|
|
|
|
if (TargetBF->isFragment()) {
|
2020-11-06 11:19:03 -08:00
|
|
|
// TargetBF is a fragment, but parent function is not registered.
|
|
|
|
// This means there's no direct jump between parent and fragment.
|
|
|
|
// Set parent link here in jump table analysis, based on function name
|
2020-11-12 11:54:51 -08:00
|
|
|
// matching heuristic.
|
|
|
|
if (!TargetBF->getParentFragment() && isFragment(*TargetBF, BF))
|
|
|
|
registerFragment(*TargetBF, BF);
|
|
|
|
return TargetBF->getParentFragment() == &BF;
|
2020-11-06 11:19:03 -08:00
|
|
|
}
|
2020-11-12 11:54:51 -08:00
|
|
|
return false;
|
2020-11-06 11:19:03 -08:00
|
|
|
};
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2019-08-19 14:06:36 -07:00
|
|
|
if (!Section)
|
2019-06-12 18:21:02 -07:00
|
|
|
return false;
|
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
// The upper bound is defined by containing object, section limits, and
|
|
|
|
// the next jump table in memory.
|
2021-04-08 00:19:26 -07:00
|
|
|
uint64_t UpperBound = Section->getEndAddress();
|
|
|
|
const BinaryData *JumpTableBD = getBinaryDataAtAddress(Address);
|
2019-08-19 14:06:36 -07:00
|
|
|
if (JumpTableBD && JumpTableBD->getSize()) {
|
|
|
|
assert(JumpTableBD->getEndAddress() <= UpperBound &&
|
|
|
|
"data object cannot cross a section boundary");
|
|
|
|
UpperBound = JumpTableBD->getEndAddress();
|
|
|
|
}
|
|
|
|
if (NextJTAddress) {
|
|
|
|
UpperBound = std::min(NextJTAddress, UpperBound);
|
|
|
|
}
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: analyzeJumpTable in " << BF.getPrintName()
|
|
|
|
<< '\n');
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t EntrySize = getJumpTableEntrySize(Type);
|
|
|
|
for (uint64_t EntryAddress = Address; EntryAddress <= UpperBound - EntrySize;
|
2019-08-19 14:06:36 -07:00
|
|
|
EntryAddress += EntrySize) {
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << " * Checking 0x" << Twine::utohexstr(EntryAddress)
|
|
|
|
<< " -> ");
|
2019-08-19 14:06:36 -07:00
|
|
|
// Check if there's a proper relocation against the jump table entry.
|
2019-11-19 18:52:08 -08:00
|
|
|
if (HasRelocations) {
|
2020-11-12 11:54:38 -08:00
|
|
|
if (Type == JumpTable::JTT_PIC &&
|
|
|
|
!DataPCRelocations.count(EntryAddress)) {
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(
|
2020-11-12 11:54:38 -08:00
|
|
|
dbgs() << "FAIL: JTT_PIC table, no relocation for this address\n");
|
2019-11-19 18:52:08 -08:00
|
|
|
break;
|
2020-11-12 11:54:38 -08:00
|
|
|
}
|
|
|
|
if (Type == JumpTable::JTT_NORMAL && !getRelocationAt(EntryAddress)) {
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs()
|
|
|
|
<< "FAIL: JTT_NORMAL table, no relocation for this address\n");
|
2019-11-19 18:52:08 -08:00
|
|
|
break;
|
2020-11-12 11:54:38 -08:00
|
|
|
}
|
2019-11-19 18:52:08 -08:00
|
|
|
}
|
2019-08-19 14:06:36 -07:00
|
|
|
|
|
|
|
const uint64_t Value = (Type == JumpTable::JTT_PIC)
|
|
|
|
? Address + *getSignedValueAtAddress(EntryAddress, EntrySize)
|
|
|
|
: *getPointerAtAddress(EntryAddress);
|
|
|
|
|
|
|
|
// __builtin_unreachable() case.
|
|
|
|
if (Value == BF.getAddress() + BF.getSize()) {
|
|
|
|
addOffset(Value - BF.getAddress());
|
|
|
|
HasUnreachable = true;
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "OK: __builtin_unreachable\n");
|
2019-08-19 14:06:36 -07:00
|
|
|
continue;
|
|
|
|
}
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2020-11-06 11:19:03 -08:00
|
|
|
// Function or one of its fragments.
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *TargetBF = getBinaryFunctionContainingAddress(Value);
|
2020-11-06 11:19:03 -08:00
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
// We assume that a jump table cannot have function start as an entry.
|
2020-11-12 11:54:38 -08:00
|
|
|
if (!doesBelongToFunction(Value, TargetBF) || Value == BF.getAddress()) {
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG({
|
2020-11-12 11:54:38 -08:00
|
|
|
if (!BF.containsAddress(Value)) {
|
|
|
|
dbgs() << "FAIL: function doesn't contain this address\n";
|
|
|
|
if (TargetBF) {
|
|
|
|
dbgs() << " ! function containing this address: "
|
|
|
|
<< TargetBF->getPrintName() << '\n';
|
|
|
|
if (TargetBF->isFragment())
|
|
|
|
dbgs() << " ! is a fragment\n";
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *TargetParent = TargetBF->getParentFragment();
|
2020-11-12 11:54:38 -08:00
|
|
|
dbgs() << " ! its parent is "
|
|
|
|
<< (TargetParent ? TargetParent->getPrintName() : "(none)")
|
|
|
|
<< '\n';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Value == BF.getAddress())
|
|
|
|
dbgs() << "FAIL: jump table cannot have function start as an entry\n";
|
|
|
|
});
|
2019-08-19 14:06:36 -07:00
|
|
|
break;
|
2020-11-12 11:54:38 -08:00
|
|
|
}
|
2019-08-19 14:06:36 -07:00
|
|
|
|
|
|
|
// Check there's an instruction at this offset.
|
2020-11-06 11:19:03 -08:00
|
|
|
if (TargetBF->getState() == BinaryFunction::State::Disassembled &&
|
|
|
|
!TargetBF->getInstructionAtOffset(Value - TargetBF->getAddress())) {
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "FAIL: no instruction at this offset\n");
|
2019-08-19 14:06:36 -07:00
|
|
|
break;
|
2020-11-06 11:19:03 -08:00
|
|
|
}
|
2019-08-19 14:06:36 -07:00
|
|
|
|
|
|
|
++NumRealEntries;
|
2020-11-06 11:19:03 -08:00
|
|
|
|
|
|
|
if (TargetBF == &BF) {
|
|
|
|
// Address inside the function.
|
|
|
|
addOffset(Value - TargetBF->getAddress());
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "OK: real entry\n");
|
2020-11-06 11:19:03 -08:00
|
|
|
} else {
|
|
|
|
// Address in split fragment.
|
|
|
|
BF.setHasSplitJumpTable(true);
|
2020-11-12 11:54:44 -08:00
|
|
|
// Add invalid offset for proper identification of jump table size.
|
|
|
|
addOffset(INVALID_OFFSET);
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "OK: address in split fragment\n");
|
2020-11-06 11:19:03 -08:00
|
|
|
}
|
2019-08-19 14:06:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// It's a jump table if the number of real entries is more than 1, or there's
|
|
|
|
// one real entry and "unreachable" targets. If there are only multiple
|
|
|
|
// "unreachable" targets, then it's not a jump table.
|
|
|
|
return NumRealEntries + HasUnreachable >= 2;
|
2019-06-12 18:21:02 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::populateJumpTables() {
|
2020-11-06 11:19:03 -08:00
|
|
|
std::vector<BinaryFunction *> FuncsToSkip;
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "DataPCRelocations: " << DataPCRelocations.size()
|
|
|
|
<< '\n');
|
2019-06-12 18:21:02 -07:00
|
|
|
for (auto JTI = JumpTables.begin(), JTE = JumpTables.end(); JTI != JTE;
|
|
|
|
++JTI) {
|
2021-04-08 00:19:26 -07:00
|
|
|
JumpTable *JT = JTI->second;
|
|
|
|
BinaryFunction &BF = *JT->Parent;
|
2019-06-12 18:21:02 -07:00
|
|
|
|
2019-11-10 21:09:01 -08:00
|
|
|
if (!BF.isSimple())
|
|
|
|
continue;
|
|
|
|
|
2019-08-19 14:06:36 -07:00
|
|
|
uint64_t NextJTAddress{0};
|
2019-06-12 18:21:02 -07:00
|
|
|
auto NextJTI = std::next(JTI);
|
|
|
|
if (NextJTI != JTE) {
|
2019-08-19 14:06:36 -07:00
|
|
|
NextJTAddress = NextJTI->second->getAddress();
|
2019-06-12 18:21:02 -07:00
|
|
|
}
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
const bool Success = analyzeJumpTable(JT->getAddress(), JT->Type, BF,
|
|
|
|
NextJTAddress, &JT->OffsetEntries);
|
2019-08-19 14:06:36 -07:00
|
|
|
if (!Success) {
|
|
|
|
dbgs() << "failed to analyze jump table in function " << BF << '\n';
|
2019-06-28 09:21:27 -07:00
|
|
|
JT->print(dbgs());
|
|
|
|
if (NextJTI != JTE) {
|
|
|
|
dbgs() << "next jump table at 0x"
|
|
|
|
<< Twine::utohexstr(NextJTI->second->getAddress())
|
|
|
|
<< " belongs to function " << *NextJTI->second->Parent << '\n';
|
|
|
|
NextJTI->second->print(dbgs());
|
|
|
|
}
|
2019-08-19 14:06:36 -07:00
|
|
|
llvm_unreachable("jump table heuristic failure");
|
2019-06-28 09:21:27 -07:00
|
|
|
}
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
for (uint64_t EntryOffset : JT->OffsetEntries) {
|
2019-08-19 14:06:36 -07:00
|
|
|
if (EntryOffset == BF.getSize())
|
|
|
|
BF.IgnoredBranches.emplace_back(EntryOffset, BF.getSize());
|
|
|
|
else
|
|
|
|
BF.registerReferencedOffset(EntryOffset);
|
|
|
|
}
|
|
|
|
|
|
|
|
// In strict mode, erase PC-relative relocation record. Later we check that
|
|
|
|
// all such records are erased and thus have been accounted for.
|
|
|
|
if (opts::StrictMode && JT->Type == JumpTable::JTT_PIC) {
|
2021-04-08 00:19:26 -07:00
|
|
|
for (uint64_t Address = JT->getAddress();
|
2019-06-28 09:21:27 -07:00
|
|
|
Address < JT->getAddress() + JT->getSize();
|
|
|
|
Address += JT->EntrySize) {
|
2019-11-19 18:52:08 -08:00
|
|
|
DataPCRelocations.erase(DataPCRelocations.find(Address));
|
2019-06-28 09:21:27 -07:00
|
|
|
}
|
|
|
|
}
|
2020-11-06 11:19:03 -08:00
|
|
|
|
|
|
|
// Mark to skip the function and all its fragments.
|
|
|
|
if (BF.hasSplitJumpTable())
|
|
|
|
FuncsToSkip.push_back(&BF);
|
2019-06-12 18:21:02 -07:00
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
|
2020-11-12 11:54:38 -08:00
|
|
|
if (opts::StrictMode && DataPCRelocations.size()) {
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG({
|
2020-11-12 11:54:38 -08:00
|
|
|
dbgs() << DataPCRelocations.size()
|
|
|
|
<< " unclaimed PC-relative relocations left in data:\n";
|
2021-04-08 00:19:26 -07:00
|
|
|
for (uint64_t Reloc : DataPCRelocations)
|
2020-11-12 11:54:38 -08:00
|
|
|
dbgs() << Twine::utohexstr(Reloc) << '\n';
|
|
|
|
});
|
|
|
|
assert(0 && "unclaimed PC-relative relocations left in data\n");
|
|
|
|
}
|
2019-11-19 18:52:08 -08:00
|
|
|
clearList(DataPCRelocations);
|
2020-11-06 11:19:03 -08:00
|
|
|
// Functions containing split jump tables need to be skipped with all
|
|
|
|
// fragments.
|
2021-04-08 00:19:26 -07:00
|
|
|
for (BinaryFunction *BF : FuncsToSkip) {
|
2020-11-12 11:54:51 -08:00
|
|
|
BinaryFunction *ParentBF =
|
|
|
|
const_cast<BinaryFunction *>(BF->getTopmostFragment());
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "Skipping " << ParentBF->getPrintName()
|
|
|
|
<< " family\n");
|
2020-11-12 11:54:51 -08:00
|
|
|
ParentBF->setIgnored();
|
|
|
|
ParentBF->ignoreFragments();
|
2020-11-06 11:19:03 -08:00
|
|
|
}
|
2019-06-12 18:21:02 -07:00
|
|
|
}
|
|
|
|
|
2015-10-14 15:35:14 -07:00
|
|
|
MCSymbol *BinaryContext::getOrCreateGlobalSymbol(uint64_t Address,
|
2018-09-21 12:00:20 -07:00
|
|
|
Twine Prefix,
|
2017-11-14 20:05:11 -08:00
|
|
|
uint64_t Size,
|
|
|
|
uint16_t Alignment,
|
2018-04-20 20:03:31 -07:00
|
|
|
unsigned Flags) {
|
2017-11-14 20:05:11 -08:00
|
|
|
auto Itr = BinaryDataMap.find(Address);
|
|
|
|
if (Itr != BinaryDataMap.end()) {
|
|
|
|
assert(Itr->second->getSize() == Size || !Size);
|
|
|
|
return Itr->second->getSymbol();
|
2015-10-14 15:35:14 -07:00
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
std::string Name = (Prefix + "0x" + Twine::utohexstr(Address)).str();
|
|
|
|
assert(!GlobalSymbols.count(Name) && "created name is not unique");
|
2018-04-20 20:03:31 -07:00
|
|
|
return registerNameAtAddress(Name, Address, Size, Alignment, Flags);
|
2017-11-14 20:05:11 -08:00
|
|
|
}
|
2015-10-14 15:35:14 -07:00
|
|
|
|
2019-04-03 15:52:01 -07:00
|
|
|
BinaryFunction *BinaryContext::createBinaryFunction(
|
|
|
|
const std::string &Name, BinarySection &Section, uint64_t Address,
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
uint64_t Size, uint64_t SymbolSize, uint16_t Alignment) {
|
2019-04-03 15:52:01 -07:00
|
|
|
auto Result = BinaryFunctions.emplace(
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
Address, BinaryFunction(Name, Section, Address, Size, *this));
|
2019-04-03 15:52:01 -07:00
|
|
|
assert(Result.second == true && "unexpected duplicate function");
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *BF = &Result.first->second;
|
2019-04-03 15:52:01 -07:00
|
|
|
registerNameAtAddress(Name, Address, SymbolSize ? SymbolSize : Size,
|
|
|
|
Alignment);
|
|
|
|
setSymbolToFunctionMap(BF->getSymbol(), BF);
|
|
|
|
return BF;
|
|
|
|
}
|
|
|
|
|
2019-07-02 16:56:41 -07:00
|
|
|
const MCSymbol *
|
|
|
|
BinaryContext::getOrCreateJumpTable(BinaryFunction &Function, uint64_t Address,
|
|
|
|
JumpTable::JumpTableType Type) {
|
2021-04-08 00:19:26 -07:00
|
|
|
if (JumpTable *JT = getJumpTableContainingAddress(Address)) {
|
2019-05-02 17:42:06 -07:00
|
|
|
assert(JT->Type == Type && "jump table types have to match");
|
|
|
|
assert(JT->Parent == &Function &&
|
|
|
|
"cannot re-use jump table of a different function");
|
2019-06-28 09:21:27 -07:00
|
|
|
assert(Address == JT->getAddress() && "unexpected non-empty jump table");
|
2019-05-02 17:42:06 -07:00
|
|
|
|
2019-07-02 16:56:41 -07:00
|
|
|
return JT->getFirstLabel();
|
2019-05-02 17:42:06 -07:00
|
|
|
}
|
|
|
|
|
2019-06-28 09:21:27 -07:00
|
|
|
// Re-use the existing symbol if possible.
|
|
|
|
MCSymbol *JTLabel{nullptr};
|
2021-04-08 00:19:26 -07:00
|
|
|
if (BinaryData *Object = getBinaryDataAtAddress(Address)) {
|
2019-06-28 09:21:27 -07:00
|
|
|
if (!isInternalSymbolName(Object->getSymbol()->getName()))
|
|
|
|
JTLabel = Object->getSymbol();
|
|
|
|
}
|
2019-08-19 14:06:36 -07:00
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t EntrySize = getJumpTableEntrySize(Type);
|
2019-06-28 09:21:27 -07:00
|
|
|
if (!JTLabel) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const std::string JumpTableName = generateJumpTableName(Function, Address);
|
2020-01-10 16:17:47 -08:00
|
|
|
JTLabel = registerNameAtAddress(JumpTableName, Address, 0, EntrySize);
|
2019-06-28 09:21:27 -07:00
|
|
|
}
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: creating jump table " << JTLabel->getName()
|
|
|
|
<< " in function " << Function << '\n');
|
2019-05-02 17:42:06 -07:00
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
JumpTable *JT = new JumpTable(*JTLabel, Address, EntrySize, Type,
|
|
|
|
JumpTable::LabelMapType{{0, JTLabel}}, Function,
|
|
|
|
*getSectionForAddress(Address));
|
2019-05-02 17:42:06 -07:00
|
|
|
JumpTables.emplace(Address, JT);
|
|
|
|
|
|
|
|
// Duplicate the entry for the parent function for easy access.
|
|
|
|
Function.JumpTables.emplace(Address, JT);
|
|
|
|
|
2019-07-02 16:56:41 -07:00
|
|
|
return JTLabel;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::pair<uint64_t, const MCSymbol *>
|
|
|
|
BinaryContext::duplicateJumpTable(BinaryFunction &Function, JumpTable *JT,
|
|
|
|
const MCSymbol *OldLabel) {
|
2019-08-07 16:09:50 -07:00
|
|
|
auto L = scopeLock();
|
2019-07-02 16:56:41 -07:00
|
|
|
unsigned Offset = 0;
|
|
|
|
bool Found = false;
|
2021-04-08 00:19:26 -07:00
|
|
|
for (std::pair<const unsigned, MCSymbol *> Elmt : JT->Labels) {
|
2019-07-02 16:56:41 -07:00
|
|
|
if (Elmt.second != OldLabel)
|
|
|
|
continue;
|
|
|
|
Offset = Elmt.first;
|
|
|
|
Found = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
assert(Found && "Label not found");
|
2021-04-08 00:19:26 -07:00
|
|
|
MCSymbol *NewLabel = Ctx->createNamedTempSymbol("duplicatedJT");
|
|
|
|
JumpTable *NewJT =
|
|
|
|
new JumpTable(*NewLabel, JT->getAddress(), JT->EntrySize, JT->Type,
|
|
|
|
JumpTable::LabelMapType{{Offset, NewLabel}}, Function,
|
|
|
|
*getSectionForAddress(JT->getAddress()));
|
2019-07-02 16:56:41 -07:00
|
|
|
NewJT->Entries = JT->Entries;
|
|
|
|
NewJT->Counts = JT->Counts;
|
|
|
|
uint64_t JumpTableID = ++DuplicatedJumpTables;
|
|
|
|
// Invert it to differentiate from regular jump tables whose IDs are their
|
|
|
|
// addresses in the input binary memory space
|
|
|
|
JumpTableID = ~JumpTableID;
|
|
|
|
JumpTables.emplace(JumpTableID, NewJT);
|
|
|
|
Function.JumpTables.emplace(JumpTableID, NewJT);
|
|
|
|
return std::make_pair(JumpTableID, NewLabel);
|
2019-05-02 17:42:06 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
std::string BinaryContext::generateJumpTableName(const BinaryFunction &BF,
|
|
|
|
uint64_t Address) {
|
|
|
|
size_t Id;
|
|
|
|
uint64_t Offset = 0;
|
2021-04-08 00:19:26 -07:00
|
|
|
if (const JumpTable *JT = BF.getJumpTableContainingAddress(Address)) {
|
2019-05-02 17:42:06 -07:00
|
|
|
Offset = Address - JT->getAddress();
|
|
|
|
auto Itr = JT->Labels.find(Offset);
|
|
|
|
if (Itr != JT->Labels.end()) {
|
2020-12-01 16:29:39 -08:00
|
|
|
return std::string(Itr->second->getName());
|
2019-05-02 17:42:06 -07:00
|
|
|
}
|
|
|
|
Id = JumpTableIds.at(JT->getAddress());
|
|
|
|
} else {
|
|
|
|
Id = JumpTableIds[Address] = BF.JumpTables.size();
|
|
|
|
}
|
2020-01-13 11:56:59 -08:00
|
|
|
return ("JUMP_TABLE/" + BF.getOneName().str() + "." + std::to_string(Id) +
|
2019-05-02 17:42:06 -07:00
|
|
|
(Offset ? ("." + std::to_string(Offset)) : ""));
|
|
|
|
}
|
|
|
|
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
bool BinaryContext::hasValidCodePadding(const BinaryFunction &BF) {
|
|
|
|
// FIXME: aarch64 support is missing.
|
|
|
|
if (!isX86())
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (BF.getSize() == BF.getMaxSize())
|
|
|
|
return true;
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<ArrayRef<unsigned char>> FunctionData = BF.getData();
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
assert(FunctionData && "cannot get function as data");
|
|
|
|
|
|
|
|
uint64_t Offset = BF.getSize();
|
|
|
|
MCInst Instr;
|
|
|
|
uint64_t InstrSize{0};
|
|
|
|
uint64_t InstrAddress = BF.getAddress() + Offset;
|
|
|
|
using std::placeholders::_1;
|
|
|
|
|
|
|
|
// Skip instructions that satisfy the predicate condition.
|
|
|
|
auto skipInstructions = [&](std::function<bool(const MCInst &)> Predicate) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t StartOffset = Offset;
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
for (; Offset < BF.getMaxSize();
|
|
|
|
Offset += InstrSize, InstrAddress += InstrSize) {
|
|
|
|
if (!DisAsm->getInstruction(Instr,
|
|
|
|
InstrSize,
|
|
|
|
FunctionData->slice(Offset),
|
|
|
|
InstrAddress,
|
|
|
|
nulls()))
|
|
|
|
break;
|
|
|
|
if (!Predicate(Instr))
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Offset - StartOffset;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Skip a sequence of zero bytes.
|
|
|
|
auto skipZeros = [&]() {
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t StartOffset = Offset;
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
for (; Offset < BF.getMaxSize(); ++Offset)
|
|
|
|
if ((*FunctionData)[Offset] != 0)
|
|
|
|
break;
|
|
|
|
|
|
|
|
return Offset - StartOffset;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Accept the whole padding area filled with breakpoints.
|
|
|
|
auto isBreakpoint = std::bind(&MCPlusBuilder::isBreakpoint, MIB.get(), _1);
|
|
|
|
if (skipInstructions(isBreakpoint) && Offset == BF.getMaxSize())
|
|
|
|
return true;
|
|
|
|
|
|
|
|
auto isNoop = std::bind(&MCPlusBuilder::isNoop, MIB.get(), _1);
|
|
|
|
|
|
|
|
// Some functions have a jump to the next function or to the padding area
|
|
|
|
// inserted after the body.
|
|
|
|
auto isSkipJump = [&](const MCInst &Instr) {
|
|
|
|
uint64_t TargetAddress{0};
|
|
|
|
if (MIB->isUnconditionalBranch(Instr) &&
|
|
|
|
MIB->evaluateBranch(Instr, InstrAddress, InstrSize, TargetAddress)) {
|
|
|
|
if (TargetAddress >= InstrAddress + InstrSize &&
|
|
|
|
TargetAddress <= BF.getAddress() + BF.getMaxSize()) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Skip over nops, jumps, and zero padding. Allow interleaving (this happens).
|
|
|
|
while (skipInstructions(isNoop) ||
|
|
|
|
skipInstructions(isSkipJump) ||
|
|
|
|
skipZeros())
|
|
|
|
;
|
|
|
|
|
|
|
|
if (Offset == BF.getMaxSize())
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (opts::Verbosity >= 1) {
|
|
|
|
errs() << "BOLT-WARNING: bad padding at address 0x"
|
|
|
|
<< Twine::utohexstr(BF.getAddress() + BF.getSize())
|
|
|
|
<< " starting at offset "
|
|
|
|
<< (Offset - BF.getSize()) << " in function "
|
2019-07-31 16:03:49 -07:00
|
|
|
<< BF << '\n'
|
|
|
|
<< FunctionData->slice(BF.getSize(), BF.getMaxSize() - BF.getSize())
|
|
|
|
<< '\n';
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::adjustCodePadding() {
|
|
|
|
for (auto &BFI : BinaryFunctions) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction &BF = BFI.second;
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
if (!shouldEmit(BF))
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
continue;
|
|
|
|
|
|
|
|
if (!hasValidCodePadding(BF)) {
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
if (HasRelocations) {
|
|
|
|
if (opts::Verbosity >= 1) {
|
|
|
|
outs() << "BOLT-INFO: function " << BF
|
|
|
|
<< " has invalid padding. Ignoring the function.\n";
|
|
|
|
}
|
|
|
|
BF.setIgnored();
|
|
|
|
} else {
|
|
|
|
BF.setMaxSize(BF.getSize());
|
|
|
|
}
|
[BOLT] Add code padding verification
Summary:
In non-relocation mode, we allow data objects to be embedded in the
code. Such objects could be unmarked, and could occupy an area between
functions, the area which is considered to be code padding.
When we disassemble code, we detect references into the padding area
and adjust it, so that it is not overwritten during the code emission.
We assume the reference to be pointing to the beginning of the object.
However, assembly-written functions may reference the middle of an
object and use negative offsets to reference data fields. Thus,
conservatively, we reduce the possibly-overwritten padding area to
a minimum if the object reference was detected.
Since we also allow functions with unknown code in non-relocation mode,
it is possible that we miss references to some objects in code.
To cover such cases, we need to verify the padding area before we
allow to overwrite it.
(cherry picked from FBD16477787)
2019-07-23 20:48:41 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
MCSymbol *BinaryContext::registerNameAtAddress(StringRef Name,
|
|
|
|
uint64_t Address,
|
|
|
|
uint64_t Size,
|
2018-04-20 20:03:31 -07:00
|
|
|
uint16_t Alignment,
|
|
|
|
unsigned Flags) {
|
2020-01-10 16:17:47 -08:00
|
|
|
// Register the name with MCContext.
|
2021-04-08 00:19:26 -07:00
|
|
|
MCSymbol *Symbol = Ctx->getOrCreateSymbol(Name);
|
2020-01-10 16:17:47 -08:00
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
auto GAI = BinaryDataMap.find(Address);
|
|
|
|
BinaryData *BD;
|
|
|
|
if (GAI == BinaryDataMap.end()) {
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> SectionOrErr = getSectionForAddress(Address);
|
|
|
|
BinarySection &Section =
|
|
|
|
SectionOrErr ? SectionOrErr.get() : absoluteSection();
|
2020-01-10 16:17:47 -08:00
|
|
|
BD = new BinaryData(*Symbol,
|
2017-11-14 20:05:11 -08:00
|
|
|
Address,
|
|
|
|
Size,
|
|
|
|
Alignment ? Alignment : 1,
|
2018-04-20 20:03:31 -07:00
|
|
|
Section,
|
|
|
|
Flags);
|
2017-11-14 20:05:11 -08:00
|
|
|
GAI = BinaryDataMap.emplace(Address, BD).first;
|
|
|
|
GlobalSymbols[Name] = BD;
|
|
|
|
updateObjectNesting(GAI);
|
2020-01-10 16:17:47 -08:00
|
|
|
} else {
|
|
|
|
BD = GAI->second;
|
|
|
|
if (!BD->hasName(Name)) {
|
|
|
|
GlobalSymbols[Name] = BD;
|
|
|
|
BD->Symbols.push_back(Symbol);
|
|
|
|
}
|
2017-11-14 20:05:11 -08:00
|
|
|
}
|
|
|
|
|
2015-10-14 15:35:14 -07:00
|
|
|
return Symbol;
|
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
const BinaryData *
|
2020-03-03 15:51:24 -08:00
|
|
|
BinaryContext::getBinaryDataContainingAddressImpl(uint64_t Address) const {
|
2017-11-14 20:05:11 -08:00
|
|
|
auto NI = BinaryDataMap.lower_bound(Address);
|
|
|
|
auto End = BinaryDataMap.end();
|
2020-03-03 15:51:24 -08:00
|
|
|
if ((NI != End && Address == NI->first) ||
|
2020-03-03 13:36:32 -08:00
|
|
|
((NI != BinaryDataMap.begin()) && (NI-- != BinaryDataMap.begin()))) {
|
2020-03-03 15:51:24 -08:00
|
|
|
if (NI->second->containsAddress(Address)) {
|
2017-11-14 20:05:11 -08:00
|
|
|
return NI->second;
|
|
|
|
}
|
2016-09-29 11:19:06 -07:00
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
// If this is a sub-symbol, see if a parent data contains the address.
|
2021-04-08 00:19:26 -07:00
|
|
|
const BinaryData *BD = NI->second->getParent();
|
2017-11-14 20:05:11 -08:00
|
|
|
while (BD) {
|
2020-03-03 15:51:24 -08:00
|
|
|
if (BD->containsAddress(Address))
|
2017-11-14 20:05:11 -08:00
|
|
|
return BD;
|
|
|
|
BD = BD->getParent();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nullptr;
|
|
|
|
}
|
2016-09-29 11:19:06 -07:00
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
bool BinaryContext::setBinaryDataSize(uint64_t Address, uint64_t Size) {
|
|
|
|
auto NI = BinaryDataMap.find(Address);
|
|
|
|
assert(NI != BinaryDataMap.end());
|
|
|
|
if (NI == BinaryDataMap.end())
|
|
|
|
return false;
|
2018-03-13 18:59:22 -07:00
|
|
|
// TODO: it's possible that a jump table starts at the same address
|
|
|
|
// as a larger blob of private data. When we set the size of the
|
|
|
|
// jump table, it might be smaller than the total blob size. In this
|
|
|
|
// case we just leave the original size since (currently) it won't really
|
|
|
|
// affect anything. See T26915981.
|
|
|
|
assert((!NI->second->Size || NI->second->Size == Size ||
|
|
|
|
(NI->second->isJumpTable() && NI->second->Size > Size)) &&
|
|
|
|
"can't change the size of a symbol that has already had its "
|
|
|
|
"size set");
|
|
|
|
if (!NI->second->Size) {
|
|
|
|
NI->second->Size = Size;
|
|
|
|
updateObjectNesting(NI);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
2016-09-29 11:19:06 -07:00
|
|
|
}
|
|
|
|
|
2018-06-06 03:17:32 -07:00
|
|
|
void BinaryContext::generateSymbolHashes() {
|
|
|
|
auto isPadding = [](const BinaryData &BD) {
|
2021-04-08 00:19:26 -07:00
|
|
|
StringRef Contents = BD.getSection().getContents();
|
|
|
|
StringRef SymData = Contents.substr(BD.getOffset(), BD.getSize());
|
2018-06-06 03:17:32 -07:00
|
|
|
return (BD.getName().startswith("HOLEat") ||
|
|
|
|
SymData.find_first_not_of(0) == StringRef::npos);
|
|
|
|
};
|
|
|
|
|
2018-06-11 17:17:25 -07:00
|
|
|
uint64_t NumCollisions = 0;
|
2018-06-06 03:17:32 -07:00
|
|
|
for (auto &Entry : BinaryDataMap) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData &BD = *Entry.second;
|
|
|
|
StringRef Name = BD.getName();
|
2018-06-06 03:17:32 -07:00
|
|
|
|
2019-06-28 09:21:27 -07:00
|
|
|
if (!isInternalSymbolName(Name))
|
2018-06-06 03:17:32 -07:00
|
|
|
continue;
|
|
|
|
|
|
|
|
// First check if a non-anonymous alias exists and move it to the front.
|
2020-01-10 16:17:47 -08:00
|
|
|
if (BD.getSymbols().size() > 1) {
|
|
|
|
auto Itr = std::find_if(BD.getSymbols().begin(),
|
|
|
|
BD.getSymbols().end(),
|
|
|
|
[&](const MCSymbol *Symbol) {
|
|
|
|
return !isInternalSymbolName(Symbol->getName());
|
2019-06-28 09:21:27 -07:00
|
|
|
});
|
2020-01-10 16:17:47 -08:00
|
|
|
if (Itr != BD.getSymbols().end()) {
|
2021-04-08 00:19:26 -07:00
|
|
|
size_t Idx = std::distance(BD.getSymbols().begin(), Itr);
|
2020-01-10 16:17:47 -08:00
|
|
|
std::swap(BD.getSymbols()[0], BD.getSymbols()[Idx]);
|
2018-06-06 03:17:32 -07:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We have to skip 0 size symbols since they will all collide.
|
|
|
|
if (BD.getSize() == 0) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t Hash = BD.getSection().hash(BD);
|
|
|
|
const size_t Idx = Name.find("0x");
|
2018-06-06 03:17:32 -07:00
|
|
|
std::string NewName = (Twine(Name.substr(0, Idx)) +
|
|
|
|
"_" + Twine::utohexstr(Hash)).str();
|
|
|
|
if (getBinaryDataByName(NewName)) {
|
|
|
|
// Ignore collisions for symbols that appear to be padding
|
|
|
|
// (i.e. all zeros or a "hole")
|
|
|
|
if (!isPadding(BD)) {
|
2018-06-11 17:17:25 -07:00
|
|
|
if (opts::Verbosity) {
|
|
|
|
errs() << "BOLT-WARNING: collision detected when hashing " << BD
|
|
|
|
<< " with new name (" << NewName << "), skipping.\n";
|
|
|
|
}
|
|
|
|
++NumCollisions;
|
2018-06-06 03:17:32 -07:00
|
|
|
}
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
BD.Symbols.insert(BD.Symbols.begin(),
|
|
|
|
Ctx->getOrCreateSymbol(NewName));
|
|
|
|
GlobalSymbols[NewName] = &BD;
|
|
|
|
}
|
2018-06-11 17:17:25 -07:00
|
|
|
if (NumCollisions) {
|
|
|
|
errs() << "BOLT-WARNING: " << NumCollisions
|
|
|
|
<< " collisions detected while hashing binary objects";
|
|
|
|
if (!opts::Verbosity)
|
|
|
|
errs() << ". Use -v=1 to see the list.";
|
|
|
|
errs() << '\n';
|
|
|
|
}
|
2018-06-06 03:17:32 -07:00
|
|
|
}
|
|
|
|
|
2020-11-06 10:27:33 -08:00
|
|
|
void BinaryContext::registerFragment(BinaryFunction &TargetFunction,
|
|
|
|
BinaryFunction &Function) const {
|
|
|
|
// Only a parent function (or a sibling) can reach its fragment.
|
|
|
|
assert(!Function.IsFragment &&
|
|
|
|
"only one cold fragment is supported at this time");
|
2021-04-08 00:19:26 -07:00
|
|
|
if (BinaryFunction *TargetParent = TargetFunction.getParentFragment()) {
|
2020-11-06 10:27:33 -08:00
|
|
|
assert(TargetParent == &Function && "mismatching parent function");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
TargetFunction.setParentFragment(Function);
|
|
|
|
Function.addFragment(TargetFunction);
|
|
|
|
if (!HasRelocations) {
|
|
|
|
TargetFunction.setSimple(false);
|
|
|
|
Function.setSimple(false);
|
|
|
|
}
|
|
|
|
if (opts::Verbosity >= 1) {
|
|
|
|
outs() << "BOLT-INFO: marking " << TargetFunction
|
|
|
|
<< " as a fragment of " << Function << '\n';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
void BinaryContext::processInterproceduralReferences(BinaryFunction &Function) {
|
2021-04-08 00:19:26 -07:00
|
|
|
for (uint64_t Address : Function.InterproceduralReferences) {
|
2020-09-14 15:48:32 -07:00
|
|
|
if (!Address)
|
2019-05-22 11:26:58 -07:00
|
|
|
continue;
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *TargetFunction =
|
|
|
|
getBinaryFunctionContainingAddress(Address);
|
2020-09-14 15:48:32 -07:00
|
|
|
if (&Function == TargetFunction)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
if (TargetFunction) {
|
2020-11-06 10:57:47 -08:00
|
|
|
if (TargetFunction->IsFragment)
|
2020-11-06 10:27:33 -08:00
|
|
|
registerFragment(*TargetFunction, Function);
|
2021-04-08 00:19:26 -07:00
|
|
|
if (uint64_t Offset = Address - TargetFunction->getAddress())
|
2020-11-06 10:57:47 -08:00
|
|
|
TargetFunction->addEntryPointAtOffset(Offset);
|
2019-05-22 11:26:58 -07:00
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
continue;
|
|
|
|
}
|
2019-05-22 11:26:58 -07:00
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
// Check if address falls in function padding space - this could be
|
|
|
|
// unmarked data in code. In this case adjust the padding space size.
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2020-09-14 15:48:32 -07:00
|
|
|
assert(Section && "cannot get section for referenced address");
|
2019-05-22 11:26:58 -07:00
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
if (!Section->isText())
|
|
|
|
continue;
|
2019-05-22 11:26:58 -07:00
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
// PLT requires special handling and could be ignored in this context.
|
|
|
|
StringRef SectionName = Section->getName();
|
|
|
|
if (SectionName == ".plt" || SectionName == ".plt.got")
|
|
|
|
continue;
|
2019-05-22 11:26:58 -07:00
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
if (opts::processAllFunctions()) {
|
|
|
|
errs() << "BOLT-ERROR: cannot process binaries with unmarked "
|
|
|
|
<< "object in code at address 0x"
|
|
|
|
<< Twine::utohexstr(Address) << " belonging to section "
|
|
|
|
<< SectionName << " in current mode\n";
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
TargetFunction =
|
|
|
|
getBinaryFunctionContainingAddress(Address,
|
|
|
|
/*CheckPastEnd=*/false,
|
|
|
|
/*UseMaxSize=*/true);
|
|
|
|
// We are not going to overwrite non-simple functions, but for simple
|
|
|
|
// ones - adjust the padding size.
|
|
|
|
if (TargetFunction && TargetFunction->isSimple()) {
|
|
|
|
errs() << "BOLT-WARNING: function " << *TargetFunction
|
|
|
|
<< " has an object detected in a padding region at address 0x"
|
|
|
|
<< Twine::utohexstr(Address) << '\n';
|
|
|
|
TargetFunction->setMaxSize(TargetFunction->getSize());
|
2019-05-22 11:26:58 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
clearList(Function.InterproceduralReferences);
|
2019-05-22 11:26:58 -07:00
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
void BinaryContext::postProcessSymbolTable() {
|
|
|
|
fixBinaryDataHoles();
|
|
|
|
bool Valid = true;
|
|
|
|
for (auto &Entry : BinaryDataMap) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *BD = Entry.second;
|
2017-11-14 20:05:11 -08:00
|
|
|
if ((BD->getName().startswith("SYMBOLat") ||
|
|
|
|
BD->getName().startswith("DATAat")) &&
|
|
|
|
!BD->getParent() &&
|
|
|
|
!BD->getSize() &&
|
|
|
|
!BD->isAbsolute() &&
|
|
|
|
BD->getSection()) {
|
2018-07-30 16:30:18 -07:00
|
|
|
errs() << "BOLT-WARNING: zero-sized top level symbol: " << *BD << "\n";
|
2017-11-14 20:05:11 -08:00
|
|
|
Valid = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
assert(Valid);
|
2018-06-06 03:17:32 -07:00
|
|
|
generateSymbolHashes();
|
2017-06-09 13:17:36 -07:00
|
|
|
}
|
|
|
|
|
2016-12-21 17:13:56 -08:00
|
|
|
void BinaryContext::foldFunction(BinaryFunction &ChildBF,
|
2020-01-06 14:57:15 -08:00
|
|
|
BinaryFunction &ParentBF) {
|
2020-01-13 11:56:59 -08:00
|
|
|
assert(!ChildBF.isMultiEntry() && !ParentBF.isMultiEntry() &&
|
|
|
|
"cannot merge functions with multiple entry points");
|
|
|
|
|
2019-05-31 16:45:31 -07:00
|
|
|
std::unique_lock<std::shared_timed_mutex> WriteCtxLock(CtxMutex,
|
|
|
|
std::defer_lock);
|
|
|
|
std::unique_lock<std::shared_timed_mutex> WriteSymbolMapLock(
|
|
|
|
SymbolToFunctionMapMutex, std::defer_lock);
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
const StringRef ChildName = ChildBF.getOneName();
|
2016-12-21 17:13:56 -08:00
|
|
|
|
2020-01-13 11:56:59 -08:00
|
|
|
// Move symbols over and update bookkeeping info.
|
2021-04-08 00:19:26 -07:00
|
|
|
for (MCSymbol *Symbol : ChildBF.getSymbols()) {
|
2020-01-13 11:56:59 -08:00
|
|
|
ParentBF.getSymbols().push_back(Symbol);
|
2019-05-31 16:45:31 -07:00
|
|
|
WriteSymbolMapLock.lock();
|
|
|
|
SymbolToFunctionMap[Symbol] = &ParentBF;
|
|
|
|
WriteSymbolMapLock.unlock();
|
2017-11-14 20:05:11 -08:00
|
|
|
// NB: there's no need to update BinaryDataMap and GlobalSymbols.
|
2016-12-21 17:13:56 -08:00
|
|
|
}
|
2020-01-13 11:56:59 -08:00
|
|
|
ChildBF.getSymbols().clear();
|
|
|
|
|
|
|
|
// Move other names the child function is known under.
|
|
|
|
std::move(ChildBF.Aliases.begin(), ChildBF.Aliases.end(),
|
|
|
|
std::back_inserter(ParentBF.Aliases));
|
|
|
|
ChildBF.Aliases.clear();
|
2016-12-21 17:13:56 -08:00
|
|
|
|
2017-12-09 21:40:39 -08:00
|
|
|
if (HasRelocations) {
|
2020-04-04 20:12:38 -07:00
|
|
|
// Merge execution counts of ChildBF into those of ParentBF.
|
|
|
|
// Without relocations, we cannot reliably merge profiles as both functions
|
|
|
|
// continue to exist and either one can be executed.
|
|
|
|
ChildBF.mergeProfileDataInto(ParentBF);
|
|
|
|
|
2019-05-31 16:45:31 -07:00
|
|
|
std::shared_lock<std::shared_timed_mutex> ReadBfsLock(BinaryFunctionsMutex,
|
|
|
|
std::defer_lock);
|
|
|
|
std::unique_lock<std::shared_timed_mutex> WriteBfsLock(BinaryFunctionsMutex,
|
|
|
|
std::defer_lock);
|
2016-12-21 17:13:56 -08:00
|
|
|
// Remove ChildBF from the global set of functions in relocs mode.
|
2019-05-31 16:45:31 -07:00
|
|
|
ReadBfsLock.lock();
|
2019-04-03 15:52:01 -07:00
|
|
|
auto FI = BinaryFunctions.find(ChildBF.getAddress());
|
2019-05-31 16:45:31 -07:00
|
|
|
ReadBfsLock.unlock();
|
|
|
|
|
2019-04-03 15:52:01 -07:00
|
|
|
assert(FI != BinaryFunctions.end() && "function not found");
|
2016-12-21 17:13:56 -08:00
|
|
|
assert(&ChildBF == &FI->second && "function mismatch");
|
2019-05-31 16:45:31 -07:00
|
|
|
|
|
|
|
WriteBfsLock.lock();
|
2019-04-03 15:52:01 -07:00
|
|
|
FI = BinaryFunctions.erase(FI);
|
2019-05-31 16:45:31 -07:00
|
|
|
WriteBfsLock.unlock();
|
|
|
|
|
2016-12-21 17:13:56 -08:00
|
|
|
} else {
|
|
|
|
// In non-relocation mode we keep the function, but rename it.
|
2020-01-13 11:56:59 -08:00
|
|
|
std::string NewName = "__ICF_" + ChildName.str();
|
2019-05-31 16:45:31 -07:00
|
|
|
|
|
|
|
WriteCtxLock.lock();
|
2020-01-13 11:56:59 -08:00
|
|
|
ChildBF.getSymbols().push_back(Ctx->getOrCreateSymbol(NewName));
|
2019-05-31 16:45:31 -07:00
|
|
|
WriteCtxLock.unlock();
|
|
|
|
|
2020-04-04 20:12:38 -07:00
|
|
|
ChildBF.setFolded(&ParentBF);
|
2016-12-21 17:13:56 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
void BinaryContext::fixBinaryDataHoles() {
|
|
|
|
assert(validateObjectNesting() && "object nesting inconsitency detected");
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
for (BinarySection &Section : allocatableSections()) {
|
2017-11-14 20:05:11 -08:00
|
|
|
std::vector<std::pair<uint64_t, uint64_t>> Holes;
|
|
|
|
|
|
|
|
auto isNotHole = [&Section](const binary_data_iterator &Itr) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *BD = Itr->second;
|
2017-11-14 20:05:11 -08:00
|
|
|
bool isHole = (!BD->getParent() &&
|
|
|
|
!BD->getSize() &&
|
|
|
|
BD->isObject() &&
|
|
|
|
(BD->getName().startswith("SYMBOLat0x") ||
|
|
|
|
BD->getName().startswith("DATAat0x") ||
|
|
|
|
BD->getName().startswith("ANONYMOUS")));
|
|
|
|
return !isHole && BD->getSection() == Section && !BD->getParent();
|
|
|
|
};
|
|
|
|
|
|
|
|
auto BDStart = BinaryDataMap.begin();
|
|
|
|
auto BDEnd = BinaryDataMap.end();
|
|
|
|
auto Itr = FilteredBinaryDataIterator(isNotHole, BDStart, BDEnd);
|
|
|
|
auto End = FilteredBinaryDataIterator(isNotHole, BDEnd, BDEnd);
|
|
|
|
|
|
|
|
uint64_t EndAddress = Section.getAddress();
|
|
|
|
|
|
|
|
while (Itr != End) {
|
2018-03-16 09:03:12 -07:00
|
|
|
if (Itr->second->getAddress() > EndAddress) {
|
2021-04-08 00:19:26 -07:00
|
|
|
uint64_t Gap = Itr->second->getAddress() - EndAddress;
|
2021-05-07 18:43:25 -07:00
|
|
|
Holes.emplace_back(EndAddress, Gap);
|
2017-11-14 20:05:11 -08:00
|
|
|
}
|
|
|
|
EndAddress = Itr->second->getEndAddress();
|
|
|
|
++Itr;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (EndAddress < Section.getEndAddress()) {
|
2021-05-07 18:43:25 -07:00
|
|
|
Holes.emplace_back(EndAddress, Section.getEndAddress() - EndAddress);
|
2017-11-14 20:05:11 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// If there is already a symbol at the start of the hole, grow that symbol
|
|
|
|
// to cover the rest. Otherwise, create a new symbol to cover the hole.
|
2021-04-08 00:19:26 -07:00
|
|
|
for (std::pair<uint64_t, uint64_t> &Hole : Holes) {
|
|
|
|
BinaryData *BD = getBinaryDataAtAddress(Hole.first);
|
2017-11-14 20:05:11 -08:00
|
|
|
if (BD) {
|
|
|
|
// BD->getSection() can be != Section if there are sections that
|
|
|
|
// overlap. In this case it is probably safe to just skip the holes
|
|
|
|
// since the overlapping section will not(?) have any symbols in it.
|
|
|
|
if (BD->getSection() == Section)
|
|
|
|
setBinaryDataSize(Hole.first, Hole.second);
|
|
|
|
} else {
|
2018-09-21 12:00:20 -07:00
|
|
|
getOrCreateGlobalSymbol(Hole.first, "HOLEat", Hole.second, 1);
|
2017-11-14 20:05:11 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
assert(validateObjectNesting() && "object nesting inconsitency detected");
|
|
|
|
assert(validateHoles() && "top level hole detected in object map");
|
|
|
|
}
|
|
|
|
|
2016-07-23 08:01:53 -07:00
|
|
|
void BinaryContext::printGlobalSymbols(raw_ostream& OS) const {
|
2017-11-14 20:05:11 -08:00
|
|
|
const BinarySection* CurrentSection = nullptr;
|
|
|
|
bool FirstSection = true;
|
|
|
|
|
|
|
|
for (auto &Entry : BinaryDataMap) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const BinaryData *BD = Entry.second;
|
|
|
|
const BinarySection &Section = BD->getSection();
|
2017-11-14 20:05:11 -08:00
|
|
|
if (FirstSection || Section != *CurrentSection) {
|
|
|
|
uint64_t Address, Size;
|
|
|
|
StringRef Name = Section.getName();
|
|
|
|
if (Section) {
|
|
|
|
Address = Section.getAddress();
|
|
|
|
Size = Section.getSize();
|
|
|
|
} else {
|
|
|
|
Address = BD->getAddress();
|
|
|
|
Size = BD->getSize();
|
|
|
|
}
|
|
|
|
OS << "BOLT-INFO: Section " << Name << ", "
|
|
|
|
<< "0x" + Twine::utohexstr(Address) << ":"
|
|
|
|
<< "0x" + Twine::utohexstr(Address + Size) << "/"
|
|
|
|
<< Size << "\n";
|
|
|
|
CurrentSection = &Section;
|
|
|
|
FirstSection = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
OS << "BOLT-INFO: ";
|
2021-04-08 00:19:26 -07:00
|
|
|
const BinaryData *P = BD->getParent();
|
2017-11-14 20:05:11 -08:00
|
|
|
while (P) {
|
|
|
|
OS << " ";
|
|
|
|
P = P->getParent();
|
|
|
|
}
|
|
|
|
OS << *BD << "\n";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-02 11:58:53 -07:00
|
|
|
unsigned BinaryContext::addDebugFilenameToUnit(const uint32_t DestCUID,
|
|
|
|
const uint32_t SrcCUID,
|
|
|
|
unsigned FileIndex) {
|
2021-04-08 00:19:26 -07:00
|
|
|
DWARFCompileUnit *SrcUnit = DwCtx->getCompileUnitForOffset(SrcCUID);
|
|
|
|
const DWARFDebugLine::LineTable *LineTable =
|
|
|
|
DwCtx->getLineTableForUnit(SrcUnit);
|
|
|
|
const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
|
|
|
|
LineTable->Prologue.FileNames;
|
2016-09-02 11:58:53 -07:00
|
|
|
// Dir indexes start at 1, as DWARF file numbers, and a dir index 0
|
|
|
|
// means empty dir.
|
|
|
|
assert(FileIndex > 0 && FileIndex <= FileNames.size() &&
|
|
|
|
"FileIndex out of range for the compilation unit.");
|
2018-05-04 10:10:41 -07:00
|
|
|
StringRef Dir = "";
|
|
|
|
if (FileNames[FileIndex - 1].DirIdx != 0) {
|
2021-04-08 00:19:26 -07:00
|
|
|
if (Optional<const char *> DirName = dwarf::toString(
|
2018-05-04 10:10:41 -07:00
|
|
|
LineTable->Prologue
|
2020-12-01 16:29:39 -08:00
|
|
|
.IncludeDirectories[FileNames[FileIndex - 1].DirIdx - 1])) {
|
2018-05-04 10:10:41 -07:00
|
|
|
Dir = *DirName;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
StringRef FileName = "";
|
2021-04-08 00:19:26 -07:00
|
|
|
if (Optional<const char *> FName =
|
|
|
|
dwarf::toString(FileNames[FileIndex - 1].Name))
|
2018-05-04 10:10:41 -07:00
|
|
|
FileName = *FName;
|
|
|
|
assert(FileName != "");
|
2020-12-01 16:29:39 -08:00
|
|
|
return cantFail(Ctx->getDwarfFile(Dir, FileName, 0, None, None, DestCUID));
|
2016-09-02 11:58:53 -07:00
|
|
|
}
|
|
|
|
|
2019-04-03 15:52:01 -07:00
|
|
|
std::vector<BinaryFunction *> BinaryContext::getSortedFunctions() {
|
2017-08-31 11:45:37 -07:00
|
|
|
std::vector<BinaryFunction *> SortedFunctions(BinaryFunctions.size());
|
|
|
|
std::transform(BinaryFunctions.begin(), BinaryFunctions.end(),
|
|
|
|
SortedFunctions.begin(),
|
|
|
|
[](std::pair<const uint64_t, BinaryFunction> &BFI) {
|
|
|
|
return &BFI.second;
|
|
|
|
});
|
|
|
|
|
2017-11-28 09:57:21 -08:00
|
|
|
std::stable_sort(SortedFunctions.begin(), SortedFunctions.end(),
|
2019-03-14 18:51:05 -07:00
|
|
|
[] (const BinaryFunction *A, const BinaryFunction *B) {
|
|
|
|
if (A->hasValidIndex() && B->hasValidIndex()) {
|
|
|
|
return A->getIndex() < B->getIndex();
|
|
|
|
}
|
|
|
|
return A->hasValidIndex();
|
|
|
|
});
|
2017-08-31 11:45:37 -07:00
|
|
|
return SortedFunctions;
|
|
|
|
}
|
|
|
|
|
2020-10-09 16:06:27 -07:00
|
|
|
std::vector<BinaryFunction *> BinaryContext::getAllBinaryFunctions() {
|
|
|
|
std::vector<BinaryFunction *> AllFunctions;
|
|
|
|
AllFunctions.reserve(BinaryFunctions.size() + InjectedBinaryFunctions.size());
|
|
|
|
std::transform(BinaryFunctions.begin(), BinaryFunctions.end(),
|
|
|
|
std::back_inserter(AllFunctions),
|
|
|
|
[](std::pair<const uint64_t, BinaryFunction> &BFI) {
|
|
|
|
return &BFI.second;
|
|
|
|
});
|
|
|
|
std::copy(InjectedBinaryFunctions.begin(), InjectedBinaryFunctions.end(),
|
|
|
|
std::back_inserter(AllFunctions));
|
|
|
|
|
|
|
|
return AllFunctions;
|
|
|
|
}
|
|
|
|
|
2019-04-03 15:52:01 -07:00
|
|
|
void BinaryContext::preprocessDebugInfo() {
|
2020-10-12 21:04:42 -07:00
|
|
|
struct CURange {
|
|
|
|
uint64_t LowPC;
|
|
|
|
uint64_t HighPC;
|
|
|
|
DWARFUnit *Unit;
|
|
|
|
|
|
|
|
bool operator<(const CURange &Other) const {
|
|
|
|
return LowPC < Other.LowPC;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Building a map of address ranges to CUs similar to .debug_aranges and use
|
|
|
|
// it to assign CU to functions.
|
|
|
|
std::vector<CURange> AllRanges;
|
2020-12-01 16:29:39 -08:00
|
|
|
AllRanges.reserve(DwCtx->getNumCompileUnits());
|
2021-04-08 00:19:26 -07:00
|
|
|
for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
|
|
|
|
Expected<DWARFAddressRangesVector> RangesOrError =
|
|
|
|
CU->getUnitDIE().getAddressRanges();
|
2021-04-06 12:57:09 -07:00
|
|
|
if (!RangesOrError) {
|
|
|
|
consumeError(RangesOrError.takeError());
|
|
|
|
continue;
|
|
|
|
}
|
2021-04-08 00:19:26 -07:00
|
|
|
for (DWARFAddressRange &Range : *RangesOrError) {
|
2020-10-12 21:04:42 -07:00
|
|
|
// Parts of the debug info could be invalidated due to corresponding code
|
|
|
|
// being removed from the binary by the linker. Hence we check if the
|
|
|
|
// address is a valid one.
|
|
|
|
if (containsAddress(Range.LowPC))
|
|
|
|
AllRanges.emplace_back(CURange{Range.LowPC, Range.HighPC, CU.get()});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
std::sort(AllRanges.begin(), AllRanges.end());
|
|
|
|
for (auto &KV : BinaryFunctions) {
|
|
|
|
const uint64_t FunctionAddress = KV.first;
|
|
|
|
BinaryFunction &Function = KV.second;
|
|
|
|
|
|
|
|
auto It = std::partition_point(AllRanges.begin(), AllRanges.end(),
|
|
|
|
[=](CURange R) { return R.HighPC <= FunctionAddress; });
|
|
|
|
if (It != AllRanges.end() && It->LowPC <= FunctionAddress) {
|
|
|
|
Function.setDWARFUnit(It->Unit);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Populate MCContext with DWARF files from all units.
|
2020-12-01 16:29:39 -08:00
|
|
|
StringRef GlobalPrefix = AsmInfo->getPrivateGlobalPrefix();
|
2021-04-08 00:19:26 -07:00
|
|
|
for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
|
2020-12-01 16:29:39 -08:00
|
|
|
const uint64_t CUID = CU->getOffset();
|
2020-10-12 21:04:42 -07:00
|
|
|
const DWARFDebugLine::LineTable *LineTable =
|
|
|
|
DwCtx->getLineTableForUnit(CU.get());
|
2021-04-08 00:19:26 -07:00
|
|
|
const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
|
|
|
|
LineTable->Prologue.FileNames;
|
2020-12-01 16:29:39 -08:00
|
|
|
|
|
|
|
// Assign a unique label to every line table, one per CU.
|
|
|
|
Ctx->getMCDwarfLineTable(CUID).setLabel(
|
|
|
|
Ctx->getOrCreateSymbol(GlobalPrefix + "line_table_start" + Twine(CUID)));
|
|
|
|
|
2018-08-27 20:12:59 -07:00
|
|
|
// Make sure empty debug line tables are registered too.
|
|
|
|
if (FileNames.empty()) {
|
2020-12-01 16:29:39 -08:00
|
|
|
cantFail(Ctx->getDwarfFile("", "<unknown>", 0, None, None, CUID));
|
2018-08-27 20:12:59 -07:00
|
|
|
continue;
|
|
|
|
}
|
2016-03-14 18:48:05 -07:00
|
|
|
for (size_t I = 0, Size = FileNames.size(); I != Size; ++I) {
|
|
|
|
// Dir indexes start at 1, as DWARF file numbers, and a dir index 0
|
|
|
|
// means empty dir.
|
2018-05-04 10:10:41 -07:00
|
|
|
StringRef Dir = "";
|
|
|
|
if (FileNames[I].DirIdx != 0)
|
2021-04-08 00:19:26 -07:00
|
|
|
if (Optional<const char *> DirName = dwarf::toString(
|
2020-12-01 16:29:39 -08:00
|
|
|
LineTable->Prologue
|
|
|
|
.IncludeDirectories[FileNames[I].DirIdx - 1]))
|
2018-05-04 10:10:41 -07:00
|
|
|
Dir = *DirName;
|
|
|
|
StringRef FileName = "";
|
2021-04-08 00:19:26 -07:00
|
|
|
if (Optional<const char *> FName = dwarf::toString(FileNames[I].Name))
|
2018-05-04 10:10:41 -07:00
|
|
|
FileName = *FName;
|
|
|
|
assert(FileName != "");
|
2020-12-01 16:29:39 -08:00
|
|
|
cantFail(Ctx->getDwarfFile(Dir, FileName, 0, None, None, CUID));
|
2016-03-14 18:48:05 -07:00
|
|
|
}
|
|
|
|
}
|
2019-10-14 17:57:36 -07:00
|
|
|
}
|
2016-05-27 20:19:19 -07:00
|
|
|
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
bool BinaryContext::shouldEmit(const BinaryFunction &Function) const {
|
|
|
|
if (opts::processAllFunctions())
|
|
|
|
return true;
|
|
|
|
|
|
|
|
if (Function.isIgnored())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// In relocation mode we will emit non-simple functions with CFG.
|
|
|
|
// If the function does not have a CFG it should be marked as ignored.
|
|
|
|
return HasRelocations || Function.isSimple();
|
|
|
|
}
|
|
|
|
|
2017-05-01 16:52:54 -07:00
|
|
|
void BinaryContext::printCFI(raw_ostream &OS, const MCCFIInstruction &Inst) {
|
|
|
|
uint32_t Operation = Inst.getOperation();
|
|
|
|
switch (Operation) {
|
|
|
|
case MCCFIInstruction::OpSameValue:
|
|
|
|
OS << "OpSameValue Reg" << Inst.getRegister();
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpRememberState:
|
|
|
|
OS << "OpRememberState";
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpRestoreState:
|
|
|
|
OS << "OpRestoreState";
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpOffset:
|
|
|
|
OS << "OpOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpDefCfaRegister:
|
|
|
|
OS << "OpDefCfaRegister Reg" << Inst.getRegister();
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpDefCfaOffset:
|
|
|
|
OS << "OpDefCfaOffset " << Inst.getOffset();
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpDefCfa:
|
|
|
|
OS << "OpDefCfa Reg" << Inst.getRegister() << " " << Inst.getOffset();
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpRelOffset:
|
2018-09-05 14:36:52 -07:00
|
|
|
OS << "OpRelOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
|
2017-05-01 16:52:54 -07:00
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpAdjustCfaOffset:
|
2018-09-05 14:36:52 -07:00
|
|
|
OS << "OfAdjustCfaOffset " << Inst.getOffset();
|
2017-05-01 16:52:54 -07:00
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpEscape:
|
|
|
|
OS << "OpEscape";
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpRestore:
|
2018-09-05 14:36:52 -07:00
|
|
|
OS << "OpRestore Reg" << Inst.getRegister();
|
2017-05-01 16:52:54 -07:00
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpUndefined:
|
2018-09-05 14:36:52 -07:00
|
|
|
OS << "OpUndefined Reg" << Inst.getRegister();
|
2017-05-01 16:52:54 -07:00
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpRegister:
|
2018-09-05 14:36:52 -07:00
|
|
|
OS << "OpRegister Reg" << Inst.getRegister() << " Reg"
|
|
|
|
<< Inst.getRegister2();
|
2017-05-01 16:52:54 -07:00
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpWindowSave:
|
|
|
|
OS << "OpWindowSave";
|
|
|
|
break;
|
|
|
|
case MCCFIInstruction::OpGnuArgsSize:
|
|
|
|
OS << "OpGnuArgsSize";
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
OS << "Op#" << Operation;
|
|
|
|
break;
|
2016-07-23 08:01:53 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::printInstruction(raw_ostream &OS,
|
|
|
|
const MCInst &Instruction,
|
|
|
|
uint64_t Offset,
|
|
|
|
const BinaryFunction* Function,
|
2017-10-20 12:11:34 -07:00
|
|
|
bool PrintMCInst,
|
|
|
|
bool PrintMemData,
|
|
|
|
bool PrintRelocations) const {
|
2018-03-09 09:45:13 -08:00
|
|
|
if (MIB->isEHLabel(Instruction)) {
|
|
|
|
OS << " EH_LABEL: " << *MIB->getTargetSymbol(Instruction) << '\n';
|
2016-07-23 08:01:53 -07:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
OS << format(" %08" PRIx64 ": ", Offset);
|
2018-03-09 09:45:13 -08:00
|
|
|
if (MIB->isCFI(Instruction)) {
|
2016-07-23 08:01:53 -07:00
|
|
|
uint32_t Offset = Instruction.getOperand(0).getImm();
|
|
|
|
OS << "\t!CFI\t$" << Offset << "\t; ";
|
2016-08-22 14:24:09 -07:00
|
|
|
if (Function)
|
2017-05-01 16:52:54 -07:00
|
|
|
printCFI(OS, *Function->getCFIFor(Instruction));
|
2016-07-23 08:01:53 -07:00
|
|
|
OS << "\n";
|
|
|
|
return;
|
|
|
|
}
|
2020-12-01 16:29:39 -08:00
|
|
|
InstPrinter->printInst(&Instruction, 0, "", *STI, OS);
|
2018-03-09 09:45:13 -08:00
|
|
|
if (MIB->isCall(Instruction)) {
|
|
|
|
if (MIB->isTailCall(Instruction))
|
2016-07-23 08:01:53 -07:00
|
|
|
OS << " # TAILCALL ";
|
2018-03-09 09:45:13 -08:00
|
|
|
if (MIB->isInvoke(Instruction)) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const Optional<MCPlus::MCLandingPad> EHInfo = MIB->getEHInfo(Instruction);
|
2019-01-31 11:23:02 -08:00
|
|
|
OS << " # handler: ";
|
|
|
|
if (EHInfo->first)
|
|
|
|
OS << *EHInfo->first;
|
|
|
|
else
|
|
|
|
OS << '0';
|
|
|
|
OS << "; action: " << EHInfo->second;
|
2021-04-08 00:19:26 -07:00
|
|
|
const int64_t GnuArgsSize = MIB->getGnuArgsSize(Instruction);
|
2016-07-23 08:01:53 -07:00
|
|
|
if (GnuArgsSize >= 0)
|
|
|
|
OS << "; GNU_args_size = " << GnuArgsSize;
|
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
} else if (MIB->isIndirectBranch(Instruction)) {
|
2021-04-08 00:19:26 -07:00
|
|
|
if (uint64_t JTAddress = MIB->getJumpTable(Instruction)) {
|
2016-09-16 15:54:32 -07:00
|
|
|
OS << " # JUMPTABLE @0x" << Twine::utohexstr(JTAddress);
|
2019-06-28 09:21:27 -07:00
|
|
|
} else {
|
|
|
|
OS << " # UNKNOWN CONTROL FLOW";
|
2016-09-14 16:45:40 -07:00
|
|
|
}
|
|
|
|
}
|
2016-07-23 08:01:53 -07:00
|
|
|
|
[BOLT][Refactoring] Isolate changes to MC layer
Summary:
Changes that we made to MCInst, MCOperand, MCExpr, etc. are now all
moved into tools/llvm-bolt. That required a change to the way we handle
annotations and any extra operands for MCInst.
Any MCPlus information is now attached via an extra operand of type
MCInst with an opcode ANNOTATION_LABEL. Since this operand is MCInst, we
attach extra info as operands to this instruction. For first-level
annotations use functions to access the information, such as
getConditionalTailCall() or getEHInfo(), etc. For the rest, optional or
second-class annotations, use a general named-annotation interface such
as getAnnotationAs<uint64_t>(Inst, "Count").
I did a test on HHVM binary, and a memory consumption went down a little
bit while the runtime remained the same.
(cherry picked from FBD7405412)
2018-03-19 18:32:12 -07:00
|
|
|
MIB->printAnnotations(Instruction, OS);
|
Indirect call promotion optimization.
Summary:
Perform indirect call promotion optimization in BOLT.
The code scans the instructions during CFG creation for all
indirect calls. Right now indirect tail calls are not handled
since the functions are marked not simple. The offsets of the
indirect calls are stored for later use by the ICP pass.
The indirect call promotion pass visits each indirect call and
examines the BranchData for each. If the most frequent targets
from that callsite exceed the specified threshold (default 90%),
the call is promoted. Otherwise, it is ignored. By default,
only one target is considered at each callsite.
When an candiate callsite is processed, we modify the callsite
to test for the most common call targets before calling through
the original generic call mechanism.
The CFG and layout are modified by ICP.
A few new command line options have been added:
-indirect-call-promotion
-indirect-call-promotion-threshold=<percentage>
-indirect-call-promotion-topn=<int>
The threshold is the minimum frequency of a call target needed
before ICP is triggered.
The topn option controls the number of targets to consider for
each callsite, e.g. ICP is triggered if topn=2 and the total
requency of the top two call targets exceeds the threshold.
Example of ICP:
C++ code:
int B_count = 0;
int C_count = 0;
struct A { virtual void foo() = 0; }
struct B : public A { virtual void foo() { ++B_count; }; };
struct C : public A { virtual void foo() { ++C_count; }; };
A* a = ...
a->foo();
...
original:
400863: 49 8b 07 mov (%r15),%rax
400866: 4c 89 ff mov %r15,%rdi
400869: ff 10 callq *(%rax)
40086b: 41 83 e6 01 and $0x1,%r14d
40086f: 4d 89 e6 mov %r12,%r14
400872: 4c 0f 44 f5 cmove %rbp,%r14
400876: 4c 89 f7 mov %r14,%rdi
...
after ICP:
40085e: 49 8b 07 mov (%r15),%rax
400861: 4c 89 ff mov %r15,%rdi
400864: 49 ba e0 0b 40 00 00 movabs $0x400be0,%r10
40086b: 00 00 00
40086e: 4c 3b 10 cmp (%rax),%r10
400871: 75 29 jne 40089c <main+0x9c>
400873: 41 ff d2 callq *%r10
400876: 41 83 e6 01 and $0x1,%r14d
40087a: 4d 89 e6 mov %r12,%r14
40087d: 4c 0f 44 f5 cmove %rbp,%r14
400881: 4c 89 f7 mov %r14,%rdi
...
40089c: ff 10 callq *(%rax)
40089e: eb d6 jmp 400876 <main+0x76>
(cherry picked from FBD3612218)
2016-09-07 18:59:23 -07:00
|
|
|
|
2016-07-23 08:01:53 -07:00
|
|
|
const DWARFDebugLine::LineTable *LineTable =
|
2020-10-12 21:04:42 -07:00
|
|
|
Function && opts::PrintDebugInfo ? Function->getDWARFLineTable()
|
2016-07-23 08:01:53 -07:00
|
|
|
: nullptr;
|
|
|
|
|
|
|
|
if (LineTable) {
|
2021-04-08 00:19:26 -07:00
|
|
|
DebugLineTableRowRef RowRef =
|
|
|
|
DebugLineTableRowRef::fromSMLoc(Instruction.getLoc());
|
2016-07-23 08:01:53 -07:00
|
|
|
|
|
|
|
if (RowRef != DebugLineTableRowRef::NULL_ROW) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const DWARFDebugLine::Row &Row = LineTable->Rows[RowRef.RowIndex - 1];
|
2018-05-04 10:10:41 -07:00
|
|
|
StringRef FileName = "";
|
2021-04-08 00:19:26 -07:00
|
|
|
if (Optional<const char *> FName =
|
2020-12-01 16:29:39 -08:00
|
|
|
dwarf::toString(LineTable->Prologue.FileNames[Row.File - 1].Name))
|
2018-05-04 10:10:41 -07:00
|
|
|
FileName = *FName;
|
|
|
|
OS << " # debug line " << FileName << ":" << Row.Line;
|
2016-07-23 08:01:53 -07:00
|
|
|
|
|
|
|
if (Row.Column) {
|
|
|
|
OS << ":" << Row.Column;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-20 12:11:34 -07:00
|
|
|
if ((opts::PrintRelocations || PrintRelocations) && Function) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t Size = computeCodeSize(&Instruction, &Instruction + 1);
|
2017-10-20 12:11:34 -07:00
|
|
|
Function->printRelocations(OS, Offset, Size);
|
|
|
|
}
|
|
|
|
|
2016-07-23 08:01:53 -07:00
|
|
|
OS << "\n";
|
|
|
|
|
2017-10-20 12:11:34 -07:00
|
|
|
if (PrintMCInst) {
|
2016-07-23 08:01:53 -07:00
|
|
|
Instruction.dump_pretty(OS, InstPrinter.get());
|
|
|
|
OS << "\n";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-23 15:10:24 -08:00
|
|
|
ErrorOr<BinarySection&> BinaryContext::getSectionForAddress(uint64_t Address) {
|
2018-01-31 12:12:59 -08:00
|
|
|
auto SI = AddressToSection.upper_bound(Address);
|
|
|
|
if (SI != AddressToSection.begin()) {
|
2018-01-23 15:10:24 -08:00
|
|
|
--SI;
|
2021-04-08 00:19:26 -07:00
|
|
|
uint64_t UpperBound = SI->first + SI->second->getSize();
|
2019-06-27 03:20:17 -07:00
|
|
|
if (!SI->second->getSize())
|
|
|
|
UpperBound += 1;
|
|
|
|
if (UpperBound > Address)
|
2018-01-31 12:12:59 -08:00
|
|
|
return *SI->second;
|
2016-07-21 12:45:35 -07:00
|
|
|
}
|
|
|
|
return std::make_error_code(std::errc::bad_address);
|
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
ErrorOr<StringRef>
|
|
|
|
BinaryContext::getSectionNameForAddress(uint64_t Address) const {
|
2021-04-08 00:19:26 -07:00
|
|
|
if (ErrorOr<const BinarySection &> Section = getSectionForAddress(Address)) {
|
2017-11-14 20:05:11 -08:00
|
|
|
return Section->getName();
|
|
|
|
}
|
|
|
|
return std::make_error_code(std::errc::bad_address);
|
|
|
|
}
|
|
|
|
|
2018-02-01 16:33:43 -08:00
|
|
|
BinarySection &BinaryContext::registerSection(BinarySection *Section) {
|
|
|
|
auto Res = Sections.insert(Section);
|
2018-01-31 12:12:59 -08:00
|
|
|
assert(Res.second && "can't register the same section twice.");
|
2020-07-06 14:39:44 -07:00
|
|
|
|
|
|
|
// Only register allocatable sections in the AddressToSection map.
|
2020-09-14 14:31:50 -07:00
|
|
|
if (Section->isAllocatable() && Section->getAddress())
|
2018-02-01 16:33:43 -08:00
|
|
|
AddressToSection.insert(std::make_pair(Section->getAddress(), Section));
|
2020-12-01 16:29:39 -08:00
|
|
|
NameToSection.insert(
|
|
|
|
std::make_pair(std::string(Section->getName()), Section));
|
|
|
|
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: registering " << *Section << "\n");
|
2018-02-01 16:33:43 -08:00
|
|
|
return *Section;
|
|
|
|
}
|
|
|
|
|
|
|
|
BinarySection &BinaryContext::registerSection(SectionRef Section) {
|
2018-04-20 20:03:31 -07:00
|
|
|
return registerSection(new BinarySection(*this, Section));
|
|
|
|
}
|
|
|
|
|
|
|
|
BinarySection &
|
|
|
|
BinaryContext::registerSection(StringRef SectionName,
|
|
|
|
const BinarySection &OriginalSection) {
|
|
|
|
return registerSection(new BinarySection(*this,
|
|
|
|
SectionName,
|
|
|
|
OriginalSection));
|
2018-02-01 16:33:43 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
BinarySection &BinaryContext::registerOrUpdateSection(StringRef Name,
|
|
|
|
unsigned ELFType,
|
|
|
|
unsigned ELFFlags,
|
|
|
|
uint8_t *Data,
|
|
|
|
uint64_t Size,
|
2020-02-18 09:20:17 -08:00
|
|
|
unsigned Alignment) {
|
2018-02-01 16:33:43 -08:00
|
|
|
auto NamedSections = getSectionByName(Name);
|
|
|
|
if (NamedSections.begin() != NamedSections.end()) {
|
|
|
|
assert(std::next(NamedSections.begin()) == NamedSections.end() &&
|
|
|
|
"can only update unique sections");
|
2021-04-08 00:19:26 -07:00
|
|
|
BinarySection *Section = NamedSections.begin()->second;
|
2018-02-01 16:33:43 -08:00
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: updating " << *Section << " -> ");
|
2021-04-08 00:19:26 -07:00
|
|
|
const bool Flag = Section->isAllocatable();
|
2020-02-18 09:20:17 -08:00
|
|
|
Section->update(Data, Size, Alignment, ELFType, ELFFlags);
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(dbgs() << *Section << "\n");
|
2020-06-12 20:16:27 -07:00
|
|
|
// FIXME: Fix section flags/attributes for MachO.
|
|
|
|
if (isELF())
|
|
|
|
assert(Flag == Section->isAllocatable() &&
|
|
|
|
"can't change section allocation status");
|
2018-02-01 16:33:43 -08:00
|
|
|
return *Section;
|
|
|
|
}
|
|
|
|
|
2018-04-20 20:03:31 -07:00
|
|
|
return registerSection(new BinarySection(*this, Name, Data, Size, Alignment,
|
2020-02-18 09:20:17 -08:00
|
|
|
ELFType, ELFFlags));
|
2018-02-01 16:33:43 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
bool BinaryContext::deregisterSection(BinarySection &Section) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinarySection *SectionPtr = &Section;
|
2018-02-01 16:33:43 -08:00
|
|
|
auto Itr = Sections.find(SectionPtr);
|
|
|
|
if (Itr != Sections.end()) {
|
|
|
|
auto Range = AddressToSection.equal_range(SectionPtr->getAddress());
|
|
|
|
while (Range.first != Range.second) {
|
|
|
|
if (Range.first->second == SectionPtr) {
|
|
|
|
AddressToSection.erase(Range.first);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
++Range.first;
|
|
|
|
}
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
auto NameRange =
|
|
|
|
NameToSection.equal_range(std::string(SectionPtr->getName()));
|
2018-02-01 16:33:43 -08:00
|
|
|
while (NameRange.first != NameRange.second) {
|
|
|
|
if (NameRange.first->second == SectionPtr) {
|
|
|
|
NameToSection.erase(NameRange.first);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
++NameRange.first;
|
|
|
|
}
|
|
|
|
|
|
|
|
Sections.erase(Itr);
|
|
|
|
delete SectionPtr;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::printSections(raw_ostream &OS) const {
|
2021-04-08 00:19:26 -07:00
|
|
|
for (BinarySection *const &Section : Sections) {
|
2018-02-01 16:33:43 -08:00
|
|
|
OS << "BOLT-INFO: " << *Section << "\n";
|
|
|
|
}
|
2018-01-31 12:12:59 -08:00
|
|
|
}
|
|
|
|
|
2017-11-14 20:05:11 -08:00
|
|
|
BinarySection &BinaryContext::absoluteSection() {
|
2021-04-08 00:19:26 -07:00
|
|
|
if (ErrorOr<BinarySection &> Section = getUniqueSectionByName("<absolute>"))
|
2017-11-14 20:05:11 -08:00
|
|
|
return *Section;
|
|
|
|
return registerOrUpdateSection("<absolute>", ELF::SHT_NULL, 0u);
|
|
|
|
}
|
|
|
|
|
2017-08-27 17:04:06 -07:00
|
|
|
ErrorOr<uint64_t>
|
2019-04-09 12:29:40 -07:00
|
|
|
BinaryContext::getUnsignedValueAtAddress(uint64_t Address,
|
|
|
|
size_t Size) const {
|
2021-04-08 00:19:26 -07:00
|
|
|
const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
|
2019-04-09 12:29:40 -07:00
|
|
|
if (!Section)
|
|
|
|
return std::make_error_code(std::errc::bad_address);
|
|
|
|
|
|
|
|
if (Section->isVirtual())
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
|
|
|
|
AsmInfo->getCodePointerSize());
|
2020-12-01 16:29:39 -08:00
|
|
|
auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
|
2019-04-09 12:29:40 -07:00
|
|
|
return DE.getUnsigned(&ValueOffset, Size);
|
|
|
|
}
|
|
|
|
|
|
|
|
ErrorOr<uint64_t>
|
|
|
|
BinaryContext::getSignedValueAtAddress(uint64_t Address,
|
|
|
|
size_t Size) const {
|
2021-04-08 00:19:26 -07:00
|
|
|
const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
|
2017-08-27 17:04:06 -07:00
|
|
|
if (!Section)
|
2018-01-23 15:10:24 -08:00
|
|
|
return std::make_error_code(std::errc::bad_address);
|
2017-08-27 17:04:06 -07:00
|
|
|
|
2019-04-09 12:29:40 -07:00
|
|
|
if (Section->isVirtual())
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
|
[BOLT rebase] Rebase fixes on top of LLVM Feb2018
Summary:
This commit includes all code necessary to make BOLT working again
after the rebase. This includes a redesign of the EHFrame work,
cherry-pick of the 3dnow disassembly work, compilation error fixes,
and port of the debug_info work. The macroop fusion feature is not
ported yet.
The rebased version has minor changes to the "executed instructions"
dynostats counter because REP prefixes are considered a part of the
instruction it applies to. Also, some X86 instructions had the "mayLoad"
tablegen property removed, which BOLT uses to identify and account
for loads, thus reducing the total number of loads reported by
dynostats. This was observed in X86::MOVDQUmr. TRAP instructions are
not terminators anymore, changing our CFG. This commit adds compensation
to preserve this old behavior and minimize tests changes. debug_info
sections are now slightly larger. The discriminator field in the line
table is slightly different due to a change upstream. New profiles
generated with the other bolt are incompatible with this version
because of different hash values calculated for functions, so they will
be considered 100% stale. This commit changes the corresponding test
to XFAIL so it can be updated. The hash function changes because it
relies on raw opcode values, which change according to the opcodes
described in the X86 tablegen files. When processing HHVM, bolt was
observed to be using about 800MB more memory in the rebased version
and being about 5% slower.
(cherry picked from FBD7078072)
2018-02-06 15:00:23 -08:00
|
|
|
AsmInfo->getCodePointerSize());
|
2020-12-01 16:29:39 -08:00
|
|
|
auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
|
2019-04-09 12:29:40 -07:00
|
|
|
return DE.getSigned(&ValueOffset, Size);
|
2017-08-27 17:04:06 -07:00
|
|
|
}
|
|
|
|
|
2018-01-23 15:10:24 -08:00
|
|
|
void BinaryContext::addRelocation(uint64_t Address,
|
|
|
|
MCSymbol *Symbol,
|
|
|
|
uint64_t Type,
|
2018-02-01 16:33:43 -08:00
|
|
|
uint64_t Addend,
|
|
|
|
uint64_t Value) {
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2018-01-23 15:10:24 -08:00
|
|
|
assert(Section && "cannot find section for address");
|
2018-02-01 16:33:43 -08:00
|
|
|
Section->addRelocation(Address - Section->getAddress(),
|
|
|
|
Symbol,
|
|
|
|
Type,
|
|
|
|
Addend,
|
|
|
|
Value);
|
2017-02-21 16:15:15 -08:00
|
|
|
}
|
|
|
|
|
2020-06-23 12:22:58 -07:00
|
|
|
void BinaryContext::addDynamicRelocation(uint64_t Address,
|
|
|
|
MCSymbol *Symbol,
|
|
|
|
uint64_t Type,
|
|
|
|
uint64_t Addend,
|
|
|
|
uint64_t Value) {
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2020-06-23 12:22:58 -07:00
|
|
|
assert(Section && "cannot find section for address");
|
|
|
|
Section->addDynamicRelocation(Address - Section->getAddress(),
|
|
|
|
Symbol,
|
|
|
|
Type,
|
|
|
|
Addend,
|
|
|
|
Value);
|
|
|
|
}
|
|
|
|
|
2018-02-01 16:33:43 -08:00
|
|
|
bool BinaryContext::removeRelocationAt(uint64_t Address) {
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2018-01-23 15:10:24 -08:00
|
|
|
assert(Section && "cannot find section for address");
|
2018-02-01 16:33:43 -08:00
|
|
|
return Section->removeRelocationAt(Address - Section->getAddress());
|
2017-02-21 16:15:15 -08:00
|
|
|
}
|
|
|
|
|
2017-12-11 17:07:56 -08:00
|
|
|
const Relocation *BinaryContext::getRelocationAt(uint64_t Address) {
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2019-06-28 09:21:27 -07:00
|
|
|
if (!Section)
|
|
|
|
return nullptr;
|
|
|
|
|
2018-01-23 15:10:24 -08:00
|
|
|
return Section->getRelocationAt(Address - Section->getAddress());
|
2017-10-20 12:11:34 -07:00
|
|
|
}
|
2018-06-20 12:03:24 -07:00
|
|
|
|
2020-06-23 12:22:58 -07:00
|
|
|
const Relocation *BinaryContext::getDynamicRelocationAt(uint64_t Address) {
|
2021-04-08 00:19:26 -07:00
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
2020-06-23 12:22:58 -07:00
|
|
|
if (!Section)
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
return Section->getDynamicRelocationAt(Address - Section->getAddress());
|
|
|
|
}
|
|
|
|
|
2019-11-18 14:08:17 -08:00
|
|
|
void BinaryContext::markAmbiguousRelocations(BinaryData &BD,
|
|
|
|
const uint64_t Address) {
|
|
|
|
auto setImmovable = [&](BinaryData &BD) {
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *Root = BD.getAtomicRoot();
|
2020-12-01 16:29:39 -08:00
|
|
|
LLVM_DEBUG(if (Root->isMoveable()) {
|
2019-11-18 14:08:17 -08:00
|
|
|
dbgs() << "BOLT-DEBUG: setting " << *Root << " as immovable "
|
|
|
|
<< "due to ambiguous relocation referencing 0x"
|
|
|
|
<< Twine::utohexstr(Address) << '\n';
|
|
|
|
});
|
|
|
|
Root->setIsMoveable(false);
|
|
|
|
};
|
|
|
|
|
|
|
|
if (Address == BD.getAddress()) {
|
|
|
|
setImmovable(BD);
|
|
|
|
|
|
|
|
// Set previous symbol as immovable
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *Prev = getBinaryDataContainingAddress(Address - 1);
|
2019-11-18 14:08:17 -08:00
|
|
|
if (Prev && Prev->getEndAddress() == BD.getAddress())
|
|
|
|
setImmovable(*Prev);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Address == BD.getEndAddress()) {
|
|
|
|
setImmovable(BD);
|
|
|
|
|
|
|
|
// Set next symbol as immovable
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryData *Next = getBinaryDataContainingAddress(BD.getEndAddress());
|
2019-11-18 14:08:17 -08:00
|
|
|
if (Next && Next->getAddress() == BD.getEndAddress())
|
|
|
|
setImmovable(*Next);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-06 14:57:15 -08:00
|
|
|
BinaryFunction *BinaryContext::getFunctionForSymbol(const MCSymbol *Symbol,
|
|
|
|
uint64_t *EntryDesc) {
|
|
|
|
std::shared_lock<std::shared_timed_mutex> Lock(SymbolToFunctionMapMutex);
|
|
|
|
auto BFI = SymbolToFunctionMap.find(Symbol);
|
|
|
|
if (BFI == SymbolToFunctionMap.end())
|
|
|
|
return nullptr;
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *BF = BFI->second;
|
2020-01-06 14:57:15 -08:00
|
|
|
if (EntryDesc)
|
2020-04-19 22:29:54 -07:00
|
|
|
*EntryDesc = BF->getEntryIDForSymbol(Symbol);
|
2020-01-06 14:57:15 -08:00
|
|
|
|
|
|
|
return BF;
|
|
|
|
}
|
|
|
|
|
2018-06-20 12:03:24 -07:00
|
|
|
void BinaryContext::exitWithBugReport(StringRef Message,
|
|
|
|
const BinaryFunction &Function) const {
|
|
|
|
errs() << "=======================================\n";
|
|
|
|
errs() << "BOLT is unable to proceed because it couldn't properly understand "
|
|
|
|
"this function.\n";
|
|
|
|
errs() << "If you are running the most recent version of BOLT, you may "
|
|
|
|
"want to "
|
|
|
|
"report this and paste this dump.\nPlease check that there is no "
|
|
|
|
"sensitive contents being shared in this dump.\n";
|
|
|
|
errs() << "\nOffending function: " << Function.getPrintName() << "\n\n";
|
|
|
|
ScopedPrinter SP(errs());
|
2020-02-10 15:35:11 -08:00
|
|
|
SP.printBinaryBlock("Function contents", *Function.getData());
|
2018-06-20 12:03:24 -07:00
|
|
|
errs() << "\n";
|
|
|
|
Function.dump();
|
|
|
|
errs() << "ERROR: " << Message;
|
|
|
|
errs() << "\n=======================================\n";
|
|
|
|
exit(1);
|
|
|
|
}
|
2018-07-08 12:14:08 -07:00
|
|
|
|
|
|
|
BinaryFunction *
|
|
|
|
BinaryContext::createInjectedBinaryFunction(const std::string &Name,
|
|
|
|
bool IsSimple) {
|
|
|
|
InjectedBinaryFunctions.push_back(new BinaryFunction(Name, *this, IsSimple));
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *BF = InjectedBinaryFunctions.back();
|
2018-07-08 12:14:08 -07:00
|
|
|
setSymbolToFunctionMap(BF->getSymbol(), BF);
|
2019-10-31 16:54:48 -07:00
|
|
|
BF->CurrentState = BinaryFunction::State::CFG;
|
2018-07-08 12:14:08 -07:00
|
|
|
return BF;
|
|
|
|
}
|
2018-11-15 16:02:16 -08:00
|
|
|
|
|
|
|
std::pair<size_t, size_t>
|
[BOLT][non-reloc] Change function splitting in non-relocation mode
Summary:
This diff applies to non-relocation mode mostly. In this mode, we are
limited by original function boundaries, i.e. if a function becomes
larger after optimizations (e.g. because of the newly introduced
branches) then we might not be able to write the optimized version,
unless we split the function. At the same time, we do not benefit from
function splitting as we do in the relocation mode since we are not
moving functions/fragments, and the hot code does not become more
compact.
For the reasons described above, we used to execute multiple re-write
attempts to optimize the binary and we would only split functions that
were too large to fit into their original space.
After the first attempt, we would know functions that did not fit
into their original space. Then we would re-run all our passes again
feeding back the function information and forcefully splitting
such functions. Some functions still wouldn't fit even after the
splitting (mostly because of the branch relaxation for conditional tail
calls that does not happen in non-relocation mode). Yet we have emitted
debug info as if they were successfully overwritten. That's why we had
one more stage to write the functions again, marking failed-to-emit
functions non-simple. Sadly, there was a bug in the way 2nd and 3rd
attempts interacted, and we were not splitting the functions correctly
and as a result we were emitting less optimized code.
One of the reasons we had the multi-pass rewrite scheme in place, was
that we did not have an ability to precisely estimate the code size
before the actual code emission. Recently, BinaryContext obtained such
functionality, and now we can use it instead of relying on the
multi-pass rewrite. This eliminates redundant work of re-running
the same function passes multiple times.
Because function splitting runs before a number of optimization passes
that run on post-CFG state (those rely on the splitting pass), we
cannot estimate the non-split code size with 100% accuracy. However,
it is good enough for over 99% of the cases to extract most of the
performance gains for the binary.
As a result of eliminating the multi-pass rewrite, the processing time
in non-relocation mode with `-split-functions=2` is greatly reduced.
With debug info update, it is less than half of what it used to be.
New semantics for `-split-functions=<n>`:
-split-functions - split functions into hot and cold regions
=0 - do not split any function
=1 - in non-relocation mode only split functions too large to fit
into original code space
=2 - same as 1 (backwards compatibility)
=3 - split all functions
(cherry picked from FBD17362607)
2019-09-11 15:42:22 -07:00
|
|
|
BinaryContext::calculateEmittedSize(BinaryFunction &BF, bool FixBranches) {
|
2018-11-15 16:02:16 -08:00
|
|
|
// Adjust branch instruction to match the current layout.
|
[BOLT][non-reloc] Change function splitting in non-relocation mode
Summary:
This diff applies to non-relocation mode mostly. In this mode, we are
limited by original function boundaries, i.e. if a function becomes
larger after optimizations (e.g. because of the newly introduced
branches) then we might not be able to write the optimized version,
unless we split the function. At the same time, we do not benefit from
function splitting as we do in the relocation mode since we are not
moving functions/fragments, and the hot code does not become more
compact.
For the reasons described above, we used to execute multiple re-write
attempts to optimize the binary and we would only split functions that
were too large to fit into their original space.
After the first attempt, we would know functions that did not fit
into their original space. Then we would re-run all our passes again
feeding back the function information and forcefully splitting
such functions. Some functions still wouldn't fit even after the
splitting (mostly because of the branch relaxation for conditional tail
calls that does not happen in non-relocation mode). Yet we have emitted
debug info as if they were successfully overwritten. That's why we had
one more stage to write the functions again, marking failed-to-emit
functions non-simple. Sadly, there was a bug in the way 2nd and 3rd
attempts interacted, and we were not splitting the functions correctly
and as a result we were emitting less optimized code.
One of the reasons we had the multi-pass rewrite scheme in place, was
that we did not have an ability to precisely estimate the code size
before the actual code emission. Recently, BinaryContext obtained such
functionality, and now we can use it instead of relying on the
multi-pass rewrite. This eliminates redundant work of re-running
the same function passes multiple times.
Because function splitting runs before a number of optimization passes
that run on post-CFG state (those rely on the splitting pass), we
cannot estimate the non-split code size with 100% accuracy. However,
it is good enough for over 99% of the cases to extract most of the
performance gains for the binary.
As a result of eliminating the multi-pass rewrite, the processing time
in non-relocation mode with `-split-functions=2` is greatly reduced.
With debug info update, it is less than half of what it used to be.
New semantics for `-split-functions=<n>`:
-split-functions - split functions into hot and cold regions
=0 - do not split any function
=1 - in non-relocation mode only split functions too large to fit
into original code space
=2 - same as 1 (backwards compatibility)
=3 - split all functions
(cherry picked from FBD17362607)
2019-09-11 15:42:22 -07:00
|
|
|
if (FixBranches)
|
|
|
|
BF.fixBranches();
|
2018-11-15 16:02:16 -08:00
|
|
|
|
|
|
|
// Create local MC context to isolate the effect of ephemeral code emission.
|
2021-04-08 00:19:26 -07:00
|
|
|
IndependentCodeEmitter MCEInstance = createIndependentMCCodeEmitter();
|
|
|
|
MCContext *LocalCtx = MCEInstance.LocalCtx.get();
|
|
|
|
MCAsmBackend *MAB =
|
|
|
|
TheTarget->createMCAsmBackend(*STI, *MRI, MCTargetOptions());
|
2019-07-08 12:32:58 -07:00
|
|
|
|
2018-11-15 16:02:16 -08:00
|
|
|
SmallString<256> Code;
|
|
|
|
raw_svector_ostream VecOS(Code);
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
std::unique_ptr<MCObjectWriter> OW = MAB->createObjectWriter(VecOS);
|
2018-11-15 16:02:16 -08:00
|
|
|
std::unique_ptr<MCStreamer> Streamer(TheTarget->createMCObjectStreamer(
|
2020-12-01 16:29:39 -08:00
|
|
|
*TheTriple, *LocalCtx, std::unique_ptr<MCAsmBackend>(MAB), std::move(OW),
|
2019-07-08 12:32:58 -07:00
|
|
|
std::unique_ptr<MCCodeEmitter>(MCEInstance.MCE.release()), *STI,
|
2020-03-06 15:06:37 -08:00
|
|
|
/*RelaxAll=*/false,
|
|
|
|
/*IncrementalLinkerCompatible=*/false,
|
|
|
|
/*DWARFMustBeAtTheEnd=*/false));
|
2018-11-15 16:02:16 -08:00
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
Streamer->initSections(false, *STI);
|
2018-11-15 16:02:16 -08:00
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
MCSection *Section = MCEInstance.LocalMOFI->getTextSection();
|
2018-11-15 16:02:16 -08:00
|
|
|
Section->setHasInstructions(true);
|
|
|
|
|
2020-11-16 14:34:51 -08:00
|
|
|
// Create symbols in the LocalCtx so that they get destroyed with it.
|
|
|
|
MCSymbol *StartLabel = LocalCtx->createTempSymbol();
|
|
|
|
MCSymbol *EndLabel = LocalCtx->createTempSymbol();
|
|
|
|
MCSymbol *ColdStartLabel = LocalCtx->createTempSymbol();
|
|
|
|
MCSymbol *ColdEndLabel = LocalCtx->createTempSymbol();
|
2018-11-15 16:02:16 -08:00
|
|
|
|
|
|
|
Streamer->SwitchSection(Section);
|
2020-12-01 16:29:39 -08:00
|
|
|
Streamer->emitLabel(StartLabel);
|
2020-03-06 15:06:37 -08:00
|
|
|
emitFunctionBody(*Streamer, BF, /*EmitColdPart=*/false,
|
|
|
|
/*EmitCodeOnly=*/true);
|
2020-12-01 16:29:39 -08:00
|
|
|
Streamer->emitLabel(EndLabel);
|
2018-11-15 16:02:16 -08:00
|
|
|
|
|
|
|
if (BF.isSplit()) {
|
2021-04-08 00:19:26 -07:00
|
|
|
MCSectionELF *ColdSection =
|
|
|
|
LocalCtx->getELFSection(BF.getColdCodeSectionName(), ELF::SHT_PROGBITS,
|
|
|
|
ELF::SHF_EXECINSTR | ELF::SHF_ALLOC);
|
2018-11-15 16:02:16 -08:00
|
|
|
ColdSection->setHasInstructions(true);
|
|
|
|
|
|
|
|
Streamer->SwitchSection(ColdSection);
|
2020-12-01 16:29:39 -08:00
|
|
|
Streamer->emitLabel(ColdStartLabel);
|
2020-03-06 15:06:37 -08:00
|
|
|
emitFunctionBody(*Streamer, BF, /*EmitColdPart=*/true,
|
|
|
|
/*EmitCodeOnly=*/true);
|
2020-12-01 16:29:39 -08:00
|
|
|
Streamer->emitLabel(ColdEndLabel);
|
|
|
|
// To avoid calling MCObjectStreamer::flushPendingLabels() which is private
|
|
|
|
Streamer->emitBytes(StringRef(""));
|
|
|
|
Streamer->SwitchSection(Section);
|
2018-11-15 16:02:16 -08:00
|
|
|
}
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
// To avoid calling MCObjectStreamer::flushPendingLabels() which is private or
|
|
|
|
// MCStreamer::Finish(), which does more than we want
|
|
|
|
Streamer->emitBytes(StringRef(""));
|
2018-11-15 16:02:16 -08:00
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
MCAssembler &Assembler =
|
2018-11-15 16:02:16 -08:00
|
|
|
static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler();
|
|
|
|
MCAsmLayout Layout(Assembler);
|
|
|
|
Assembler.layout(Layout);
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t HotSize =
|
|
|
|
Layout.getSymbolOffset(*EndLabel) - Layout.getSymbolOffset(*StartLabel);
|
|
|
|
const uint64_t ColdSize = BF.isSplit()
|
|
|
|
? Layout.getSymbolOffset(*ColdEndLabel) -
|
|
|
|
Layout.getSymbolOffset(*ColdStartLabel)
|
|
|
|
: 0ULL;
|
2018-11-15 16:02:16 -08:00
|
|
|
|
|
|
|
// Clean-up the effect of the code emission.
|
2021-04-08 00:19:26 -07:00
|
|
|
for (const MCSymbol &Symbol : Assembler.symbols()) {
|
|
|
|
MCSymbol *MutableSymbol = const_cast<MCSymbol *>(&Symbol);
|
2018-11-15 16:02:16 -08:00
|
|
|
MutableSymbol->setUndefined();
|
|
|
|
MutableSymbol->setIsRegistered(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
return std::make_pair(HotSize, ColdSize);
|
|
|
|
}
|
2019-04-03 15:52:01 -07:00
|
|
|
|
2019-11-22 14:53:20 -08:00
|
|
|
bool BinaryContext::validateEncoding(const MCInst &Inst,
|
|
|
|
ArrayRef<uint8_t> InputEncoding) const {
|
|
|
|
SmallString<256> Code;
|
|
|
|
SmallVector<MCFixup, 4> Fixups;
|
|
|
|
raw_svector_ostream VecOS(Code);
|
|
|
|
|
|
|
|
MCE->encodeInstruction(Inst, VecOS, Fixups, *STI);
|
|
|
|
auto EncodedData = ArrayRef<uint8_t>((uint8_t *)Code.data(), Code.size());
|
|
|
|
if (InputEncoding != EncodedData) {
|
2020-01-13 11:24:10 -08:00
|
|
|
if (opts::Verbosity > 1) {
|
|
|
|
errs() << "BOLT-WARNING: mismatched encoding detected\n"
|
|
|
|
<< " input: " << InputEncoding << '\n'
|
|
|
|
<< " output: " << EncodedData << '\n';
|
|
|
|
}
|
2019-11-22 14:53:20 -08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-07-27 18:07:18 -07:00
|
|
|
uint64_t BinaryContext::getHotThreshold() const {
|
|
|
|
static uint64_t Threshold{0};
|
|
|
|
if (Threshold == 0) {
|
|
|
|
Threshold = std::max((uint64_t)opts::ExecutionCountThreshold,
|
|
|
|
NumProfiledFuncs ? SumExecutionCount / (2 * NumProfiledFuncs) : 1);
|
|
|
|
}
|
|
|
|
return Threshold;
|
|
|
|
}
|
|
|
|
|
2019-04-03 15:52:01 -07:00
|
|
|
BinaryFunction *
|
|
|
|
BinaryContext::getBinaryFunctionContainingAddress(uint64_t Address,
|
[BOLT] Basic support for split functions
Summary:
This adds very basic and limited support for split functions.
In non-relocation mode, split functions are ignored, while their debug
info is properly updated. No support in the relocation mode yet.
Split functions consist of a main body and one or more fragments.
For fragments, the main part is called their parent. Any fragment
could only be entered via its parent or another fragment.
The short-term goal is to correctly update debug information for split
functions, while the long-term goal is to have a complete support
including full optimization. Note that if we don't detect split
bodies, we would have to add multiple entry points via tail calls,
which we would rather avoid.
Parent functions and fragments are represented by a `BinaryFunction`
and are marked accordingly. For now they are marked as non-simple, and
thus only supported in non-relocation mode. Once we start building a
CFG, it should be a common graph (i.e. the one that includes all
fragments) in the parent function.
The function discovery is unchanged, except for the detection of
`\.cold\.` pattern in the function name, which automatically marks the
function as a fragment of another function.
Because of the local function name ambiguity, we cannot rely on the
function name to establish child fragment and parent relationship.
Instead we rely on disassembly processing.
`BinaryContext::getBinaryFunctionContainingAddress()` now returns a
parent function if an address from its fragment is passed.
There's no jump table support at the moment. Jump tables can have
source and destinations in both fragment and parent.
Parent functions that enter their fragments via C++ exception handling
mechanism are not yet supported.
(cherry picked from FBD14970569)
2019-04-16 10:24:34 -07:00
|
|
|
bool CheckPastEnd,
|
2020-09-14 15:48:32 -07:00
|
|
|
bool UseMaxSize) {
|
2019-04-03 15:52:01 -07:00
|
|
|
auto FI = BinaryFunctions.upper_bound(Address);
|
|
|
|
if (FI == BinaryFunctions.begin())
|
|
|
|
return nullptr;
|
|
|
|
--FI;
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
const uint64_t UsedSize =
|
|
|
|
UseMaxSize ? FI->second.getMaxSize() : FI->second.getSize();
|
2019-04-03 15:52:01 -07:00
|
|
|
|
|
|
|
if (Address >= FI->first + UsedSize + (CheckPastEnd ? 1 : 0))
|
|
|
|
return nullptr;
|
[BOLT] Basic support for split functions
Summary:
This adds very basic and limited support for split functions.
In non-relocation mode, split functions are ignored, while their debug
info is properly updated. No support in the relocation mode yet.
Split functions consist of a main body and one or more fragments.
For fragments, the main part is called their parent. Any fragment
could only be entered via its parent or another fragment.
The short-term goal is to correctly update debug information for split
functions, while the long-term goal is to have a complete support
including full optimization. Note that if we don't detect split
bodies, we would have to add multiple entry points via tail calls,
which we would rather avoid.
Parent functions and fragments are represented by a `BinaryFunction`
and are marked accordingly. For now they are marked as non-simple, and
thus only supported in non-relocation mode. Once we start building a
CFG, it should be a common graph (i.e. the one that includes all
fragments) in the parent function.
The function discovery is unchanged, except for the detection of
`\.cold\.` pattern in the function name, which automatically marks the
function as a fragment of another function.
Because of the local function name ambiguity, we cannot rely on the
function name to establish child fragment and parent relationship.
Instead we rely on disassembly processing.
`BinaryContext::getBinaryFunctionContainingAddress()` now returns a
parent function if an address from its fragment is passed.
There's no jump table support at the moment. Jump tables can have
source and destinations in both fragment and parent.
Parent functions that enter their fragments via C++ exception handling
mechanism are not yet supported.
(cherry picked from FBD14970569)
2019-04-16 10:24:34 -07:00
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
return &FI->second;
|
[BOLT] Basic support for split functions
Summary:
This adds very basic and limited support for split functions.
In non-relocation mode, split functions are ignored, while their debug
info is properly updated. No support in the relocation mode yet.
Split functions consist of a main body and one or more fragments.
For fragments, the main part is called their parent. Any fragment
could only be entered via its parent or another fragment.
The short-term goal is to correctly update debug information for split
functions, while the long-term goal is to have a complete support
including full optimization. Note that if we don't detect split
bodies, we would have to add multiple entry points via tail calls,
which we would rather avoid.
Parent functions and fragments are represented by a `BinaryFunction`
and are marked accordingly. For now they are marked as non-simple, and
thus only supported in non-relocation mode. Once we start building a
CFG, it should be a common graph (i.e. the one that includes all
fragments) in the parent function.
The function discovery is unchanged, except for the detection of
`\.cold\.` pattern in the function name, which automatically marks the
function as a fragment of another function.
Because of the local function name ambiguity, we cannot rely on the
function name to establish child fragment and parent relationship.
Instead we rely on disassembly processing.
`BinaryContext::getBinaryFunctionContainingAddress()` now returns a
parent function if an address from its fragment is passed.
There's no jump table support at the moment. Jump tables can have
source and destinations in both fragment and parent.
Parent functions that enter their fragments via C++ exception handling
mechanism are not yet supported.
(cherry picked from FBD14970569)
2019-04-16 10:24:34 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
BinaryFunction *
|
2020-09-14 15:48:32 -07:00
|
|
|
BinaryContext::getBinaryFunctionAtAddress(uint64_t Address) {
|
2020-04-04 20:12:38 -07:00
|
|
|
// First, try to find a function starting at the given address. If the
|
|
|
|
// function was folded, this will get us the original folded function if it
|
|
|
|
// wasn't removed from the list, e.g. in non-relocation mode.
|
|
|
|
auto BFI = BinaryFunctions.find(Address);
|
|
|
|
if (BFI != BinaryFunctions.end()) {
|
2020-09-14 15:48:32 -07:00
|
|
|
return &BFI->second;
|
2020-04-04 20:12:38 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// We might have folded the function matching the object at the given
|
|
|
|
// address. In such case, we look for a function matching the symbol
|
|
|
|
// registered at the original address. The new function (the one that the
|
|
|
|
// original was folded into) will hold the symbol.
|
2021-04-08 00:19:26 -07:00
|
|
|
if (const BinaryData *BD = getBinaryDataAtAddress(Address)) {
|
2020-01-08 13:32:59 -08:00
|
|
|
uint64_t EntryID{0};
|
2021-04-08 00:19:26 -07:00
|
|
|
BinaryFunction *BF = getFunctionForSymbol(BD->getSymbol(), &EntryID);
|
2020-09-14 15:48:32 -07:00
|
|
|
if (BF && EntryID == 0)
|
[BOLT] Basic support for split functions
Summary:
This adds very basic and limited support for split functions.
In non-relocation mode, split functions are ignored, while their debug
info is properly updated. No support in the relocation mode yet.
Split functions consist of a main body and one or more fragments.
For fragments, the main part is called their parent. Any fragment
could only be entered via its parent or another fragment.
The short-term goal is to correctly update debug information for split
functions, while the long-term goal is to have a complete support
including full optimization. Note that if we don't detect split
bodies, we would have to add multiple entry points via tail calls,
which we would rather avoid.
Parent functions and fragments are represented by a `BinaryFunction`
and are marked accordingly. For now they are marked as non-simple, and
thus only supported in non-relocation mode. Once we start building a
CFG, it should be a common graph (i.e. the one that includes all
fragments) in the parent function.
The function discovery is unchanged, except for the detection of
`\.cold\.` pattern in the function name, which automatically marks the
function as a fragment of another function.
Because of the local function name ambiguity, we cannot rely on the
function name to establish child fragment and parent relationship.
Instead we rely on disassembly processing.
`BinaryContext::getBinaryFunctionContainingAddress()` now returns a
parent function if an address from its fragment is passed.
There's no jump table support at the moment. Jump tables can have
source and destinations in both fragment and parent.
Parent functions that enter their fragments via C++ exception handling
mechanism are not yet supported.
(cherry picked from FBD14970569)
2019-04-16 10:24:34 -07:00
|
|
|
return BF;
|
|
|
|
}
|
|
|
|
return nullptr;
|
2019-04-03 15:52:01 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
DebugAddressRangesVector BinaryContext::translateModuleAddressRanges(
|
|
|
|
const DWARFAddressRangesVector &InputRanges) const {
|
|
|
|
DebugAddressRangesVector OutputRanges;
|
|
|
|
|
2021-04-08 00:19:26 -07:00
|
|
|
for (const DWARFAddressRange Range : InputRanges) {
|
2019-04-03 15:52:01 -07:00
|
|
|
auto BFI = BinaryFunctions.lower_bound(Range.LowPC);
|
|
|
|
while (BFI != BinaryFunctions.end()) {
|
2021-04-08 00:19:26 -07:00
|
|
|
const BinaryFunction &Function = BFI->second;
|
2019-04-03 15:52:01 -07:00
|
|
|
if (Function.getAddress() >= Range.HighPC)
|
|
|
|
break;
|
2021-04-08 00:19:26 -07:00
|
|
|
const DebugAddressRangesVector FunctionRanges =
|
|
|
|
Function.getOutputAddressRanges();
|
2019-04-03 15:52:01 -07:00
|
|
|
std::move(std::begin(FunctionRanges),
|
|
|
|
std::end(FunctionRanges),
|
|
|
|
std::back_inserter(OutputRanges));
|
|
|
|
std::advance(BFI, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return OutputRanges;
|
|
|
|
}
|
[BOLT] Support for lite mode with relocations
Summary:
Add '-lite' support for relocations for improved processing time,
memory consumption, and more resilient processing of binaries with
embedded assembly code.
In lite relocation mode, BOLT will skip full processing of functions
without a profile. It will run scanExternalRefs() on such functions
to discover external references and to create internal relocations
to update references to optimized functions.
Note that we could have relied on the compiler/linker to provide
relocations for function references. However, there's no assurance
that all such references are reported. E.g., the compiler can resolve
inter-procedural references internally, leaving no relocations
for the linker.
The scan process takes about <10 seconds per 100MB of code on modern
hardware. It's a reasonable overhead to live with considering the
flexibility it provides.
If BOLT fails to scan or disassemble a function, .e.g., due to a data
object embedded in code, or an unsupported instruction, it enables a
patching mode to guarantee that the failed function will call
optimized/moved versions of functions. The patching happens at original
function entry points.
'-skip=<func1,func2,...>' option now can be used to skip processing of
arbitrary functions in the relocation mode.
With '-use-old-text' or '-strict' we require all functions to be
processed. As such, it is incompatible with '-lite' option,
and '-skip' option will only disable optimizations of listed
functions, not their disassembly and emission.
(cherry picked from FBD22040717)
2020-06-15 00:15:47 -07:00
|
|
|
|
|
|
|
} // namespace bolt
|
|
|
|
} // namespace llvm
|