2021-12-21 10:21:41 -08:00
|
|
|
//===- bolt/Core/BinaryContext.cpp - Low-level context --------------------===//
|
2015-10-14 15:35:14 -07:00
|
|
|
//
|
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
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
2021-12-21 10:21:41 -08:00
|
|
|
// This file implements the BinaryContext class.
|
|
|
|
//
|
2015-10-14 15:35:14 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2021-10-08 11:47:10 -07:00
|
|
|
#include "bolt/Core/BinaryContext.h"
|
|
|
|
#include "bolt/Core/BinaryEmitter.h"
|
|
|
|
#include "bolt/Core/BinaryFunction.h"
|
|
|
|
#include "bolt/Utils/CommandLineOpts.h"
|
|
|
|
#include "bolt/Utils/NameResolver.h"
|
|
|
|
#include "bolt/Utils/Utils.h"
|
2015-10-14 15:35:14 -07:00
|
|
|
#include "llvm/ADT/Twine.h"
|
2022-02-14 16:27:04 +01:00
|
|
|
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.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"
|
2022-02-09 08:26:30 -05:00
|
|
|
#include "llvm/MC/MCRegisterInfo.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"
|
2022-02-09 08:26:30 -05:00
|
|
|
#include "llvm/MC/MCSubtargetInfo.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"
|
2022-02-16 20:39:59 -08:00
|
|
|
#include "llvm/Support/Error.h"
|
2020-11-06 11:19:03 -08:00
|
|
|
#include "llvm/Support/Regex.h"
|
2021-12-01 21:14:56 -08:00
|
|
|
#include <algorithm>
|
[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>
|
2021-12-01 21:14:56 -08:00
|
|
|
#include <unordered_set>
|
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 {
|
|
|
|
|
2022-06-05 13:29:49 -07:00
|
|
|
cl::opt<bool> NoHugePages("no-huge-pages",
|
|
|
|
cl::desc("use regular size pages for code alignment"),
|
|
|
|
cl::Hidden, cl::cat(BoltCategory));
|
2018-09-24 20:58:31 -07:00
|
|
|
|
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
|
|
|
|
2022-06-05 13:29:49 -07:00
|
|
|
cl::opt<bool> PrintRelocations(
|
|
|
|
"print-relocations",
|
|
|
|
cl::desc("print relocations when printing functions/objects"), cl::Hidden,
|
|
|
|
cl::cat(BoltCategory));
|
2017-10-20 12:11:34 -07:00
|
|
|
|
|
|
|
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,
|
2021-12-14 16:52:51 -08:00
|
|
|
const Target *TheTarget, std::string TripleName,
|
2018-09-24 20:58:31 -07:00
|
|
|
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)
|
2021-12-14 16:52:51 -08: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)), DisAsm(std::move(DisAsm)) {
|
2018-09-24 20:58:31 -07:00
|
|
|
Relocation::Arch = this->TheTriple->getArch();
|
2022-03-10 23:04:03 +03:00
|
|
|
RegularPageSize = isAArch64() ? RegularPageSizeAArch64 : RegularPageSizeX86;
|
2018-09-24 20:58:31 -07:00
|
|
|
PageAlign = opts::NoHugePages ? RegularPageSize : HugePageSize;
|
|
|
|
}
|
|
|
|
|
2018-02-01 16:33:43 -08:00
|
|
|
BinaryContext::~BinaryContext() {
|
2021-12-20 11:07:46 -08:00
|
|
|
for (BinarySection *Section : Sections)
|
2018-02-01 16:33:43 -08:00
|
|
|
delete Section;
|
2021-12-20 11:07:46 -08:00
|
|
|
for (BinaryFunction *InjectedFunction : InjectedBinaryFunctions)
|
2018-07-08 12:14:08 -07:00
|
|
|
delete InjectedFunction;
|
2021-12-20 11:07:46 -08: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
|
|
|
/// Create BinaryContext for a given architecture \p ArchName and
|
|
|
|
/// triple \p TripleName.
|
2022-02-16 20:39:59 -08:00
|
|
|
Expected<std::unique_ptr<BinaryContext>>
|
2021-04-01 11:43:00 -07:00
|
|
|
BinaryContext::createBinaryContext(const 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";
|
2022-07-12 03:31:18 -04:00
|
|
|
FeaturesStr = "+all";
|
2020-01-15 15:23:45 -08:00
|
|
|
break;
|
|
|
|
default:
|
2022-02-16 20:39:59 -08:00
|
|
|
return createStringError(std::errc::not_supported,
|
|
|
|
"BOLT-ERROR: Unrecognized machine in ELF file");
|
2020-01-15 15:23:45 -08:00
|
|
|
}
|
|
|
|
|
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);
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!TheTarget)
|
|
|
|
return createStringError(make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: ", Error));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
std::unique_ptr<const MCRegisterInfo> MRI(
|
|
|
|
TheTarget->createMCRegInfo(TripleName));
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!MRI)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no register info for target ", TripleName));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
// Set up disassembler.
|
2022-03-29 15:54:08 -07:00
|
|
|
std::unique_ptr<MCAsmInfo> AsmInfo(
|
2020-12-01 16:29:39 -08:00
|
|
|
TheTarget->createMCAsmInfo(*MRI, TripleName, MCTargetOptions()));
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!AsmInfo)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no assembly info for target ", TripleName));
|
2022-03-29 15:54:08 -07:00
|
|
|
// BOLT creates "func@PLT" symbols for PLT entries. In function assembly dump
|
|
|
|
// we want to emit such names as using @PLT without double quotes to convey
|
|
|
|
// variant kind to the assembler. BOLT doesn't rely on the linker so we can
|
|
|
|
// override the default AsmInfo behavior to emit names the way we want.
|
|
|
|
AsmInfo->setAllowAtInName(true);
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
std::unique_ptr<const MCSubtargetInfo> STI(
|
|
|
|
TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!STI)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no subtarget info for target ", TripleName));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!MII)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no instruction info for target ", TripleName));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
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));
|
|
|
|
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!DisAsm)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no disassembler info for target ", TripleName));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
std::unique_ptr<const MCInstrAnalysis> MIA(
|
|
|
|
TheTarget->createMCInstrAnalysis(MII.get()));
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!MIA)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: failed to create instruction analysis for target ",
|
|
|
|
TripleName));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
|
|
|
|
std::unique_ptr<MCInstPrinter> InstructionPrinter(
|
|
|
|
TheTarget->createMCInstPrinter(*TheTriple, AsmPrinterVariant, *AsmInfo,
|
|
|
|
*MII, *MRI));
|
2022-02-16 20:39:59 -08:00
|
|
|
if (!InstructionPrinter)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no instruction printer for target ", TripleName));
|
2020-01-15 15:23:45 -08:00
|
|
|
InstructionPrinter->setPrintImmHex(true);
|
|
|
|
|
|
|
|
std::unique_ptr<MCCodeEmitter> MCE(
|
2022-02-16 13:09:59 +08:00
|
|
|
TheTarget->createMCCodeEmitter(*MII, *Ctx));
|
2020-01-15 15:23:45 -08:00
|
|
|
|
|
|
|
// 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),
|
2021-12-14 16:52:51 -08:00
|
|
|
std::move(InstructionPrinter), std::move(MIA), nullptr, std::move(MRI),
|
|
|
|
std::move(DisAsm));
|
2020-12-01 16:29:39 -08:00
|
|
|
|
|
|
|
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;
|
|
|
|
|
2022-02-22 19:06:25 -08:00
|
|
|
BC->SymbolicDisAsm = std::unique_ptr<MCDisassembler>(
|
|
|
|
BC->TheTarget->createMCDisassembler(*BC->STI, *BC->Ctx));
|
|
|
|
|
|
|
|
if (!BC->SymbolicDisAsm)
|
|
|
|
return createStringError(
|
|
|
|
make_error_code(std::errc::not_supported),
|
|
|
|
Twine("BOLT-ERROR: no disassembler info for target ", TripleName));
|
|
|
|
|
2022-04-19 18:48:27 +03:00
|
|
|
return std::move(BC);
|
2020-01-15 15:23:45 -08:00
|
|
|
}
|
|
|
|
|
2020-06-18 11:10:41 -07:00
|
|
|
bool BinaryContext::forceSymbolRelocations(StringRef SymbolName) const {
|
2021-12-14 16:52:51 -08:00
|
|
|
if (opts::HotText &&
|
|
|
|
(SymbolName == "__hot_start" || SymbolName == "__hot_end"))
|
2020-06-18 11:10:41 -07:00
|
|
|
return true;
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
if (opts::HotData &&
|
|
|
|
(SymbolName == "__hot_data_start" || SymbolName == "__hot_data_end"))
|
2020-06-18 11:10:41 -07:00
|
|
|
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
|
|
|
|
2021-12-14 16:52:51 -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);
|
2021-12-14 16:52:51 -08:00
|
|
|
while (
|
|
|
|
Itr != BinaryDataMap.end() &&
|
|
|
|
BD->containsRange(Itr->second->getAddress(), 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;
|
2021-12-20 11:07:46 -08:00
|
|
|
while (End != BinaryDataMap.end() && BD->isAncestorOf(End->second))
|
2018-04-20 20:03:31 -07:00
|
|
|
++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) {
|
2021-05-13 10:50:47 -07:00
|
|
|
uint64_t Addend = 0;
|
2019-06-04 15:30:22 -07:00
|
|
|
|
|
|
|
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)) {
|
2021-10-16 14:44:29 +03:00
|
|
|
BF.createIslandDependency(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()) {
|
2021-12-14 16:52:51 -08:00
|
|
|
if (BF.containsAddress(Address, /*UseMaxSize=*/isAArch64())) {
|
2019-06-04 15:30:22 -07:00
|
|
|
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"
|
2021-12-14 16:52:51 -08:00
|
|
|
<< Twine::utohexstr(Address) << " in function " << BF << '\n';
|
2019-06-04 15:30:22 -07:00
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
BF.HasInternalLabelReference = true;
|
2019-06-04 15:30:22 -07:00
|
|
|
return std::make_pair(
|
2021-12-14 16:52:51 -08:00
|
|
|
BF.addEntryPointAtOffset(Address - BF.getAddress()), Addend);
|
2019-06-04 15:30:22 -07:00
|
|
|
}
|
|
|
|
} else {
|
2022-07-07 00:01:33 +03:00
|
|
|
addInterproceduralReference(&BF, 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 =
|
2021-12-14 16:52:51 -08:00
|
|
|
getOrCreateJumpTable(BF, Address, JumpTable::JTT_PIC);
|
2019-08-19 14:06:36 -07:00
|
|
|
|
|
|
|
return std::make_pair(Symbol, Addend);
|
|
|
|
}
|
2019-06-28 09:21:27 -07:00
|
|
|
}
|
|
|
|
|
2021-12-20 11:07:46 -08: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);
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
MemoryContentsType BinaryContext::analyzeMemoryAt(uint64_t Address,
|
|
|
|
BinaryFunction &BF) {
|
2019-06-12 18:21:02 -07:00
|
|
|
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"
|
2021-12-14 16:52:51 -08:00
|
|
|
<< Twine::utohexstr(Address) << " referenced from function " << BF
|
|
|
|
<< '\n';
|
2019-06-12 18:21:02 -07:00
|
|
|
}
|
|
|
|
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
|
|
|
|
2021-12-01 21:14:56 -08:00
|
|
|
/// Check if <fragment restored name> == <parent restored name>.cold(.\d+)?
|
|
|
|
bool isPotentialFragmentByName(BinaryFunction &Fragment,
|
|
|
|
BinaryFunction &Parent) {
|
|
|
|
for (StringRef Name : Parent.getNames()) {
|
|
|
|
std::string NamePrefix = Regex::escape(NameResolver::restore(Name));
|
|
|
|
std::string NameRegex = Twine(NamePrefix, "\\.cold(\\.[0-9]+)?").str();
|
|
|
|
if (Fragment.hasRestoredNameRegex(NameRegex))
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
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?
|
2021-05-13 10:50:47 -07:00
|
|
|
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.
|
2021-05-13 10:50:47 -07:00
|
|
|
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-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()) {
|
2021-12-01 21:14:56 -08:00
|
|
|
// Parent function may or may not be already registered.
|
|
|
|
// Set parent link based on function name matching heuristic.
|
|
|
|
return registerFragment(BF, *TargetBF);
|
2020-11-12 11:54:51 -08:00
|
|
|
}
|
|
|
|
// Case 2: check if TargetBF is a fragment and BF is its parent.
|
2021-12-01 21:14:56 -08:00
|
|
|
return TargetBF->isFragment() && registerFragment(*TargetBF, BF);
|
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();
|
|
|
|
}
|
2021-12-20 11:07:46 -08:00
|
|
|
if (NextJTAddress)
|
2019-08-19 14:06:36 -07:00
|
|
|
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
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
const uint64_t Value =
|
|
|
|
(Type == JumpTable::JTT_PIC)
|
|
|
|
? Address + *getSignedValueAtAddress(EntryAddress, EntrySize)
|
|
|
|
: *getPointerAtAddress(EntryAddress);
|
2019-08-19 14:06:36 -07:00
|
|
|
|
|
|
|
// __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-12-01 21:14:56 -08:00
|
|
|
for (BinaryFunction *TargetParent : TargetBF->ParentFragments)
|
|
|
|
dbgs() << " ! its parent is "
|
|
|
|
<< (TargetParent ? TargetParent->getPrintName() : "(none)")
|
|
|
|
<< '\n';
|
2020-11-12 11:54:38 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
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);
|
2021-12-01 21:14:56 -08:00
|
|
|
LLVM_DEBUG(dbgs() << "OK: address in split fragment "
|
|
|
|
<< TargetBF->getPrintName() << '\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-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;
|
|
|
|
|
2021-05-13 10:50:47 -07:00
|
|
|
uint64_t NextJTAddress = 0;
|
2019-06-12 18:21:02 -07:00
|
|
|
auto NextJTI = std::next(JTI);
|
2021-12-20 11:07:46 -08:00
|
|
|
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())
|
2021-12-01 21:14:56 -08:00
|
|
|
FragmentsToSkip.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);
|
2021-12-01 21:14:56 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::skipMarkedFragments() {
|
|
|
|
// Unique functions in the vector.
|
|
|
|
std::unordered_set<BinaryFunction *> UniqueFunctions(FragmentsToSkip.begin(),
|
|
|
|
FragmentsToSkip.end());
|
|
|
|
// Copy the functions back to FragmentsToSkip.
|
|
|
|
FragmentsToSkip.assign(UniqueFunctions.begin(), UniqueFunctions.end());
|
|
|
|
auto addToWorklist = [&](BinaryFunction *Function) -> void {
|
|
|
|
if (UniqueFunctions.count(Function))
|
|
|
|
return;
|
|
|
|
FragmentsToSkip.push_back(Function);
|
|
|
|
UniqueFunctions.insert(Function);
|
|
|
|
};
|
2020-11-06 11:19:03 -08:00
|
|
|
// Functions containing split jump tables need to be skipped with all
|
2021-12-01 21:14:56 -08:00
|
|
|
// fragments (transitively).
|
|
|
|
for (size_t I = 0; I != FragmentsToSkip.size(); I++) {
|
|
|
|
BinaryFunction *BF = FragmentsToSkip[I];
|
|
|
|
assert(UniqueFunctions.count(BF) &&
|
|
|
|
"internal error in traversing function fragments");
|
|
|
|
if (opts::Verbosity >= 1)
|
|
|
|
errs() << "BOLT-WARNING: Ignoring " << BF->getPrintName() << '\n';
|
2022-06-10 15:48:13 -07:00
|
|
|
BF->setSimple(false);
|
|
|
|
BF->setHasSplitJumpTable(true);
|
|
|
|
|
2022-06-23 22:15:47 -07:00
|
|
|
llvm::for_each(BF->Fragments, addToWorklist);
|
|
|
|
llvm::for_each(BF->ParentFragments, addToWorklist);
|
2020-11-06 11:19:03 -08:00
|
|
|
}
|
2022-02-14 10:31:43 -08:00
|
|
|
if (!FragmentsToSkip.empty())
|
2022-06-10 15:48:13 -07:00
|
|
|
errs() << "BOLT-WARNING: skipped " << FragmentsToSkip.size() << " function"
|
2022-02-14 10:31:43 -08:00
|
|
|
<< (FragmentsToSkip.size() == 1 ? "" : "s")
|
|
|
|
<< " due to cold fragments\n";
|
2021-12-01 21:14:56 -08:00
|
|
|
FragmentsToSkip.clear();
|
2019-06-12 18:21:02 -07:00
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
MCSymbol *BinaryContext::getOrCreateGlobalSymbol(uint64_t Address, 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
|
|
|
|
2021-06-30 14:38:50 -07:00
|
|
|
MCSymbol *BinaryContext::getOrCreateUndefinedGlobalSymbol(StringRef Name) {
|
|
|
|
return Ctx->getOrCreateSymbol(Name);
|
|
|
|
}
|
|
|
|
|
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) {
|
[BOLT] Allow function fragments to point to one jump table
Resolve a crash related to split functions
Due to split function optimization, a function can be divided to two
fragments, and both fragments can access same jump table. This
violates
the assumption that a jump table can only have one parent
function,
which causes a crash during instrumentation.
We want to support the case: different functions cannot access same
jump tables, but different fragments of same function can!
As all fragments are from same function, we point JT::Parent to one
specific fragment. Right now it is the first disassembled fragment, but
we can point it to the function's main fragment later.
Functions are disassembled sequentially. Previously, at the end of
processing a function, JT::OffsetEntries is cleared, so other fragment
can no longer reuse JT::OffsetEntries. To extend the support for split
function, we only clear JT::OffsetEntries after all functions are
disassembled.
Let say A.hot and A.cold access JT of three targets {X, Y, Z}, where
X and Y are in A.hot, and Z is in A.cold. Suppose that A.hot is
disassembled first, JT::OffsetEntries = {X',Y',INVALID_OFFSET}. When
A.cold is disassembled, it cannot reuse JT::OffsetEntries above due to
different fragment start. A simple solution:
A.hot = {X',Y',INVALID_OFFSET}
A.cold = {INVALID_OFFSET, INVALID_OFFSET, INVALID_OFFSET}
We update the assertion to allow different fragments of same function
to get the same JumpTable object.
Potential improvements:
A.hot = {X',Y',INVALID_OFFSET}
A.cold = {INVALID_OFFSET, INVALID_OFFSET, Z'}
The main issue is A.hot and A.cold have separate CFGs, thus jump table
targets are still constrained within fragment bounds.
Future improvements:
A.hot = {X, Y, Z}
A.cold = {X, Y, Z}
Reviewed By: Amir
Differential Revision: https://reviews.llvm.org/D127924
2022-06-17 16:17:22 -07:00
|
|
|
auto isFragmentOf = [](BinaryFunction *Fragment, BinaryFunction *Parent) {
|
|
|
|
return (Fragment->isFragment() && Fragment->isParentFragment(Parent));
|
|
|
|
};
|
|
|
|
|
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");
|
[BOLT] Allow function fragments to point to one jump table
Resolve a crash related to split functions
Due to split function optimization, a function can be divided to two
fragments, and both fragments can access same jump table. This
violates
the assumption that a jump table can only have one parent
function,
which causes a crash during instrumentation.
We want to support the case: different functions cannot access same
jump tables, but different fragments of same function can!
As all fragments are from same function, we point JT::Parent to one
specific fragment. Right now it is the first disassembled fragment, but
we can point it to the function's main fragment later.
Functions are disassembled sequentially. Previously, at the end of
processing a function, JT::OffsetEntries is cleared, so other fragment
can no longer reuse JT::OffsetEntries. To extend the support for split
function, we only clear JT::OffsetEntries after all functions are
disassembled.
Let say A.hot and A.cold access JT of three targets {X, Y, Z}, where
X and Y are in A.hot, and Z is in A.cold. Suppose that A.hot is
disassembled first, JT::OffsetEntries = {X',Y',INVALID_OFFSET}. When
A.cold is disassembled, it cannot reuse JT::OffsetEntries above due to
different fragment start. A simple solution:
A.hot = {X',Y',INVALID_OFFSET}
A.cold = {INVALID_OFFSET, INVALID_OFFSET, INVALID_OFFSET}
We update the assertion to allow different fragments of same function
to get the same JumpTable object.
Potential improvements:
A.hot = {X',Y',INVALID_OFFSET}
A.cold = {INVALID_OFFSET, INVALID_OFFSET, Z'}
The main issue is A.hot and A.cold have separate CFGs, thus jump table
targets are still constrained within fragment bounds.
Future improvements:
A.hot = {X, Y, Z}
A.cold = {X, Y, Z}
Reviewed By: Amir
Differential Revision: https://reviews.llvm.org/D127924
2022-06-17 16:17:22 -07:00
|
|
|
bool HasMultipleParents = isFragmentOf(JT->Parent, &Function) ||
|
|
|
|
isFragmentOf(&Function, JT->Parent);
|
|
|
|
assert((JT->Parent == &Function || HasMultipleParents) &&
|
2019-05-02 17:42:06 -07:00
|
|
|
"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
|
|
|
|
[BOLT] Allow function fragments to point to one jump table
Resolve a crash related to split functions
Due to split function optimization, a function can be divided to two
fragments, and both fragments can access same jump table. This
violates
the assumption that a jump table can only have one parent
function,
which causes a crash during instrumentation.
We want to support the case: different functions cannot access same
jump tables, but different fragments of same function can!
As all fragments are from same function, we point JT::Parent to one
specific fragment. Right now it is the first disassembled fragment, but
we can point it to the function's main fragment later.
Functions are disassembled sequentially. Previously, at the end of
processing a function, JT::OffsetEntries is cleared, so other fragment
can no longer reuse JT::OffsetEntries. To extend the support for split
function, we only clear JT::OffsetEntries after all functions are
disassembled.
Let say A.hot and A.cold access JT of three targets {X, Y, Z}, where
X and Y are in A.hot, and Z is in A.cold. Suppose that A.hot is
disassembled first, JT::OffsetEntries = {X',Y',INVALID_OFFSET}. When
A.cold is disassembled, it cannot reuse JT::OffsetEntries above due to
different fragment start. A simple solution:
A.hot = {X',Y',INVALID_OFFSET}
A.cold = {INVALID_OFFSET, INVALID_OFFSET, INVALID_OFFSET}
We update the assertion to allow different fragments of same function
to get the same JumpTable object.
Potential improvements:
A.hot = {X',Y',INVALID_OFFSET}
A.cold = {INVALID_OFFSET, INVALID_OFFSET, Z'}
The main issue is A.hot and A.cold have separate CFGs, thus jump table
targets are still constrained within fragment bounds.
Future improvements:
A.hot = {X, Y, Z}
A.cold = {X, Y, Z}
Reviewed By: Amir
Differential Revision: https://reviews.llvm.org/D127924
2022-06-17 16:17:22 -07:00
|
|
|
// Flush OffsetEntries with INVALID_OFFSET if multiple parents
|
|
|
|
// Duplicate the entry for the parent function for easy access
|
|
|
|
if (HasMultipleParents) {
|
|
|
|
if (opts::Verbosity > 2) {
|
|
|
|
outs() << "BOLT-WARNING: Multiple fragments access same jump table: "
|
|
|
|
<< JT->Parent->getPrintName() << "; " << Function.getPrintName()
|
|
|
|
<< "\n";
|
|
|
|
}
|
|
|
|
constexpr uint64_t INVALID_OFFSET = std::numeric_limits<uint64_t>::max();
|
|
|
|
for (unsigned I = 0; I < JT->OffsetEntries.size(); ++I)
|
|
|
|
JT->OffsetEntries[I] = INVALID_OFFSET;
|
|
|
|
Function.JumpTables.emplace(Address, JT);
|
|
|
|
}
|
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.
|
2021-05-13 10:50:47 -07:00
|
|
|
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");
|
2022-05-17 14:30:00 -07:00
|
|
|
(void)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);
|
2021-12-20 11:07:46 -08:00
|
|
|
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;
|
2021-05-13 10:50:47 -07:00
|
|
|
uint64_t InstrSize = 0;
|
[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
|
|
|
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) {
|
2021-12-14 16:52:51 -08:00
|
|
|
if (!DisAsm->getInstruction(Instr, InstrSize, FunctionData->slice(Offset),
|
|
|
|
InstrAddress, nulls()))
|
[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
|
|
|
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) {
|
2021-05-13 10:50:47 -07:00
|
|
|
uint64_t TargetAddress = 0;
|
[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
|
|
|
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).
|
2021-12-14 16:52:51 -08:00
|
|
|
while (skipInstructions(isNoop) || skipInstructions(isSkipJump) ||
|
[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
|
|
|
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())
|
2021-12-14 16:52:51 -08:00
|
|
|
<< " starting at offset " << (Offset - BF.getSize())
|
|
|
|
<< " in function " << BF << '\n'
|
2019-07-31 16:03:49 -07:00
|
|
|
<< 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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
MCSymbol *BinaryContext::registerNameAtAddress(StringRef Name, uint64_t Address,
|
2017-11-14 20:05:11 -08:00
|
|
|
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();
|
2021-12-14 16:52:51 -08:00
|
|
|
BD = new BinaryData(*Symbol, Address, Size, Alignment ? Alignment : 1,
|
|
|
|
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()))) {
|
2021-12-20 11:07:46 -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
|
2021-11-08 19:54:05 -08:00
|
|
|
// affect anything.
|
2018-03-13 18:59:22 -07:00
|
|
|
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) {
|
2022-06-23 22:15:47 -07:00
|
|
|
auto Itr = llvm::find_if(BD.getSymbols(), [&](const MCSymbol *Symbol) {
|
|
|
|
return !isInternalSymbolName(Symbol->getName());
|
|
|
|
});
|
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");
|
2021-12-14 16:52:51 -08:00
|
|
|
std::string NewName =
|
|
|
|
(Twine(Name.substr(0, Idx)) + "_" + Twine::utohexstr(Hash)).str();
|
2018-06-06 03:17:32 -07:00
|
|
|
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;
|
|
|
|
}
|
2021-12-14 16:52:51 -08:00
|
|
|
BD.Symbols.insert(BD.Symbols.begin(), Ctx->getOrCreateSymbol(NewName));
|
2018-06-06 03:17:32 -07:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-12-01 21:14:56 -08:00
|
|
|
bool BinaryContext::registerFragment(BinaryFunction &TargetFunction,
|
2020-11-06 10:27:33 -08:00
|
|
|
BinaryFunction &Function) const {
|
2021-12-01 21:14:56 -08:00
|
|
|
if (!isPotentialFragmentByName(TargetFunction, Function))
|
|
|
|
return false;
|
|
|
|
assert(TargetFunction.isFragment() && "TargetFunction must be a fragment");
|
|
|
|
if (TargetFunction.isParentFragment(&Function))
|
|
|
|
return true;
|
|
|
|
TargetFunction.addParentFragment(Function);
|
2020-11-06 10:27:33 -08:00
|
|
|
Function.addFragment(TargetFunction);
|
|
|
|
if (!HasRelocations) {
|
|
|
|
TargetFunction.setSimple(false);
|
|
|
|
Function.setSimple(false);
|
|
|
|
}
|
|
|
|
if (opts::Verbosity >= 1) {
|
2021-12-14 16:52:51 -08:00
|
|
|
outs() << "BOLT-INFO: marking " << TargetFunction << " as a fragment of "
|
|
|
|
<< Function << '\n';
|
2020-11-06 10:27:33 -08:00
|
|
|
}
|
2021-12-01 21:14:56 -08:00
|
|
|
return true;
|
2020-11-06 10:27:33 -08:00
|
|
|
}
|
|
|
|
|
2022-07-07 00:01:33 +03:00
|
|
|
void BinaryContext::addAdrpAddRelocAArch64(BinaryFunction &BF,
|
|
|
|
MCInst &LoadLowBits,
|
|
|
|
MCInst &LoadHiBits,
|
|
|
|
uint64_t Target) {
|
|
|
|
const MCSymbol *TargetSymbol;
|
|
|
|
uint64_t Addend = 0;
|
|
|
|
std::tie(TargetSymbol, Addend) = handleAddressRef(Target, BF,
|
|
|
|
/*IsPCRel*/ true);
|
|
|
|
int64_t Val;
|
|
|
|
MIB->replaceImmWithSymbolRef(LoadHiBits, TargetSymbol, Addend, Ctx.get(), Val,
|
|
|
|
ELF::R_AARCH64_ADR_PREL_PG_HI21);
|
|
|
|
MIB->replaceImmWithSymbolRef(LoadLowBits, TargetSymbol, Addend, Ctx.get(),
|
|
|
|
Val, ELF::R_AARCH64_ADD_ABS_LO12_NC);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool BinaryContext::handleAArch64Veneer(uint64_t Address, bool MatchOnly) {
|
|
|
|
BinaryFunction *TargetFunction = getBinaryFunctionContainingAddress(Address);
|
|
|
|
if (TargetFunction)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
|
|
|
|
assert(Section && "cannot get section for referenced address");
|
|
|
|
if (!Section->isText())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
bool Ret = false;
|
|
|
|
StringRef SectionContents = Section->getContents();
|
|
|
|
uint64_t Offset = Address - Section->getAddress();
|
|
|
|
const uint64_t MaxSize = SectionContents.size() - Offset;
|
|
|
|
const uint8_t *Bytes =
|
|
|
|
reinterpret_cast<const uint8_t *>(SectionContents.data());
|
|
|
|
ArrayRef<uint8_t> Data(Bytes + Offset, MaxSize);
|
|
|
|
|
|
|
|
auto matchVeneer = [&](BinaryFunction::InstrMapType &Instructions,
|
|
|
|
MCInst &Instruction, uint64_t Offset,
|
|
|
|
uint64_t AbsoluteInstrAddr,
|
|
|
|
uint64_t TotalSize) -> bool {
|
|
|
|
MCInst *TargetHiBits, *TargetLowBits;
|
|
|
|
uint64_t TargetAddress, Count;
|
|
|
|
Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
|
|
|
|
AbsoluteInstrAddr, Instruction, TargetHiBits,
|
|
|
|
TargetLowBits, TargetAddress);
|
|
|
|
if (!Count)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
if (MatchOnly)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// NOTE The target symbol was created during disassemble's
|
|
|
|
// handleExternalReference
|
|
|
|
const MCSymbol *VeneerSymbol = getOrCreateGlobalSymbol(Address, "FUNCat");
|
|
|
|
BinaryFunction *Veneer = createBinaryFunction(VeneerSymbol->getName().str(),
|
|
|
|
*Section, Address, TotalSize);
|
|
|
|
addAdrpAddRelocAArch64(*Veneer, *TargetLowBits, *TargetHiBits,
|
|
|
|
TargetAddress);
|
|
|
|
MIB->addAnnotation(Instruction, "AArch64Veneer", true);
|
|
|
|
Veneer->addInstruction(Offset, std::move(Instruction));
|
|
|
|
--Count;
|
|
|
|
for (auto It = std::prev(Instructions.end()); Count != 0;
|
|
|
|
It = std::prev(It), --Count) {
|
|
|
|
MIB->addAnnotation(It->second, "AArch64Veneer", true);
|
|
|
|
Veneer->addInstruction(It->first, std::move(It->second));
|
|
|
|
}
|
|
|
|
|
|
|
|
Veneer->getOrCreateLocalLabel(Address);
|
|
|
|
Veneer->setMaxSize(TotalSize);
|
|
|
|
Veneer->updateState(BinaryFunction::State::Disassembled);
|
|
|
|
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: handling veneer function at 0x" << Address
|
|
|
|
<< "\n");
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
uint64_t Size = 0, TotalSize = 0;
|
|
|
|
BinaryFunction::InstrMapType VeneerInstructions;
|
|
|
|
for (Offset = 0; Offset < MaxSize; Offset += Size) {
|
|
|
|
MCInst Instruction;
|
|
|
|
const uint64_t AbsoluteInstrAddr = Address + Offset;
|
|
|
|
if (!SymbolicDisAsm->getInstruction(Instruction, Size, Data.slice(Offset),
|
|
|
|
AbsoluteInstrAddr, nulls()))
|
|
|
|
break;
|
|
|
|
|
|
|
|
TotalSize += Size;
|
|
|
|
if (MIB->isBranch(Instruction)) {
|
|
|
|
Ret = matchVeneer(VeneerInstructions, Instruction, Offset,
|
|
|
|
AbsoluteInstrAddr, TotalSize);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
VeneerInstructions.emplace(Offset, std::move(Instruction));
|
|
|
|
}
|
|
|
|
|
|
|
|
return Ret;
|
|
|
|
}
|
|
|
|
|
|
|
|
void BinaryContext::processInterproceduralReferences() {
|
|
|
|
for (const std::pair<BinaryFunction *, uint64_t> &It :
|
|
|
|
InterproceduralReferences) {
|
|
|
|
BinaryFunction &Function = *It.first;
|
|
|
|
uint64_t Address = It.second;
|
|
|
|
if (!Address || Function.isIgnored())
|
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) {
|
2022-07-07 00:01:33 +03:00
|
|
|
if (TargetFunction->isFragment() &&
|
2021-12-01 21:14:56 -08:00
|
|
|
!registerFragment(*TargetFunction, Function)) {
|
|
|
|
errs() << "BOLT-WARNING: interprocedural reference between unrelated "
|
|
|
|
"fragments: "
|
|
|
|
<< Function.getPrintName() << " and "
|
|
|
|
<< TargetFunction->getPrintName() << '\n';
|
|
|
|
}
|
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
|
|
|
|
2022-07-07 00:01:33 +03:00
|
|
|
// Check if it is aarch64 veneer written at Address
|
|
|
|
if (isAArch64() && handleAArch64Veneer(Address))
|
|
|
|
continue;
|
|
|
|
|
2020-09-14 15:48:32 -07:00
|
|
|
if (opts::processAllFunctions()) {
|
|
|
|
errs() << "BOLT-ERROR: cannot process binaries with unmarked "
|
2021-12-14 16:52:51 -08:00
|
|
|
<< "object in code at address 0x" << Twine::utohexstr(Address)
|
|
|
|
<< " belonging to section " << SectionName << " in current mode\n";
|
2020-09-14 15:48:32 -07:00
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
TargetFunction = getBinaryFunctionContainingAddress(Address,
|
|
|
|
/*CheckPastEnd=*/false,
|
|
|
|
/*UseMaxSize=*/true);
|
2020-09-14 15:48:32 -07:00
|
|
|
// 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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-07 00:01:33 +03:00
|
|
|
InterproceduralReferences.clear();
|
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")) &&
|
2021-12-14 16:52:51 -08:00
|
|
|
!BD->getParent() && !BD->getSize() && !BD->isAbsolute() &&
|
2017-11-14 20:05:11 -08:00
|
|
|
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);
|
2022-05-17 14:30:00 -07:00
|
|
|
(void)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.
|
2022-06-23 22:15:47 -07:00
|
|
|
llvm::move(ChildBF.Aliases, std::back_inserter(ParentBF.Aliases));
|
2020-01-13 11:56:59 -08:00
|
|
|
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();
|
2021-06-18 14:35:39 -07:00
|
|
|
ChildBF.clearDisasmState();
|
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;
|
2021-12-14 16:52:51 -08:00
|
|
|
bool isHole = (!BD->getParent() && !BD->getSize() && BD->isObject() &&
|
2017-11-14 20:05:11 -08:00
|
|
|
(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;
|
|
|
|
}
|
|
|
|
|
2021-12-20 11:07:46 -08:00
|
|
|
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");
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
void BinaryContext::printGlobalSymbols(raw_ostream &OS) const {
|
|
|
|
const BinarySection *CurrentSection = nullptr;
|
2017-11-14 20:05:11 -08:00
|
|
|
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) << ":"
|
2021-12-14 16:52:51 -08:00
|
|
|
<< "0x" + Twine::utohexstr(Address + Size) << "/" << Size << "\n";
|
2017-11-14 20:05:11 -08:00
|
|
|
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";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-21 15:47:49 -07:00
|
|
|
Expected<unsigned> BinaryContext::getDwarfFile(
|
|
|
|
StringRef Directory, StringRef FileName, unsigned FileNumber,
|
|
|
|
Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source,
|
|
|
|
unsigned CUID, unsigned DWARFVersion) {
|
2021-09-01 21:40:54 -07:00
|
|
|
DwarfLineTable &Table = DwarfLineTablesCUMap[CUID];
|
2022-04-21 15:47:49 -07:00
|
|
|
return Table.tryGetFile(Directory, FileName, Checksum, Source, DWARFVersion,
|
|
|
|
FileNumber);
|
2021-09-01 21:40:54 -07:00
|
|
|
}
|
|
|
|
|
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 != "");
|
2022-04-21 15:47:49 -07:00
|
|
|
DWARFCompileUnit *DstUnit = DwCtx->getCompileUnitForOffset(DestCUID);
|
|
|
|
return cantFail(getDwarfFile(Dir, FileName, 0, None, None, DestCUID,
|
|
|
|
DstUnit->getVersion()));
|
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());
|
2022-06-23 22:15:47 -07:00
|
|
|
llvm::transform(BinaryFunctions, SortedFunctions.begin(),
|
|
|
|
[](std::pair<const uint64_t, BinaryFunction> &BFI) {
|
|
|
|
return &BFI.second;
|
|
|
|
});
|
|
|
|
|
|
|
|
llvm::stable_sort(SortedFunctions,
|
|
|
|
[](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());
|
2022-06-23 22:15:47 -07:00
|
|
|
llvm::transform(BinaryFunctions, std::back_inserter(AllFunctions),
|
|
|
|
[](std::pair<const uint64_t, BinaryFunction> &BFI) {
|
|
|
|
return &BFI.second;
|
|
|
|
});
|
|
|
|
llvm::copy(InjectedBinaryFunctions, std::back_inserter(AllFunctions));
|
2020-10-09 16:06:27 -07:00
|
|
|
|
|
|
|
return AllFunctions;
|
|
|
|
}
|
|
|
|
|
2021-04-01 11:43:00 -07:00
|
|
|
Optional<DWARFUnit *> BinaryContext::getDWOCU(uint64_t DWOId) {
|
|
|
|
auto Iter = DWOCUs.find(DWOId);
|
|
|
|
if (Iter == DWOCUs.end())
|
|
|
|
return None;
|
|
|
|
|
|
|
|
return Iter->second;
|
|
|
|
}
|
|
|
|
|
2022-06-11 11:58:10 -07:00
|
|
|
DWARFContext *BinaryContext::getDWOContext() const {
|
2021-06-18 15:57:34 -07:00
|
|
|
if (DWOCUs.empty())
|
|
|
|
return nullptr;
|
|
|
|
return &DWOCUs.begin()->second->getContext();
|
|
|
|
}
|
|
|
|
|
2021-04-01 11:43:00 -07:00
|
|
|
/// Handles DWO sections that can either be in .o, .dwo or .dwp files.
|
|
|
|
void BinaryContext::preprocessDWODebugInfo() {
|
2021-06-16 09:52:03 -07:00
|
|
|
for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
|
|
|
|
DWARFUnit *const DwarfUnit = CU.get();
|
|
|
|
if (llvm::Optional<uint64_t> DWOId = DwarfUnit->getDWOId()) {
|
|
|
|
DWARFUnit *DWOCU = DwarfUnit->getNonSkeletonUnitDIE(false).getDwarfUnit();
|
|
|
|
if (!DWOCU->isDWOUnit()) {
|
|
|
|
std::string DWOName = dwarf::toString(
|
|
|
|
DwarfUnit->getUnitDIE().find(
|
|
|
|
{dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
|
|
|
|
"");
|
|
|
|
outs() << "BOLT-WARNING: Debug Fission: DWO debug information for "
|
|
|
|
<< DWOName
|
|
|
|
<< " was not retrieved and won't be updated. Please check "
|
|
|
|
"relative path.\n";
|
|
|
|
continue;
|
2021-04-01 11:43:00 -07:00
|
|
|
}
|
2021-06-16 09:52:03 -07:00
|
|
|
DWOCUs[*DWOId] = DWOCU;
|
2021-04-01 11:43:00 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
bool operator<(const CURange &Other) const { return LowPC < Other.LowPC; }
|
2020-10-12 21:04:42 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
// 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()});
|
|
|
|
}
|
2022-04-21 15:47:49 -07:00
|
|
|
|
|
|
|
ContainsDwarf5 |= CU->getVersion() >= 5;
|
|
|
|
ContainsDwarfLegacy |= CU->getVersion() < 5;
|
2020-10-12 21:04:42 -07:00
|
|
|
}
|
|
|
|
|
2022-06-23 22:15:47 -07:00
|
|
|
llvm::sort(AllRanges);
|
2020-10-12 21:04:42 -07:00
|
|
|
for (auto &KV : BinaryFunctions) {
|
|
|
|
const uint64_t FunctionAddress = KV.first;
|
|
|
|
BinaryFunction &Function = KV.second;
|
|
|
|
|
2022-06-23 22:15:47 -07:00
|
|
|
auto It = llvm::partition_point(
|
|
|
|
AllRanges, [=](CURange R) { return R.HighPC <= FunctionAddress; });
|
|
|
|
if (It != AllRanges.end() && It->LowPC <= FunctionAddress)
|
2020-10-12 21:04:42 -07:00
|
|
|
Function.setDWARFUnit(It->Unit);
|
|
|
|
}
|
|
|
|
|
2021-10-11 12:05:34 -07:00
|
|
|
// Discover units with debug info that needs to be updated.
|
|
|
|
for (const auto &KV : BinaryFunctions) {
|
|
|
|
const BinaryFunction &BF = KV.second;
|
|
|
|
if (shouldEmit(BF) && BF.getDWARFUnit())
|
|
|
|
ProcessedCUs.insert(BF.getDWARFUnit());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clear debug info for functions from units that we are not going to process.
|
|
|
|
for (auto &KV : BinaryFunctions) {
|
|
|
|
BinaryFunction &BF = KV.second;
|
|
|
|
if (BF.getDWARFUnit() && !ProcessedCUs.count(BF.getDWARFUnit()))
|
|
|
|
BF.setDWARFUnit(nullptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (opts::Verbosity >= 1) {
|
|
|
|
outs() << "BOLT-INFO: " << ProcessedCUs.size() << " out of "
|
|
|
|
<< DwCtx->getNumCompileUnits() << " CUs will be updated\n";
|
|
|
|
}
|
|
|
|
|
2022-05-05 14:57:14 -07:00
|
|
|
preprocessDWODebugInfo();
|
|
|
|
|
2020-10-12 21:04:42 -07:00
|
|
|
// 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();
|
2022-04-21 15:47:49 -07:00
|
|
|
DwarfLineTable &BinaryLineTable = getDwarfLineTable(CUID);
|
|
|
|
BinaryLineTable.setLabel(Ctx->getOrCreateSymbol(
|
2021-10-11 12:05:34 -07:00
|
|
|
GlobalPrefix + "line_table_start" + Twine(CUID)));
|
|
|
|
|
|
|
|
if (!ProcessedCUs.count(CU.get()))
|
|
|
|
continue;
|
|
|
|
|
2020-10-12 21:04:42 -07:00
|
|
|
const DWARFDebugLine::LineTable *LineTable =
|
2021-10-11 12:05:34 -07:00
|
|
|
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
|
|
|
|
2022-04-21 15:47:49 -07:00
|
|
|
uint16_t DwarfVersion = LineTable->Prologue.getVersion();
|
|
|
|
if (DwarfVersion >= 5) {
|
|
|
|
Optional<MD5::MD5Result> Checksum = None;
|
|
|
|
if (LineTable->Prologue.ContentTypes.HasMD5)
|
|
|
|
Checksum = LineTable->Prologue.FileNames[0].Checksum;
|
2022-05-05 14:57:14 -07:00
|
|
|
Optional<const char *> Name =
|
|
|
|
dwarf::toString(CU->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
|
|
|
|
if (Optional<uint64_t> DWOID = CU->getDWOId()) {
|
|
|
|
auto Iter = DWOCUs.find(*DWOID);
|
|
|
|
assert(Iter != DWOCUs.end() && "DWO CU was not found.");
|
|
|
|
Name = dwarf::toString(
|
|
|
|
Iter->second->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
|
|
|
|
}
|
|
|
|
BinaryLineTable.setRootFile(CU->getCompilationDir(), *Name, Checksum,
|
|
|
|
None);
|
2022-04-21 15:47:49 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
BinaryLineTable.setDwarfVersion(DwarfVersion);
|
|
|
|
|
2020-12-01 16:29:39 -08:00
|
|
|
// Assign a unique label to every line table, one per CU.
|
2018-08-27 20:12:59 -07:00
|
|
|
// Make sure empty debug line tables are registered too.
|
|
|
|
if (FileNames.empty()) {
|
2022-04-21 15:47:49 -07:00
|
|
|
cantFail(
|
|
|
|
getDwarfFile("", "<unknown>", 0, None, None, CUID, DwarfVersion));
|
2018-08-27 20:12:59 -07:00
|
|
|
continue;
|
|
|
|
}
|
2022-04-21 15:47:49 -07:00
|
|
|
const uint32_t Offset = DwarfVersion < 5 ? 1 : 0;
|
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 = "";
|
2022-04-21 15:47:49 -07:00
|
|
|
if (FileNames[I].DirIdx != 0 || DwarfVersion >= 5)
|
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
|
2022-04-21 15:47:49 -07:00
|
|
|
.IncludeDirectories[FileNames[I].DirIdx - Offset]))
|
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 != "");
|
2022-04-21 15:47:49 -07:00
|
|
|
Optional<MD5::MD5Result> Checksum = None;
|
|
|
|
if (DwarfVersion >= 5 && LineTable->Prologue.ContentTypes.HasMD5)
|
|
|
|
Checksum = LineTable->Prologue.FileNames[I].Checksum;
|
|
|
|
cantFail(
|
|
|
|
getDwarfFile(Dir, FileName, 0, Checksum, None, CUID, DwarfVersion));
|
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 {
|
2022-03-20 16:10:27 +03:00
|
|
|
if (Function.isPseudo())
|
|
|
|
return false;
|
|
|
|
|
[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 (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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-31 11:50:59 -07:00
|
|
|
MarkerSymType BinaryContext::getMarkerType(const SymbolRef &Symbol) const {
|
|
|
|
// For aarch64, the ABI defines mapping symbols so we identify data in the
|
|
|
|
// code section (see IHI0056B). $x identifies a symbol starting code or the
|
|
|
|
// end of a data chunk inside code, $d indentifies start of data.
|
|
|
|
if (!isAArch64() || ELFSymbolRef(Symbol).getSize())
|
|
|
|
return MarkerSymType::NONE;
|
|
|
|
|
|
|
|
Expected<StringRef> NameOrError = Symbol.getName();
|
|
|
|
Expected<object::SymbolRef::Type> TypeOrError = Symbol.getType();
|
|
|
|
|
|
|
|
if (!TypeOrError || !NameOrError)
|
|
|
|
return MarkerSymType::NONE;
|
|
|
|
|
|
|
|
if (*TypeOrError != SymbolRef::ST_Unknown)
|
|
|
|
return MarkerSymType::NONE;
|
|
|
|
|
|
|
|
if (*NameOrError == "$x" || NameOrError->startswith("$x."))
|
|
|
|
return MarkerSymType::CODE;
|
|
|
|
|
|
|
|
if (*NameOrError == "$d" || NameOrError->startswith("$d."))
|
|
|
|
return MarkerSymType::DATA;
|
|
|
|
|
|
|
|
return MarkerSymType::NONE;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool BinaryContext::isMarker(const SymbolRef &Symbol) const {
|
|
|
|
return getMarkerType(Symbol) != MarkerSymType::NONE;
|
|
|
|
}
|
|
|
|
|
2022-06-11 11:58:10 -07:00
|
|
|
static void printDebugInfo(raw_ostream &OS, const MCInst &Instruction,
|
|
|
|
const BinaryFunction *Function,
|
|
|
|
DWARFContext *DwCtx) {
|
|
|
|
DebugLineTableRowRef RowRef =
|
|
|
|
DebugLineTableRowRef::fromSMLoc(Instruction.getLoc());
|
|
|
|
if (RowRef == DebugLineTableRowRef::NULL_ROW)
|
|
|
|
return;
|
|
|
|
|
|
|
|
const DWARFDebugLine::LineTable *LineTable;
|
|
|
|
if (Function && Function->getDWARFUnit() &&
|
|
|
|
Function->getDWARFUnit()->getOffset() == RowRef.DwCompileUnitIndex) {
|
|
|
|
LineTable = Function->getDWARFLineTable();
|
|
|
|
} else {
|
|
|
|
LineTable = DwCtx->getLineTableForUnit(
|
|
|
|
DwCtx->getCompileUnitForOffset(RowRef.DwCompileUnitIndex));
|
|
|
|
}
|
|
|
|
assert(LineTable && "line table expected for instruction with debug info");
|
|
|
|
|
|
|
|
const DWARFDebugLine::Row &Row = LineTable->Rows[RowRef.RowIndex - 1];
|
|
|
|
StringRef FileName = "";
|
|
|
|
if (Optional<const char *> FName =
|
|
|
|
dwarf::toString(LineTable->Prologue.FileNames[Row.File - 1].Name))
|
|
|
|
FileName = *FName;
|
|
|
|
OS << " # debug line " << FileName << ":" << Row.Line;
|
|
|
|
if (Row.Column)
|
|
|
|
OS << ":" << Row.Column;
|
|
|
|
if (Row.Discriminator)
|
|
|
|
OS << " discriminator:" << Row.Discriminator;
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
void BinaryContext::printInstruction(raw_ostream &OS, const MCInst &Instruction,
|
2016-07-23 08:01:53 -07:00
|
|
|
uint64_t Offset,
|
2021-12-14 16:52:51 -08:00
|
|
|
const BinaryFunction *Function,
|
|
|
|
bool PrintMCInst, bool PrintMemData,
|
2022-05-24 18:25:40 -07:00
|
|
|
bool PrintRelocations,
|
|
|
|
StringRef Endl) const {
|
2018-03-09 09:45:13 -08:00
|
|
|
if (MIB->isEHLabel(Instruction)) {
|
2022-05-24 18:25:40 -07:00
|
|
|
OS << " EH_LABEL: " << *MIB->getTargetSymbol(Instruction) << Endl;
|
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));
|
2022-05-24 18:25:40 -07:00
|
|
|
OS << Endl;
|
2016-07-23 08:01:53 -07:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
2021-08-03 17:53:32 -07:00
|
|
|
if (Optional<uint32_t> Offset = MIB->getOffset(Instruction))
|
|
|
|
OS << " # Offset: " << *Offset;
|
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
|
|
|
|
2022-06-11 11:58:10 -07:00
|
|
|
if (opts::PrintDebugInfo)
|
|
|
|
printDebugInfo(OS, Instruction, Function, DwCtx.get());
|
2016-07-23 08:01:53 -07:00
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2022-05-24 18:25:40 -07:00
|
|
|
OS << Endl;
|
2016-07-23 08:01:53 -07:00
|
|
|
|
2017-10-20 12:11:34 -07:00
|
|
|
if (PrintMCInst) {
|
2016-07-23 08:01:53 -07:00
|
|
|
Instruction.dump_pretty(OS, InstPrinter.get());
|
2022-05-24 18:25:40 -07:00
|
|
|
OS << Endl;
|
2016-07-23 08:01:53 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-13 19:39:39 -07:00
|
|
|
Optional<uint64_t>
|
|
|
|
BinaryContext::getBaseAddressForMapping(uint64_t MMapAddress,
|
|
|
|
uint64_t FileOffset) const {
|
|
|
|
// Find a segment with a matching file offset.
|
|
|
|
for (auto &KV : SegmentMapInfo) {
|
|
|
|
const SegmentInfo &SegInfo = KV.second;
|
|
|
|
if (alignDown(SegInfo.FileOffset, SegInfo.Alignment) == FileOffset) {
|
|
|
|
// Use segment's aligned memory offset to calculate the base address.
|
|
|
|
const uint64_t MemOffset = alignDown(SegInfo.Address, SegInfo.Alignment);
|
|
|
|
return MMapAddress - MemOffset;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return NoneType();
|
|
|
|
}
|
|
|
|
|
2021-06-30 14:38:50 -07: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-12-20 11:07:46 -08: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);
|
2021-06-29 12:11:56 -07:00
|
|
|
(void)Res;
|
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) {
|
2021-12-14 16:52:51 -08:00
|
|
|
return registerSection(
|
|
|
|
new BinarySection(*this, SectionName, OriginalSection));
|
2018-02-01 16:33:43 -08:00
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
BinarySection &
|
|
|
|
BinaryContext::registerOrUpdateSection(StringRef Name, unsigned ELFType,
|
|
|
|
unsigned ELFFlags, uint8_t *Data,
|
|
|
|
uint64_t Size, 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();
|
2021-06-29 12:11:56 -07:00
|
|
|
(void)Flag;
|
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;
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
return registerSection(
|
|
|
|
new BinarySection(*this, Name, Data, Size, Alignment, 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-12-20 11:07:46 -08: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);
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
ErrorOr<uint64_t> 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);
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
void BinaryContext::addRelocation(uint64_t Address, MCSymbol *Symbol,
|
|
|
|
uint64_t Type, uint64_t Addend,
|
2018-02-01 16:33:43 -08:00
|
|
|
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");
|
2021-12-14 16:52:51 -08:00
|
|
|
Section->addRelocation(Address - Section->getAddress(), Symbol, Type, Addend,
|
2018-02-01 16:33:43 -08:00
|
|
|
Value);
|
2017-02-21 16:15:15 -08:00
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
void BinaryContext::addDynamicRelocation(uint64_t Address, MCSymbol *Symbol,
|
|
|
|
uint64_t Type, uint64_t Addend,
|
2020-06-23 12:22:58 -07:00
|
|
|
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");
|
2021-12-14 16:52:51 -08:00
|
|
|
Section->addDynamicRelocation(Address - Section->getAddress(), Symbol, Type,
|
|
|
|
Addend, Value);
|
2020-06-23 12:22:58 -07:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
2022-06-10 22:50:55 -07: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);
|
|
|
|
|
2022-06-10 22:50:55 -07:00
|
|
|
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(""));
|
2022-06-10 22:50:55 -07:00
|
|
|
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 {
|
2021-05-13 10:50:47 -07:00
|
|
|
static uint64_t Threshold = 0;
|
2020-07-27 18:07:18 -07:00
|
|
|
if (Threshold == 0) {
|
2021-12-14 16:52:51 -08:00
|
|
|
Threshold = std::max(
|
|
|
|
(uint64_t)opts::ExecutionCountThreshold,
|
2020-07-27 18:07:18 -07:00
|
|
|
NumProfiledFuncs ? SumExecutionCount / (2 * NumProfiledFuncs) : 1);
|
|
|
|
}
|
|
|
|
return Threshold;
|
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
BinaryFunction *BinaryContext::getBinaryFunctionContainingAddress(
|
|
|
|
uint64_t Address, bool CheckPastEnd, 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
|
|
|
}
|
|
|
|
|
2021-12-14 16:52:51 -08:00
|
|
|
BinaryFunction *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);
|
2021-12-20 11:07:46 -08:00
|
|
|
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)) {
|
2021-05-13 10:50:47 -07: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(
|
2021-12-14 16:52:51 -08:00
|
|
|
const DWARFAddressRangesVector &InputRanges) const {
|
2019-04-03 15:52:01 -07:00
|
|
|
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();
|
2022-06-23 22:15:47 -07:00
|
|
|
llvm::move(FunctionRanges, std::back_inserter(OutputRanges));
|
2019-04-03 15:52:01 -07:00
|
|
|
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
|