LLVM 18.0.0git
Go to the documentation of this file.
1//===-- BasicBlockSections.cpp ---=========--------------------------------===//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
9// BasicBlockSections implementation.
11// The purpose of this pass is to assign sections to basic blocks when
12// -fbasic-block-sections= option is used. Further, with profile information
13// only the subset of basic blocks with profiles are placed in separate sections
14// and the rest are grouped in a cold section. The exception handling blocks are
15// treated specially to ensure they are all in one seciton.
17// Basic Block Sections
18// ====================
20// With option, -fbasic-block-sections=list, every function may be split into
21// clusters of basic blocks. Every cluster will be emitted into a separate
22// section with its basic blocks sequenced in the given order. To get the
23// optimized performance, the clusters must form an optimal BB layout for the
24// function. We insert a symbol at the beginning of every cluster's section to
25// allow the linker to reorder the sections in any arbitrary sequence. A global
26// order of these sections would encapsulate the function layout.
27// For example, consider the following clusters for a function foo (consisting
28// of 6 basic blocks 0, 1, ..., 5).
30// 0 2
31// 1 3 5
33// * Basic blocks 0 and 2 are placed in one section with symbol `foo`
34// referencing the beginning of this section.
35// * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
36// `foo.__part.1` will reference the beginning of this section.
37// * Basic block 4 (note that it is not referenced in the list) is placed in
38// one section, and a new symbol `foo.cold` will point to it.
40// There are a couple of challenges to be addressed:
42// 1. The last basic block of every cluster should not have any implicit
43// fallthrough to its next basic block, as it can be reordered by the linker.
44// The compiler should make these fallthroughs explicit by adding
45// unconditional jumps..
47// 2. All inter-cluster branch targets would now need to be resolved by the
48// linker as they cannot be calculated during compile time. This is done
49// using static relocations. Further, the compiler tries to use short branch
50// instructions on some ISAs for small branch offsets. This is not possible
51// for inter-cluster branches as the offset is not determined at compile
52// time, and therefore, long branch instructions have to be used for those.
54// 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
55// needs special handling with basic block sections. DebugInfo needs to be
56// emitted with more relocations as basic block sections can break a
57// function into potentially several disjoint pieces, and CFI needs to be
58// emitted per cluster. This also bloats the object file and binary sizes.
60// Basic Block Labels
61// ==================
63// With -fbasic-block-sections=labels, we encode the offsets of BB addresses of
64// every function into the .llvm_bb_addr_map section. Along with the function
65// symbols, this allows for mapping of virtual addresses in PMU profiles back to
66// the corresponding basic blocks. This logic is implemented in AsmPrinter. This
67// pass only assigns the BBSectionType of every function to ``labels``.
72#include "llvm/ADT/StringRef.h"
77#include "llvm/CodeGen/Passes.h"
81#include <optional>
83using namespace llvm;
85// Placing the cold clusters in a separate section mitigates against poor
86// profiles and allows optimizations such as hugepage mapping to be applied at a
87// section granularity. Defaults to ".text.split." which is recognized by lld
88// via the `-z keep-text-section-prefix` flag.
90 "bbsections-cold-text-prefix",
91 cl::desc("The text prefix to use for cold basic block clusters"),
92 cl::init(".text.split."), cl::Hidden);
95 "bbsections-detect-source-drift",
96 cl::desc("This checks if there is a fdo instr. profile hash "
97 "mismatch for this function"),
98 cl::init(true), cl::Hidden);
100namespace {
102class BasicBlockSections : public MachineFunctionPass {
104 static char ID;
106 BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
108 BasicBlockSections() : MachineFunctionPass(ID) {
110 }
112 StringRef getPassName() const override {
113 return "Basic Block Sections Analysis";
114 }
116 void getAnalysisUsage(AnalysisUsage &AU) const override;
118 /// Identify basic blocks that need separate sections and prepare to emit them
119 /// accordingly.
120 bool runOnMachineFunction(MachineFunction &MF) override;
123} // end anonymous namespace
125char BasicBlockSections::ID = 0;
127 BasicBlockSections, "bbsections-prepare",
128 "Prepares for basic block sections, by splitting functions "
129 "into clusters of basic blocks.",
130 false, false)
132INITIALIZE_PASS_END(BasicBlockSections, "bbsections-prepare",
133 "Prepares for basic block sections, by splitting functions "
134 "into clusters of basic blocks.",
137// This function updates and optimizes the branching instructions of every basic
138// block in a given function to account for changes in the layout.
139static void
141 const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {
142 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
144 for (auto &MBB : MF) {
145 auto NextMBBI = std::next(MBB.getIterator());
146 auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
147 // If this block had a fallthrough before we need an explicit unconditional
148 // branch to that block if either
149 // 1- the block ends a section, which means its next block may be
150 // reorderd by the linker, or
151 // 2- the fallthrough block is not adjacent to the block in the new
152 // order.
153 if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
154 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
156 // We do not optimize branches for machine basic blocks ending sections, as
157 // their adjacent block might be reordered by the linker.
158 if (MBB.isEndSection())
159 continue;
161 // It might be possible to optimize branches by flipping the branch
162 // condition.
163 Cond.clear();
164 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
165 if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
166 continue;
167 MBB.updateTerminator(FTMBB);
168 }
171// This function sorts basic blocks according to the cluster's information.
172// All explicitly specified clusters of basic blocks will be ordered
173// accordingly. All non-specified BBs go into a separate "Cold" section.
174// Additionally, if exception handling landing pads end up in more than one
175// clusters, they are moved into a single "Exception" section. Eventually,
176// clusters are ordered in increasing order of their IDs, with the "Exception"
177// and "Cold" succeeding all other clusters.
178// FuncClusterInfo represents the cluster information for basic blocks. It
179// maps from BBID of basic blocks to their cluster information. If this is
180// empty, it means unique sections for all basic blocks in the function.
181static void
183 const DenseMap<UniqueBBID, BBClusterInfo> &FuncClusterInfo) {
184 assert(MF.hasBBSections() && "BB Sections is not set for function.");
185 // This variable stores the section ID of the cluster containing eh_pads (if
186 // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
187 // set it equal to ExceptionSectionID.
188 std::optional<MBBSectionID> EHPadsSectionID;
190 for (auto &MBB : MF) {
191 // With the 'all' option, every basic block is placed in a unique section.
192 // With the 'list' option, every basic block is placed in a section
193 // associated with its cluster, unless we want individual unique sections
194 // for every basic block in this function (if FuncClusterInfo is empty).
196 FuncClusterInfo.empty()) {
197 // If unique sections are desired for all basic blocks of the function, we
198 // set every basic block's section ID equal to its original position in
199 // the layout (which is equal to its number). This ensures that basic
200 // blocks are ordered canonically.
202 } else {
203 auto I = FuncClusterInfo.find(*MBB.getBBID());
204 if (I != FuncClusterInfo.end()) {
205 MBB.setSectionID(I->second.ClusterID);
206 } else {
207 // BB goes into the special cold section if it is not specified in the
208 // cluster info map.
210 }
211 }
213 if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
214 EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
215 // If we already have one cluster containing eh_pads, this must be updated
216 // to ExceptionSectionID. Otherwise, we set it equal to the current
217 // section ID.
218 EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
219 : MBB.getSectionID();
220 }
221 }
223 // If EHPads are in more than one section, this places all of them in the
224 // special exception section.
225 if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
226 for (auto &MBB : MF)
227 if (MBB.isEHPad())
228 MBB.setSectionID(*EHPadsSectionID);
233 [[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();
234 SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());
235 for (auto &MBB : MF)
236 PreLayoutFallThroughs[MBB.getNumber()] =
237 MBB.getFallThrough(/*JumpToFallThrough=*/false);
239 MF.sort(MBBCmp);
240 assert(&MF.front() == EntryBlock &&
241 "Entry block should not be displaced by basic block sections");
243 // Set IsBeginSection and IsEndSection according to the assigned section IDs.
246 // After reordering basic blocks, we must update basic block branches to
247 // insert explicit fallthrough branches when required and optimize branches
248 // when possible.
249 updateBranches(MF, PreLayoutFallThroughs);
252// If the exception section begins with a landing pad, that landing pad will
253// assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
254// zero implies "no landing pad." This function inserts a NOP just before the EH
255// pad label to ensure a nonzero offset.
257 for (auto &MBB : MF) {
258 if (MBB.isBeginSection() && MBB.isEHPad()) {
260 while (!MI->isEHLabel())
261 ++MI;
263 }
264 }
269 return false;
271 const char MetadataName[] = "instr_prof_hash_mismatch";
272 auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
273 if (Existing) {
274 MDTuple *Tuple = cast<MDTuple>(Existing);
275 for (const auto &N : Tuple->operands())
276 if (N.equalsStr(MetadataName))
277 return true;
278 }
280 return false;
283bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
284 auto BBSectionsType = MF.getTarget().getBBSectionsType();
285 assert(BBSectionsType != BasicBlockSection::None &&
286 "BB Sections not enabled!");
288 // Check for source drift. If the source has changed since the profiles
289 // were obtained, optimizing basic blocks might be sub-optimal.
290 // This only applies to BasicBlockSection::List as it creates
291 // clusters of basic blocks using basic block ids. Source drift can
292 // invalidate these groupings leading to sub-optimal code generation with
293 // regards to performance.
294 if (BBSectionsType == BasicBlockSection::List &&
296 return false;
297 // Renumber blocks before sorting them. This is useful for accessing the
298 // original layout positions and finding the original fallthroughs.
299 MF.RenumberBlocks();
301 if (BBSectionsType == BasicBlockSection::Labels) {
302 MF.setBBSectionsType(BBSectionsType);
303 return false;
304 }
307 if (BBSectionsType == BasicBlockSection::List) {
308 auto [HasProfile, ClusterInfo] =
309 getAnalysis<BasicBlockSectionsProfileReader>()
310 .getClusterInfoForFunction(MF.getName());
311 if (!HasProfile)
312 return false;
313 for (auto &BBClusterInfo : ClusterInfo) {
315 }
316 }
318 MF.setBBSectionsType(BBSectionsType);
319 assignSections(MF, FuncClusterInfo);
321 // We make sure that the cluster including the entry basic block precedes all
322 // other clusters.
323 auto EntryBBSectionID = MF.front().getSectionID();
325 // Helper function for ordering BB sections as follows:
326 // * Entry section (section including the entry block).
327 // * Regular sections (in increasing order of their Number).
328 // ...
329 // * Exception section
330 // * Cold section
331 auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
332 const MBBSectionID &RHS) {
333 // We make sure that the section containing the entry block precedes all the
334 // other sections.
335 if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
336 return LHS == EntryBBSectionID;
337 return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
338 };
340 // We sort all basic blocks to make sure the basic blocks of every cluster are
341 // contiguous and ordered accordingly. Furthermore, clusters are ordered in
342 // increasing order of their section IDs, with the exception and the
343 // cold section placed at the end of the function.
344 auto Comparator = [&](const MachineBasicBlock &X,
345 const MachineBasicBlock &Y) {
346 auto XSectionID = X.getSectionID();
347 auto YSectionID = Y.getSectionID();
348 if (XSectionID != YSectionID)
349 return MBBSectionOrder(XSectionID, YSectionID);
350 // If the two basic block are in the same section, the order is decided by
351 // their position within the section.
352 if (XSectionID.Type == MBBSectionID::SectionType::Default)
353 return FuncClusterInfo.lookup(*X.getBBID()).PositionInCluster <
354 FuncClusterInfo.lookup(*Y.getBBID()).PositionInCluster;
355 return X.getNumber() < Y.getNumber();
356 };
358 sortBasicBlocksAndUpdateBranches(MF, Comparator);
360 return true;
363void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
364 AU.setPreservesAll();
370 return new BasicBlockSections();
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
aarch64 promote const
MachineBasicBlock & MBB
Lower uses of LDS variables from non kernel functions
bbsections Prepares for basic block by splitting functions into clusters of basic blocks
static void assignSections(MachineFunction &MF, const DenseMap< UniqueBBID, BBClusterInfo > &FuncClusterInfo)
static cl::opt< bool > BBSectionsDetectSourceDrift("bbsections-detect-source-drift", cl::desc("This checks if there is a fdo instr. profile hash " "mismatch for this function"), cl::init(true), cl::Hidden)
bbsections Prepares for basic block by splitting functions into clusters of basic static false void updateBranches(MachineFunction &MF, const SmallVector< MachineBasicBlock * > &PreLayoutFallThroughs)
bbsections prepare
bbsections Prepares for basic block sections
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
unify loop Fixup each natural loop to have a single exit block
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:235
bool empty() const
Definition: DenseMap.h:98
iterator end()
Definition: DenseMap.h:84
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:565
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1389
Tuple of metadata.
Definition: Metadata.h:1433
bool isEHPad() const
Returns true if the block is a landing pad.
MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
std::optional< UniqueBBID > getBBID() const
void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
bool isBeginSection() const
Returns true if this block begins any section.
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
bool isEndSection() const
Returns true if this block ends any section.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void setBBSectionsType(BasicBlockSection V)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
void sort(Comp comp)
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineBasicBlock & front() const
void assignBeginEndSections()
Assign IsBeginSection IsEndSection fields for basic blocks in this function.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetInstrInfo - Interface to description of machine instruction set.
virtual void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
Insert a noop into the instruction stream at the specified point.
llvm::BasicBlockSection getBBSectionsType() const
If basic blocks should be emitted into their own section, corresponding to -fbasic-block-sections.
virtual const TargetInstrInfo * getInstrInfo() const
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:109
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineFunctionPass * createBasicBlockSectionsPass()
createBasicBlockSections Pass - This pass assigns sections to machine basic blocks and is enabled wit...
bool hasInstrProfHashMismatch(MachineFunction &MF)
This checks if the source of this function has drifted since this binary was profiled previously.
void initializeBasicBlockSectionsPass(PassRegistry &)
void avoidZeroOffsetLandingPad(MachineFunction &MF)
cl::opt< std::string > BBSectionsColdTextPrefix
void sortBasicBlocksAndUpdateBranches(MachineFunction &MF, MachineBasicBlockComparator MBBCmp)
#define N
static const MBBSectionID ExceptionSectionID
static const MBBSectionID ColdSectionID