2020-08-06 08:11:48 +08:00
|
|
|
//===-- BasicBlockSections.cpp ---=========--------------------------------===//
|
2020-03-17 06:56:02 +08: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
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
2020-08-06 08:11:48 +08:00
|
|
|
// BasicBlockSections implementation.
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
|
|
|
// The purpose of this pass is to assign sections to basic blocks when
|
2020-06-02 14:17:29 +08:00
|
|
|
// -fbasic-block-sections= option is used. Further, with profile information
|
|
|
|
// only the subset of basic blocks with profiles are placed in separate sections
|
|
|
|
// and the rest are grouped in a cold section. The exception handling blocks are
|
2020-04-14 03:14:42 +08:00
|
|
|
// treated specially to ensure they are all in one seciton.
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
|
|
|
// Basic Block Sections
|
|
|
|
// ====================
|
|
|
|
//
|
2020-06-02 14:17:29 +08:00
|
|
|
// With option, -fbasic-block-sections=list, every function may be split into
|
2020-04-14 03:14:42 +08:00
|
|
|
// clusters of basic blocks. Every cluster will be emitted into a separate
|
|
|
|
// section with its basic blocks sequenced in the given order. To get the
|
|
|
|
// optimized performance, the clusters must form an optimal BB layout for the
|
|
|
|
// function. Every cluster's section is labeled with a symbol to allow the
|
|
|
|
// linker to reorder the sections in any arbitrary sequence. A global order of
|
|
|
|
// these sections would encapsulate the function layout.
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
2020-04-14 03:14:42 +08:00
|
|
|
// There are a couple of challenges to be addressed:
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
2020-04-14 03:14:42 +08:00
|
|
|
// 1. The last basic block of every cluster should not have any implicit
|
|
|
|
// fallthrough to its next basic block, as it can be reordered by the linker.
|
|
|
|
// The compiler should make these fallthroughs explicit by adding
|
|
|
|
// unconditional jumps..
|
|
|
|
//
|
|
|
|
// 2. All inter-cluster branch targets would now need to be resolved by the
|
2020-03-17 06:56:02 +08:00
|
|
|
// linker as they cannot be calculated during compile time. This is done
|
|
|
|
// using static relocations. Further, the compiler tries to use short branch
|
|
|
|
// instructions on some ISAs for small branch offsets. This is not possible
|
2020-04-14 03:14:42 +08:00
|
|
|
// for inter-cluster branches as the offset is not determined at compile
|
|
|
|
// time, and therefore, long branch instructions have to be used for those.
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
2020-04-14 03:14:42 +08:00
|
|
|
// 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
|
2020-03-17 06:56:02 +08:00
|
|
|
// needs special handling with basic block sections. DebugInfo needs to be
|
|
|
|
// emitted with more relocations as basic block sections can break a
|
|
|
|
// function into potentially several disjoint pieces, and CFI needs to be
|
2020-04-14 03:14:42 +08:00
|
|
|
// emitted per cluster. This also bloats the object file and binary sizes.
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
|
|
|
// Basic Block Labels
|
|
|
|
// ==================
|
|
|
|
//
|
2020-09-15 01:16:44 +08:00
|
|
|
// With -fbasic-block-sections=labels, we emit the offsets of BB addresses of
|
2020-10-09 02:12:40 +08:00
|
|
|
// every function into the .llvm_bb_addr_map section. Along with the function
|
|
|
|
// symbols, this allows for mapping of virtual addresses in PMU profiles back to
|
|
|
|
// the corresponding basic blocks. This logic is implemented in AsmPrinter. This
|
2020-09-15 01:16:44 +08:00
|
|
|
// pass only assigns the BBSectionType of every function to ``labels``.
|
2020-03-17 06:56:02 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
#include "llvm/ADT/Optional.h"
|
2020-03-17 06:56:02 +08:00
|
|
|
#include "llvm/ADT/SmallSet.h"
|
2020-04-14 03:14:42 +08:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
2020-03-17 06:56:02 +08:00
|
|
|
#include "llvm/ADT/StringMap.h"
|
|
|
|
#include "llvm/ADT/StringRef.h"
|
2020-08-06 06:34:31 +08:00
|
|
|
#include "llvm/CodeGen/BasicBlockSectionUtils.h"
|
2020-03-17 06:56:02 +08:00
|
|
|
#include "llvm/CodeGen/MachineFunction.h"
|
|
|
|
#include "llvm/CodeGen/MachineFunctionPass.h"
|
|
|
|
#include "llvm/CodeGen/MachineModuleInfo.h"
|
|
|
|
#include "llvm/CodeGen/Passes.h"
|
|
|
|
#include "llvm/CodeGen/TargetInstrInfo.h"
|
|
|
|
#include "llvm/InitializePasses.h"
|
2020-04-14 03:14:42 +08:00
|
|
|
#include "llvm/Support/Error.h"
|
2020-03-17 06:56:02 +08:00
|
|
|
#include "llvm/Support/LineIterator.h"
|
|
|
|
#include "llvm/Support/MemoryBuffer.h"
|
|
|
|
#include "llvm/Target/TargetMachine.h"
|
|
|
|
|
|
|
|
using llvm::SmallSet;
|
2020-04-14 03:14:42 +08:00
|
|
|
using llvm::SmallVector;
|
2020-03-17 06:56:02 +08:00
|
|
|
using llvm::StringMap;
|
|
|
|
using llvm::StringRef;
|
|
|
|
using namespace llvm;
|
|
|
|
|
2020-09-17 12:40:00 +08:00
|
|
|
// Placing the cold clusters in a separate section mitigates against poor
|
|
|
|
// profiles and allows optimizations such as hugepage mapping to be applied at a
|
2020-10-08 02:42:02 +08:00
|
|
|
// section granularity. Defaults to ".text.split." which is recognized by lld
|
|
|
|
// via the `-z keep-text-section-prefix` flag.
|
2020-09-17 12:40:00 +08:00
|
|
|
cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
|
|
|
|
"bbsections-cold-text-prefix",
|
|
|
|
cl::desc("The text prefix to use for cold basic block clusters"),
|
2020-10-08 02:42:02 +08:00
|
|
|
cl::init(".text.split."), cl::Hidden);
|
2020-09-17 12:40:00 +08:00
|
|
|
|
2020-03-17 06:56:02 +08:00
|
|
|
namespace {
|
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// This struct represents the cluster information for a machine basic block.
|
|
|
|
struct BBClusterInfo {
|
|
|
|
// MachineBasicBlock ID.
|
|
|
|
unsigned MBBNumber;
|
|
|
|
// Cluster ID this basic block belongs to.
|
|
|
|
unsigned ClusterID;
|
|
|
|
// Position of basic block within the cluster.
|
|
|
|
unsigned PositionInCluster;
|
|
|
|
};
|
|
|
|
|
|
|
|
using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>;
|
|
|
|
|
2020-08-06 08:11:48 +08:00
|
|
|
class BasicBlockSections : public MachineFunctionPass {
|
2020-03-17 06:56:02 +08:00
|
|
|
public:
|
|
|
|
static char ID;
|
2020-04-14 03:14:42 +08:00
|
|
|
|
|
|
|
// This contains the basic-block-sections profile.
|
2020-03-17 06:56:02 +08:00
|
|
|
const MemoryBuffer *MBuf = nullptr;
|
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// This encapsulates the BB cluster information for the whole program.
|
|
|
|
//
|
|
|
|
// For every function name, it contains the cluster information for (all or
|
|
|
|
// some of) its basic blocks. The cluster information for every basic block
|
|
|
|
// includes its cluster ID along with the position of the basic block in that
|
|
|
|
// cluster.
|
|
|
|
ProgramBBClusterInfoMapTy ProgramBBClusterInfo;
|
|
|
|
|
|
|
|
// Some functions have alias names. We use this map to find the main alias
|
|
|
|
// name for which we have mapping in ProgramBBClusterInfo.
|
|
|
|
StringMap<StringRef> FuncAliasMap;
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-08-06 08:11:48 +08:00
|
|
|
BasicBlockSections(const MemoryBuffer *Buf)
|
2020-03-17 06:56:02 +08:00
|
|
|
: MachineFunctionPass(ID), MBuf(Buf) {
|
2020-08-06 08:11:48 +08:00
|
|
|
initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
|
2020-03-17 06:56:02 +08:00
|
|
|
};
|
|
|
|
|
2020-08-06 08:11:48 +08:00
|
|
|
BasicBlockSections() : MachineFunctionPass(ID) {
|
|
|
|
initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
|
2020-04-14 03:14:42 +08:00
|
|
|
}
|
|
|
|
|
2020-03-17 06:56:02 +08:00
|
|
|
StringRef getPassName() const override {
|
|
|
|
return "Basic Block Sections Analysis";
|
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override;
|
|
|
|
|
|
|
|
/// Read profiles of basic blocks if available here.
|
|
|
|
bool doInitialization(Module &M) override;
|
|
|
|
|
|
|
|
/// Identify basic blocks that need separate sections and prepare to emit them
|
|
|
|
/// accordingly.
|
|
|
|
bool runOnMachineFunction(MachineFunction &MF) override;
|
|
|
|
};
|
|
|
|
|
|
|
|
} // end anonymous namespace
|
|
|
|
|
2020-08-06 08:11:48 +08:00
|
|
|
char BasicBlockSections::ID = 0;
|
|
|
|
INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
|
2020-04-14 03:14:42 +08:00
|
|
|
"Prepares for basic block sections, by splitting functions "
|
|
|
|
"into clusters of basic blocks.",
|
|
|
|
false, false)
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// This function updates and optimizes the branching instructions of every basic
|
|
|
|
// block in a given function to account for changes in the layout.
|
|
|
|
static void updateBranches(
|
|
|
|
MachineFunction &MF,
|
|
|
|
const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) {
|
|
|
|
const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
|
|
|
|
SmallVector<MachineOperand, 4> Cond;
|
|
|
|
for (auto &MBB : MF) {
|
|
|
|
auto NextMBBI = std::next(MBB.getIterator());
|
|
|
|
auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
|
|
|
|
// If this block had a fallthrough before we need an explicit unconditional
|
|
|
|
// branch to that block if either
|
|
|
|
// 1- the block ends a section, which means its next block may be
|
|
|
|
// reorderd by the linker, or
|
|
|
|
// 2- the fallthrough block is not adjacent to the block in the new
|
|
|
|
// order.
|
|
|
|
if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
|
|
|
|
TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
|
|
|
|
|
|
|
|
// We do not optimize branches for machine basic blocks ending sections, as
|
|
|
|
// their adjacent block might be reordered by the linker.
|
|
|
|
if (MBB.isEndSection())
|
|
|
|
continue;
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// It might be possible to optimize branches by flipping the branch
|
|
|
|
// condition.
|
|
|
|
Cond.clear();
|
|
|
|
MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
|
|
|
|
if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
|
|
|
|
continue;
|
MachineBasicBlock::updateTerminator now requires an explicit layout successor.
Previously, it tried to infer the correct destination block from the
successor list, but this is a rather tricky propspect, given the
existence of successors that occur mid-block, such as invoke, and
potentially in the future, callbr/INLINEASM_BR. (INLINEASM_BR, in
particular would be problematic, because its successor blocks are not
distinct from "normal" successors, as EHPads are.)
Instead, require the caller to pass in the expected fallthrough
successor explicitly. In most callers, the correct block is
immediately clear. But, in MachineBlockPlacement, we do need to record
the original ordering, before starting to reorder blocks.
Unfortunately, the goal of decoupling the behavior of end-of-block
jumps from the successor list has not been fully accomplished in this
patch, as there is currently no other way to determine whether a block
is intended to fall-through, or end as unreachable. Further work is
needed there.
Differential Revision: https://reviews.llvm.org/D79605
2020-02-19 23:41:28 +08:00
|
|
|
MBB.updateTerminator(FTMBB);
|
2020-04-14 03:14:42 +08:00
|
|
|
}
|
|
|
|
}
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// This function provides the BBCluster information associated with a function.
|
|
|
|
// Returns true if a valid association exists and false otherwise.
|
|
|
|
static bool getBBClusterInfoForFunction(
|
|
|
|
const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap,
|
|
|
|
const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
|
|
|
|
std::vector<Optional<BBClusterInfo>> &V) {
|
|
|
|
// Get the main alias name for the function.
|
|
|
|
auto FuncName = MF.getName();
|
|
|
|
auto R = FuncAliasMap.find(FuncName);
|
|
|
|
StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second;
|
|
|
|
|
|
|
|
// Find the assoicated cluster information.
|
|
|
|
auto P = ProgramBBClusterInfo.find(AliasName);
|
|
|
|
if (P == ProgramBBClusterInfo.end())
|
|
|
|
return false;
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
if (P->second.empty()) {
|
|
|
|
// This indicates that sections are desired for all basic blocks of this
|
|
|
|
// function. We clear the BBClusterInfo vector to denote this.
|
|
|
|
V.clear();
|
|
|
|
return true;
|
2020-04-14 02:39:23 +08:00
|
|
|
}
|
2020-04-14 03:12:34 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
V.resize(MF.getNumBlockIDs());
|
|
|
|
for (auto bbClusterInfo : P->second) {
|
|
|
|
// Bail out if the cluster information contains invalid MBB numbers.
|
|
|
|
if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs())
|
|
|
|
return false;
|
|
|
|
V[bbClusterInfo.MBBNumber] = bbClusterInfo;
|
|
|
|
}
|
|
|
|
return true;
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// This function sorts basic blocks according to the cluster's information.
|
|
|
|
// All explicitly specified clusters of basic blocks will be ordered
|
|
|
|
// accordingly. All non-specified BBs go into a separate "Cold" section.
|
|
|
|
// Additionally, if exception handling landing pads end up in more than one
|
|
|
|
// clusters, they are moved into a single "Exception" section. Eventually,
|
|
|
|
// clusters are ordered in increasing order of their IDs, with the "Exception"
|
|
|
|
// and "Cold" succeeding all other clusters.
|
|
|
|
// FuncBBClusterInfo represent the cluster information for basic blocks. If this
|
|
|
|
// is empty, it means unique sections for all basic blocks in the function.
|
2020-08-06 06:34:31 +08:00
|
|
|
static void
|
|
|
|
assignSections(MachineFunction &MF,
|
|
|
|
const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) {
|
2020-04-14 03:14:42 +08:00
|
|
|
assert(MF.hasBBSections() && "BB Sections is not set for function.");
|
|
|
|
// This variable stores the section ID of the cluster containing eh_pads (if
|
|
|
|
// all eh_pads are one cluster). If more than one cluster contain eh_pads, we
|
|
|
|
// set it equal to ExceptionSectionID.
|
|
|
|
Optional<MBBSectionID> EHPadsSectionID;
|
2020-03-17 06:56:02 +08:00
|
|
|
|
|
|
|
for (auto &MBB : MF) {
|
2020-04-14 03:14:42 +08:00
|
|
|
// With the 'all' option, every basic block is placed in a unique section.
|
|
|
|
// With the 'list' option, every basic block is placed in a section
|
|
|
|
// associated with its cluster, unless we want individual unique sections
|
|
|
|
// for every basic block in this function (if FuncBBClusterInfo is empty).
|
|
|
|
if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
|
|
|
|
FuncBBClusterInfo.empty()) {
|
|
|
|
// If unique sections are desired for all basic blocks of the function, we
|
|
|
|
// set every basic block's section ID equal to its number (basic block
|
|
|
|
// id). This further ensures that basic blocks are ordered canonically.
|
|
|
|
MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())});
|
|
|
|
} else if (FuncBBClusterInfo[MBB.getNumber()].hasValue())
|
|
|
|
MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID);
|
|
|
|
else {
|
|
|
|
// BB goes into the special cold section if it is not specified in the
|
|
|
|
// cluster info map.
|
|
|
|
MBB.setSectionID(MBBSectionID::ColdSectionID);
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
2020-04-14 03:14:42 +08:00
|
|
|
|
|
|
|
if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
|
|
|
|
EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
|
|
|
|
// If we already have one cluster containing eh_pads, this must be updated
|
|
|
|
// to ExceptionSectionID. Otherwise, we set it equal to the current
|
|
|
|
// section ID.
|
|
|
|
EHPadsSectionID = EHPadsSectionID.hasValue()
|
|
|
|
? MBBSectionID::ExceptionSectionID
|
|
|
|
: MBB.getSectionID();
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// If EHPads are in more than one section, this places all of them in the
|
|
|
|
// special exception section.
|
|
|
|
if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
|
|
|
|
for (auto &MBB : MF)
|
2020-03-17 06:56:02 +08:00
|
|
|
if (MBB.isEHPad())
|
2020-04-14 03:14:42 +08:00
|
|
|
MBB.setSectionID(EHPadsSectionID.getValue());
|
2020-08-06 06:34:31 +08:00
|
|
|
}
|
2020-04-14 03:14:42 +08:00
|
|
|
|
2020-08-06 06:34:31 +08:00
|
|
|
void llvm::sortBasicBlocksAndUpdateBranches(
|
|
|
|
MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
|
2020-04-14 03:14:42 +08:00
|
|
|
SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs(
|
|
|
|
MF.getNumBlockIDs());
|
|
|
|
for (auto &MBB : MF)
|
|
|
|
PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
|
|
|
|
|
2020-08-06 06:34:31 +08:00
|
|
|
MF.sort(MBBCmp);
|
|
|
|
|
|
|
|
// Set IsBeginSection and IsEndSection according to the assigned section IDs.
|
|
|
|
MF.assignBeginEndSections();
|
|
|
|
|
|
|
|
// After reordering basic blocks, we must update basic block branches to
|
|
|
|
// insert explicit fallthrough branches when required and optimize branches
|
|
|
|
// when possible.
|
|
|
|
updateBranches(MF, PreLayoutFallThroughs);
|
|
|
|
}
|
|
|
|
|
Exception support for basic block sections
This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf
This patch provides exception support for basic block sections by splitting the call-site table into call-site ranges corresponding to different basic block sections. Still all landing pads must reside in the same basic block section (which is guaranteed by the the core basic block section patch D73674 (ExceptionSection) ). Each call-site table will refer to the landing pad fragment by explicitly specifying @LPstart (which is omitted in the normal non-basic-block section case). All these call-site tables will share their action and type tables.
The C++ ABI somehow assumes that no landing pads point directly to LPStart (which works in the normal case since the function begin is never a landing pad), and uses LP.offset = 0 to specify no landing pad. In the case of basic block section where one section contains all the landing pads, the landing pad offset relative to LPStart could actually be zero. Thus, we avoid zero-offset landing pads by inserting a **nop** operation as the first non-CFI instruction in the exception section.
**Background on Exception Handling in C++ ABI**
https://github.com/itanium-cxx-abi/cxx-abi/blob/master/exceptions.pdf
Compiler emits an exception table for every function. When an exception is thrown, the stack unwinding library queries the unwind table (which includes the start and end of each function) to locate the exception table for that function.
The exception table includes a call site table for the function, which is used to guide the exception handling runtime to take the appropriate action upon an exception. Each call site record in this table is structured as follows:
| CallSite | --> Position of the call site (relative to the function entry)
| CallSite length | --> Length of the call site.
| Landing Pad | --> Position of the landing pad (relative to the landing pad fragment’s begin label)
| Action record offset | --> Position of the first action record
The call site records partition a function into different pieces and describe what action must be taken for each callsite. The callsite fields are relative to the start of the function (as captured in the unwind table).
The landing pad entry is a reference into the function and corresponds roughly to the catch block of a try/catch statement. When execution resumes at a landing pad, it receives an exception structure and a selector value corresponding to the type of the exception thrown, and executes similar to a switch-case statement. The landing pad field is relative to the beginning of the procedure fragment which includes all the landing pads (@LPStart). The C++ ABI requires all landing pads to be in the same fragment. Nonetheless, without basic block sections, @LPStart is the same as the function @Start (found in the unwind table) and can be omitted.
The action record offset is an index into the action table which includes information about which exception types are caught.
**C++ Exceptions with Basic Block Sections**
Basic block sections break the contiguity of a function fragment. Therefore, call sites must be specified relative to the beginning of the basic block section. Furthermore, the unwinding library should be able to find the corresponding callsites for each section. To do so, the .cfi_lsda directive for a section must point to the range of call-sites for that section.
This patch introduces a new **CallSiteRange** structure which specifies the range of call-sites which correspond to every section:
`struct CallSiteRange {
// Symbol marking the beginning of the precedure fragment.
MCSymbol *FragmentBeginLabel = nullptr;
// Symbol marking the end of the procedure fragment.
MCSymbol *FragmentEndLabel = nullptr;
// LSDA symbol for this call-site range.
MCSymbol *ExceptionLabel = nullptr;
// Index of the first call-site entry in the call-site table which
// belongs to this range.
size_t CallSiteBeginIdx = 0;
// Index just after the last call-site entry in the call-site table which
// belongs to this range.
size_t CallSiteEndIdx = 0;
// Whether this is the call-site range containing all the landing pads.
bool IsLPRange = false;
};`
With N basic-block-sections, the call-site table is partitioned into N call-site ranges.
Conceptually, we emit the call-site ranges for sections sequentially in the exception table as if each section has its own exception table. In the example below, two sections result in the two call site ranges (denoted by LSDA1 and LSDA2) placed next to each other. However, their call-sites will refer to records in the shared Action Table. We also emit the header fields (@LPStart and CallSite Table Length) for each call site range in order to place the call site ranges in separate LSDAs. We note that with -basic-block-sections, The CallSiteTableLength will not actually represent the length of the call site table, but rather the reference to the action table. Since the only purpose of this field is to locate the action table, correctness is guaranteed.
Finally, every call site range has one @LPStart pointer so the landing pads of each section must all reside in one section (not necessarily the same section). To make this easier, we decide to place all landing pads of the function in one section (hence the `IsLPRange` field in CallSiteRange).
| @LPStart | ---> Landing pad fragment ( LSDA1 points here)
| CallSite Table Length | ---> Used to find the action table.
| CallSites |
| … |
| … |
| @LPStart | ---> Landing pad fragment ( LSDA2 points here)
| CallSite Table Length |
| CallSites |
| … |
| … |
…
…
| Action Table |
| Types Table |
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D73739
2020-10-01 01:37:00 +08:00
|
|
|
// If the exception section begins with a landing pad, that landing pad will
|
|
|
|
// assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
|
|
|
|
// zero implies "no landing pad." This function inserts a NOP just before the EH
|
|
|
|
// pad label to ensure a nonzero offset. Returns true if padding is not needed.
|
|
|
|
static bool avoidZeroOffsetLandingPad(MachineFunction &MF) {
|
|
|
|
for (auto &MBB : MF) {
|
|
|
|
if (MBB.isBeginSection() && MBB.isEHPad()) {
|
|
|
|
MachineBasicBlock::iterator MI = MBB.begin();
|
|
|
|
while (!MI->isEHLabel())
|
|
|
|
++MI;
|
|
|
|
MCInst Noop;
|
|
|
|
MF.getSubtarget().getInstrInfo()->getNoop(Noop);
|
|
|
|
BuildMI(MBB, MI, DebugLoc(),
|
|
|
|
MF.getSubtarget().getInstrInfo()->get(Noop.getOpcode()));
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2020-08-06 06:34:31 +08:00
|
|
|
bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
|
|
|
|
auto BBSectionsType = MF.getTarget().getBBSectionsType();
|
|
|
|
assert(BBSectionsType != BasicBlockSection::None &&
|
|
|
|
"BB Sections not enabled!");
|
|
|
|
// Renumber blocks before sorting them for basic block sections. This is
|
|
|
|
// useful during sorting, basic blocks in the same section will retain the
|
|
|
|
// default order. This renumbering should also be done for basic block
|
|
|
|
// labels to match the profiles with the correct blocks.
|
|
|
|
MF.RenumberBlocks();
|
|
|
|
|
|
|
|
if (BBSectionsType == BasicBlockSection::Labels) {
|
|
|
|
MF.setBBSectionsType(BBSectionsType);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo;
|
|
|
|
if (BBSectionsType == BasicBlockSection::List &&
|
|
|
|
!getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo,
|
|
|
|
FuncBBClusterInfo))
|
|
|
|
return true;
|
|
|
|
MF.setBBSectionsType(BBSectionsType);
|
|
|
|
assignSections(MF, FuncBBClusterInfo);
|
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// We make sure that the cluster including the entry basic block precedes all
|
|
|
|
// other clusters.
|
|
|
|
auto EntryBBSectionID = MF.front().getSectionID();
|
|
|
|
|
|
|
|
// Helper function for ordering BB sections as follows:
|
|
|
|
// * Entry section (section including the entry block).
|
|
|
|
// * Regular sections (in increasing order of their Number).
|
|
|
|
// ...
|
|
|
|
// * Exception section
|
|
|
|
// * Cold section
|
|
|
|
auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
|
|
|
|
const MBBSectionID &RHS) {
|
|
|
|
// We make sure that the section containing the entry block precedes all the
|
|
|
|
// other sections.
|
|
|
|
if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
|
|
|
|
return LHS == EntryBBSectionID;
|
|
|
|
return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
|
|
|
|
};
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
// We sort all basic blocks to make sure the basic blocks of every cluster are
|
|
|
|
// contiguous and ordered accordingly. Furthermore, clusters are ordered in
|
|
|
|
// increasing order of their section IDs, with the exception and the
|
|
|
|
// cold section placed at the end of the function.
|
2020-08-06 06:34:31 +08:00
|
|
|
auto Comparator = [&](const MachineBasicBlock &X,
|
|
|
|
const MachineBasicBlock &Y) {
|
2020-04-14 03:14:42 +08:00
|
|
|
auto XSectionID = X.getSectionID();
|
|
|
|
auto YSectionID = Y.getSectionID();
|
|
|
|
if (XSectionID != YSectionID)
|
|
|
|
return MBBSectionOrder(XSectionID, YSectionID);
|
|
|
|
// If the two basic block are in the same section, the order is decided by
|
|
|
|
// their position within the section.
|
|
|
|
if (XSectionID.Type == MBBSectionID::SectionType::Default)
|
|
|
|
return FuncBBClusterInfo[X.getNumber()]->PositionInCluster <
|
|
|
|
FuncBBClusterInfo[Y.getNumber()]->PositionInCluster;
|
|
|
|
return X.getNumber() < Y.getNumber();
|
2020-08-06 06:34:31 +08:00
|
|
|
};
|
2020-03-17 06:56:02 +08:00
|
|
|
|
2020-08-06 06:34:31 +08:00
|
|
|
sortBasicBlocksAndUpdateBranches(MF, Comparator);
|
Exception support for basic block sections
This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf
This patch provides exception support for basic block sections by splitting the call-site table into call-site ranges corresponding to different basic block sections. Still all landing pads must reside in the same basic block section (which is guaranteed by the the core basic block section patch D73674 (ExceptionSection) ). Each call-site table will refer to the landing pad fragment by explicitly specifying @LPstart (which is omitted in the normal non-basic-block section case). All these call-site tables will share their action and type tables.
The C++ ABI somehow assumes that no landing pads point directly to LPStart (which works in the normal case since the function begin is never a landing pad), and uses LP.offset = 0 to specify no landing pad. In the case of basic block section where one section contains all the landing pads, the landing pad offset relative to LPStart could actually be zero. Thus, we avoid zero-offset landing pads by inserting a **nop** operation as the first non-CFI instruction in the exception section.
**Background on Exception Handling in C++ ABI**
https://github.com/itanium-cxx-abi/cxx-abi/blob/master/exceptions.pdf
Compiler emits an exception table for every function. When an exception is thrown, the stack unwinding library queries the unwind table (which includes the start and end of each function) to locate the exception table for that function.
The exception table includes a call site table for the function, which is used to guide the exception handling runtime to take the appropriate action upon an exception. Each call site record in this table is structured as follows:
| CallSite | --> Position of the call site (relative to the function entry)
| CallSite length | --> Length of the call site.
| Landing Pad | --> Position of the landing pad (relative to the landing pad fragment’s begin label)
| Action record offset | --> Position of the first action record
The call site records partition a function into different pieces and describe what action must be taken for each callsite. The callsite fields are relative to the start of the function (as captured in the unwind table).
The landing pad entry is a reference into the function and corresponds roughly to the catch block of a try/catch statement. When execution resumes at a landing pad, it receives an exception structure and a selector value corresponding to the type of the exception thrown, and executes similar to a switch-case statement. The landing pad field is relative to the beginning of the procedure fragment which includes all the landing pads (@LPStart). The C++ ABI requires all landing pads to be in the same fragment. Nonetheless, without basic block sections, @LPStart is the same as the function @Start (found in the unwind table) and can be omitted.
The action record offset is an index into the action table which includes information about which exception types are caught.
**C++ Exceptions with Basic Block Sections**
Basic block sections break the contiguity of a function fragment. Therefore, call sites must be specified relative to the beginning of the basic block section. Furthermore, the unwinding library should be able to find the corresponding callsites for each section. To do so, the .cfi_lsda directive for a section must point to the range of call-sites for that section.
This patch introduces a new **CallSiteRange** structure which specifies the range of call-sites which correspond to every section:
`struct CallSiteRange {
// Symbol marking the beginning of the precedure fragment.
MCSymbol *FragmentBeginLabel = nullptr;
// Symbol marking the end of the procedure fragment.
MCSymbol *FragmentEndLabel = nullptr;
// LSDA symbol for this call-site range.
MCSymbol *ExceptionLabel = nullptr;
// Index of the first call-site entry in the call-site table which
// belongs to this range.
size_t CallSiteBeginIdx = 0;
// Index just after the last call-site entry in the call-site table which
// belongs to this range.
size_t CallSiteEndIdx = 0;
// Whether this is the call-site range containing all the landing pads.
bool IsLPRange = false;
};`
With N basic-block-sections, the call-site table is partitioned into N call-site ranges.
Conceptually, we emit the call-site ranges for sections sequentially in the exception table as if each section has its own exception table. In the example below, two sections result in the two call site ranges (denoted by LSDA1 and LSDA2) placed next to each other. However, their call-sites will refer to records in the shared Action Table. We also emit the header fields (@LPStart and CallSite Table Length) for each call site range in order to place the call site ranges in separate LSDAs. We note that with -basic-block-sections, The CallSiteTableLength will not actually represent the length of the call site table, but rather the reference to the action table. Since the only purpose of this field is to locate the action table, correctness is guaranteed.
Finally, every call site range has one @LPStart pointer so the landing pads of each section must all reside in one section (not necessarily the same section). To make this easier, we decide to place all landing pads of the function in one section (hence the `IsLPRange` field in CallSiteRange).
| @LPStart | ---> Landing pad fragment ( LSDA1 points here)
| CallSite Table Length | ---> Used to find the action table.
| CallSites |
| … |
| … |
| @LPStart | ---> Landing pad fragment ( LSDA2 points here)
| CallSite Table Length |
| CallSites |
| … |
| … |
…
…
| Action Table |
| Types Table |
Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D73739
2020-10-01 01:37:00 +08:00
|
|
|
avoidZeroOffsetLandingPad(MF);
|
2020-03-17 06:56:02 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Basic Block Sections can be enabled for a subset of machine basic blocks.
|
|
|
|
// This is done by passing a file containing names of functions for which basic
|
|
|
|
// block sections are desired. Additionally, machine basic block ids of the
|
2020-04-14 03:14:42 +08:00
|
|
|
// functions can also be specified for a finer granularity. Moreover, a cluster
|
|
|
|
// of basic blocks could be assigned to the same section.
|
|
|
|
// A file with basic block sections for all of function main and three blocks
|
|
|
|
// for function foo (of which 1 and 2 are placed in a cluster) looks like this:
|
2020-03-17 06:56:02 +08:00
|
|
|
// ----------------------------
|
|
|
|
// list.txt:
|
|
|
|
// !main
|
|
|
|
// !foo
|
2020-04-14 03:14:42 +08:00
|
|
|
// !!1 2
|
2020-03-17 06:56:02 +08:00
|
|
|
// !!4
|
2020-04-14 03:14:42 +08:00
|
|
|
static Error getBBClusterInfo(const MemoryBuffer *MBuf,
|
|
|
|
ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
|
|
|
|
StringMap<StringRef> &FuncAliasMap) {
|
|
|
|
assert(MBuf);
|
2020-04-14 03:12:34 +08:00
|
|
|
line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#');
|
2020-04-14 02:39:23 +08:00
|
|
|
|
2020-04-14 03:14:42 +08:00
|
|
|
auto invalidProfileError = [&](auto Message) {
|
|
|
|
return make_error<StringError>(
|
|
|
|
Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " +
|
|
|
|
Twine(LineIt.line_number()) + ": " + Message),
|
|
|
|
inconvertibleErrorCode());
|
|
|
|
};
|
|
|
|
|
|
|
|
auto FI = ProgramBBClusterInfo.end();
|
|
|
|
|
|
|
|
// Current cluster ID corresponding to this function.
|
|
|
|
unsigned CurrentCluster = 0;
|
|
|
|
// Current position in the current cluster.
|
|
|
|
unsigned CurrentPosition = 0;
|
|
|
|
|
|
|
|
// Temporary set to ensure every basic block ID appears once in the clusters
|
|
|
|
// of a function.
|
|
|
|
SmallSet<unsigned, 4> FuncBBIDs;
|
2020-03-17 06:56:02 +08:00
|
|
|
|
|
|
|
for (; !LineIt.is_at_eof(); ++LineIt) {
|
2020-04-14 03:14:42 +08:00
|
|
|
StringRef S(*LineIt);
|
|
|
|
if (S[0] == '@')
|
2020-03-17 06:56:02 +08:00
|
|
|
continue;
|
|
|
|
// Check for the leading "!"
|
2020-04-14 03:14:42 +08:00
|
|
|
if (!S.consume_front("!") || S.empty())
|
2020-03-17 06:56:02 +08:00
|
|
|
break;
|
2020-04-14 03:14:42 +08:00
|
|
|
// Check for second "!" which indicates a cluster of basic blocks.
|
|
|
|
if (S.consume_front("!")) {
|
|
|
|
if (FI == ProgramBBClusterInfo.end())
|
|
|
|
return invalidProfileError(
|
|
|
|
"Cluster list does not follow a function name specifier.");
|
|
|
|
SmallVector<StringRef, 4> BBIndexes;
|
|
|
|
S.split(BBIndexes, ' ');
|
|
|
|
// Reset current cluster position.
|
|
|
|
CurrentPosition = 0;
|
|
|
|
for (auto BBIndexStr : BBIndexes) {
|
|
|
|
unsigned long long BBIndex;
|
|
|
|
if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex))
|
|
|
|
return invalidProfileError(Twine("Unsigned integer expected: '") +
|
|
|
|
BBIndexStr + "'.");
|
|
|
|
if (!FuncBBIDs.insert(BBIndex).second)
|
|
|
|
return invalidProfileError(Twine("Duplicate basic block id found '") +
|
|
|
|
BBIndexStr + "'.");
|
|
|
|
if (!BBIndex && CurrentPosition)
|
|
|
|
return invalidProfileError("Entry BB (0) does not begin a cluster.");
|
|
|
|
|
|
|
|
FI->second.emplace_back(BBClusterInfo{
|
|
|
|
((unsigned)BBIndex), CurrentCluster, CurrentPosition++});
|
|
|
|
}
|
|
|
|
CurrentCluster++;
|
|
|
|
} else { // This is a function name specifier.
|
|
|
|
// Function aliases are separated using '/'. We use the first function
|
|
|
|
// name for the cluster info mapping and delegate all other aliases to
|
|
|
|
// this one.
|
|
|
|
SmallVector<StringRef, 4> Aliases;
|
|
|
|
S.split(Aliases, '/');
|
|
|
|
for (size_t i = 1; i < Aliases.size(); ++i)
|
|
|
|
FuncAliasMap.try_emplace(Aliases[i], Aliases.front());
|
|
|
|
|
|
|
|
// Prepare for parsing clusters of this function name.
|
|
|
|
// Start a new cluster map for this function name.
|
|
|
|
FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first;
|
|
|
|
CurrentCluster = 0;
|
|
|
|
FuncBBIDs.clear();
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
|
|
|
}
|
2020-04-14 03:14:42 +08:00
|
|
|
return Error::success();
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
|
|
|
|
2020-08-06 08:11:48 +08:00
|
|
|
bool BasicBlockSections::doInitialization(Module &M) {
|
2020-04-14 03:14:42 +08:00
|
|
|
if (!MBuf)
|
|
|
|
return false;
|
|
|
|
if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap))
|
|
|
|
report_fatal_error(std::move(Err));
|
|
|
|
return false;
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
|
|
|
|
2020-08-06 08:11:48 +08:00
|
|
|
void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
|
2020-03-17 06:56:02 +08:00
|
|
|
AU.setPreservesAll();
|
2020-07-01 10:10:01 +08:00
|
|
|
MachineFunctionPass::getAnalysisUsage(AU);
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
MachineFunctionPass *
|
2020-08-06 08:11:48 +08:00
|
|
|
llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) {
|
|
|
|
return new BasicBlockSections(Buf);
|
2020-03-17 06:56:02 +08:00
|
|
|
}
|