xref: /llvm-project/llvm/lib/CodeGen/BasicBlockSections.cpp (revision 7b7747dc1d3da1a829503ea9505b4cecce4f5bda)
18d943a92SSnehasish Kumar //===-- BasicBlockSections.cpp ---=========--------------------------------===//
28d943a92SSnehasish Kumar //
38d943a92SSnehasish Kumar // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
48d943a92SSnehasish Kumar // See https://llvm.org/LICENSE.txt for license information.
58d943a92SSnehasish Kumar // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68d943a92SSnehasish Kumar //
78d943a92SSnehasish Kumar //===----------------------------------------------------------------------===//
88d943a92SSnehasish Kumar //
98d943a92SSnehasish Kumar // BasicBlockSections implementation.
108d943a92SSnehasish Kumar //
118d943a92SSnehasish Kumar // The purpose of this pass is to assign sections to basic blocks when
128d943a92SSnehasish Kumar // -fbasic-block-sections= option is used. Further, with profile information
138d943a92SSnehasish Kumar // only the subset of basic blocks with profiles are placed in separate sections
148d943a92SSnehasish Kumar // and the rest are grouped in a cold section. The exception handling blocks are
158d943a92SSnehasish Kumar // treated specially to ensure they are all in one seciton.
168d943a92SSnehasish Kumar //
178d943a92SSnehasish Kumar // Basic Block Sections
188d943a92SSnehasish Kumar // ====================
198d943a92SSnehasish Kumar //
208d943a92SSnehasish Kumar // With option, -fbasic-block-sections=list, every function may be split into
218d943a92SSnehasish Kumar // clusters of basic blocks. Every cluster will be emitted into a separate
228d943a92SSnehasish Kumar // section with its basic blocks sequenced in the given order. To get the
238d943a92SSnehasish Kumar // optimized performance, the clusters must form an optimal BB layout for the
242256b359SRahman Lavaee // function. We insert a symbol at the beginning of every cluster's section to
252256b359SRahman Lavaee // allow the linker to reorder the sections in any arbitrary sequence. A global
262256b359SRahman Lavaee // order of these sections would encapsulate the function layout.
272256b359SRahman Lavaee // For example, consider the following clusters for a function foo (consisting
282256b359SRahman Lavaee // of 6 basic blocks 0, 1, ..., 5).
292256b359SRahman Lavaee //
302256b359SRahman Lavaee // 0 2
312256b359SRahman Lavaee // 1 3 5
322256b359SRahman Lavaee //
332256b359SRahman Lavaee // * Basic blocks 0 and 2 are placed in one section with symbol `foo`
342256b359SRahman Lavaee //   referencing the beginning of this section.
352256b359SRahman Lavaee // * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
362256b359SRahman Lavaee //   `foo.__part.1` will reference the beginning of this section.
372256b359SRahman Lavaee // * Basic block 4 (note that it is not referenced in the list) is placed in
382256b359SRahman Lavaee //   one section, and a new symbol `foo.cold` will point to it.
398d943a92SSnehasish Kumar //
408d943a92SSnehasish Kumar // There are a couple of challenges to be addressed:
418d943a92SSnehasish Kumar //
428d943a92SSnehasish Kumar // 1. The last basic block of every cluster should not have any implicit
438d943a92SSnehasish Kumar //    fallthrough to its next basic block, as it can be reordered by the linker.
448d943a92SSnehasish Kumar //    The compiler should make these fallthroughs explicit by adding
458d943a92SSnehasish Kumar //    unconditional jumps..
468d943a92SSnehasish Kumar //
478d943a92SSnehasish Kumar // 2. All inter-cluster branch targets would now need to be resolved by the
488d943a92SSnehasish Kumar //    linker as they cannot be calculated during compile time. This is done
498d943a92SSnehasish Kumar //    using static relocations. Further, the compiler tries to use short branch
508d943a92SSnehasish Kumar //    instructions on some ISAs for small branch offsets. This is not possible
518d943a92SSnehasish Kumar //    for inter-cluster branches as the offset is not determined at compile
528d943a92SSnehasish Kumar //    time, and therefore, long branch instructions have to be used for those.
538d943a92SSnehasish Kumar //
548d943a92SSnehasish Kumar // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
558d943a92SSnehasish Kumar //    needs special handling with basic block sections. DebugInfo needs to be
568d943a92SSnehasish Kumar //    emitted with more relocations as basic block sections can break a
578d943a92SSnehasish Kumar //    function into potentially several disjoint pieces, and CFI needs to be
588d943a92SSnehasish Kumar //    emitted per cluster. This also bloats the object file and binary sizes.
598d943a92SSnehasish Kumar //
60acec6419SRahman Lavaee // Basic Block Address Map
618d943a92SSnehasish Kumar // ==================
628d943a92SSnehasish Kumar //
63acec6419SRahman Lavaee // With -fbasic-block-address-map, we emit the offsets of BB addresses of
642b0c5d76SRahman Lavaee // every function into the .llvm_bb_addr_map section. Along with the function
652b0c5d76SRahman Lavaee // symbols, this allows for mapping of virtual addresses in PMU profiles back to
662b0c5d76SRahman Lavaee // the corresponding basic blocks. This logic is implemented in AsmPrinter. This
677841e21cSRahman Lavaee // pass only assigns the BBSectionType of every function to ``labels``.
688d943a92SSnehasish Kumar //
698d943a92SSnehasish Kumar //===----------------------------------------------------------------------===//
708d943a92SSnehasish Kumar 
718d943a92SSnehasish Kumar #include "llvm/ADT/SmallVector.h"
728d943a92SSnehasish Kumar #include "llvm/ADT/StringRef.h"
7396b6ee1bSRahman Lavaee #include "llvm/CodeGen/BasicBlockSectionUtils.h"
743d6841b2SRahman Lavaee #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
75*d871b2e0SAlexis Engelke #include "llvm/CodeGen/MachineDominators.h"
768d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunction.h"
778d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunctionPass.h"
78*d871b2e0SAlexis Engelke #include "llvm/CodeGen/MachinePostDominators.h"
798d943a92SSnehasish Kumar #include "llvm/CodeGen/Passes.h"
808d943a92SSnehasish Kumar #include "llvm/CodeGen/TargetInstrInfo.h"
818d943a92SSnehasish Kumar #include "llvm/InitializePasses.h"
828d943a92SSnehasish Kumar #include "llvm/Target/TargetMachine.h"
8307ce3b8aSKazu Hirata #include <optional>
848d943a92SSnehasish Kumar 
858d943a92SSnehasish Kumar using namespace llvm;
868d943a92SSnehasish Kumar 
87d2696decSSnehasish Kumar // Placing the cold clusters in a separate section mitigates against poor
88d2696decSSnehasish Kumar // profiles and allows optimizations such as hugepage mapping to be applied at a
8977638a53SSnehasish Kumar // section granularity. Defaults to ".text.split." which is recognized by lld
9077638a53SSnehasish Kumar // via the `-z keep-text-section-prefix` flag.
91d2696decSSnehasish Kumar cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
92d2696decSSnehasish Kumar     "bbsections-cold-text-prefix",
93d2696decSSnehasish Kumar     cl::desc("The text prefix to use for cold basic block clusters"),
9477638a53SSnehasish Kumar     cl::init(".text.split."), cl::Hidden);
95d2696decSSnehasish Kumar 
961e692113SFangrui Song static cl::opt<bool> BBSectionsDetectSourceDrift(
97c32f3998SSriraman Tallam     "bbsections-detect-source-drift",
98c32f3998SSriraman Tallam     cl::desc("This checks if there is a fdo instr. profile hash "
99c32f3998SSriraman Tallam              "mismatch for this function"),
100c32f3998SSriraman Tallam     cl::init(true), cl::Hidden);
101c32f3998SSriraman Tallam 
1028d943a92SSnehasish Kumar namespace {
1038d943a92SSnehasish Kumar 
1048d943a92SSnehasish Kumar class BasicBlockSections : public MachineFunctionPass {
1058d943a92SSnehasish Kumar public:
1068d943a92SSnehasish Kumar   static char ID;
1078d943a92SSnehasish Kumar 
108f1ec0d12SNick Anderson   BasicBlockSectionsProfileReaderWrapperPass *BBSectionsProfileReader = nullptr;
1098d943a92SSnehasish Kumar 
1108d943a92SSnehasish Kumar   BasicBlockSections() : MachineFunctionPass(ID) {
1118d943a92SSnehasish Kumar     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
1128d943a92SSnehasish Kumar   }
1138d943a92SSnehasish Kumar 
1148d943a92SSnehasish Kumar   StringRef getPassName() const override {
1158d943a92SSnehasish Kumar     return "Basic Block Sections Analysis";
1168d943a92SSnehasish Kumar   }
1178d943a92SSnehasish Kumar 
1188d943a92SSnehasish Kumar   void getAnalysisUsage(AnalysisUsage &AU) const override;
1198d943a92SSnehasish Kumar 
1208d943a92SSnehasish Kumar   /// Identify basic blocks that need separate sections and prepare to emit them
1218d943a92SSnehasish Kumar   /// accordingly.
1228d943a92SSnehasish Kumar   bool runOnMachineFunction(MachineFunction &MF) override;
123acec6419SRahman Lavaee 
124acec6419SRahman Lavaee private:
125acec6419SRahman Lavaee   bool handleBBSections(MachineFunction &MF);
126acec6419SRahman Lavaee   bool handleBBAddrMap(MachineFunction &MF);
1278d943a92SSnehasish Kumar };
1288d943a92SSnehasish Kumar 
1298d943a92SSnehasish Kumar } // end anonymous namespace
1308d943a92SSnehasish Kumar 
1318d943a92SSnehasish Kumar char BasicBlockSections::ID = 0;
132c13b046dSRahman Lavaee INITIALIZE_PASS_BEGIN(
133c13b046dSRahman Lavaee     BasicBlockSections, "bbsections-prepare",
134c13b046dSRahman Lavaee     "Prepares for basic block sections, by splitting functions "
135c13b046dSRahman Lavaee     "into clusters of basic blocks.",
136c13b046dSRahman Lavaee     false, false)
137f1ec0d12SNick Anderson INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
138c13b046dSRahman Lavaee INITIALIZE_PASS_END(BasicBlockSections, "bbsections-prepare",
1398d943a92SSnehasish Kumar                     "Prepares for basic block sections, by splitting functions "
1408d943a92SSnehasish Kumar                     "into clusters of basic blocks.",
1418d943a92SSnehasish Kumar                     false, false)
1428d943a92SSnehasish Kumar 
1438d943a92SSnehasish Kumar // This function updates and optimizes the branching instructions of every basic
1448d943a92SSnehasish Kumar // block in a given function to account for changes in the layout.
1453d6841b2SRahman Lavaee static void
1463d6841b2SRahman Lavaee updateBranches(MachineFunction &MF,
1473d6841b2SRahman Lavaee                const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {
1488d943a92SSnehasish Kumar   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1498d943a92SSnehasish Kumar   SmallVector<MachineOperand, 4> Cond;
1508d943a92SSnehasish Kumar   for (auto &MBB : MF) {
1518d943a92SSnehasish Kumar     auto NextMBBI = std::next(MBB.getIterator());
1528d943a92SSnehasish Kumar     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
1538d943a92SSnehasish Kumar     // If this block had a fallthrough before we need an explicit unconditional
154d0ec03a3SRahman Lavaee     // branch to that block if either
1558d943a92SSnehasish Kumar     //     1- the block ends a section, which means its next block may be
1568d943a92SSnehasish Kumar     //        reorderd by the linker, or
1578d943a92SSnehasish Kumar     //     2- the fallthrough block is not adjacent to the block in the new
1588d943a92SSnehasish Kumar     //        order.
159d0ec03a3SRahman Lavaee     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
1608d943a92SSnehasish Kumar       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
1618d943a92SSnehasish Kumar 
1628d943a92SSnehasish Kumar     // We do not optimize branches for machine basic blocks ending sections, as
1638d943a92SSnehasish Kumar     // their adjacent block might be reordered by the linker.
1648d943a92SSnehasish Kumar     if (MBB.isEndSection())
1658d943a92SSnehasish Kumar       continue;
1668d943a92SSnehasish Kumar 
1678d943a92SSnehasish Kumar     // It might be possible to optimize branches by flipping the branch
1688d943a92SSnehasish Kumar     // condition.
1698d943a92SSnehasish Kumar     Cond.clear();
1708d943a92SSnehasish Kumar     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
1718d943a92SSnehasish Kumar     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
1728d943a92SSnehasish Kumar       continue;
1738d943a92SSnehasish Kumar     MBB.updateTerminator(FTMBB);
1748d943a92SSnehasish Kumar   }
1758d943a92SSnehasish Kumar }
1768d943a92SSnehasish Kumar 
1778d943a92SSnehasish Kumar // This function sorts basic blocks according to the cluster's information.
1788d943a92SSnehasish Kumar // All explicitly specified clusters of basic blocks will be ordered
1798d943a92SSnehasish Kumar // accordingly. All non-specified BBs go into a separate "Cold" section.
1808d943a92SSnehasish Kumar // Additionally, if exception handling landing pads end up in more than one
1818d943a92SSnehasish Kumar // clusters, they are moved into a single "Exception" section. Eventually,
1828d943a92SSnehasish Kumar // clusters are ordered in increasing order of their IDs, with the "Exception"
1838d943a92SSnehasish Kumar // and "Cold" succeeding all other clusters.
184f70e39ecSRahman Lavaee // FuncClusterInfo represents the cluster information for basic blocks. It
1853d6841b2SRahman Lavaee // maps from BBID of basic blocks to their cluster information. If this is
1863d6841b2SRahman Lavaee // empty, it means unique sections for all basic blocks in the function.
187f70e39ecSRahman Lavaee static void
188f70e39ecSRahman Lavaee assignSections(MachineFunction &MF,
189f70e39ecSRahman Lavaee                const DenseMap<UniqueBBID, BBClusterInfo> &FuncClusterInfo) {
1908d943a92SSnehasish Kumar   assert(MF.hasBBSections() && "BB Sections is not set for function.");
1918d943a92SSnehasish Kumar   // This variable stores the section ID of the cluster containing eh_pads (if
1928d943a92SSnehasish Kumar   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
1938d943a92SSnehasish Kumar   // set it equal to ExceptionSectionID.
19407ce3b8aSKazu Hirata   std::optional<MBBSectionID> EHPadsSectionID;
1958d943a92SSnehasish Kumar 
1968d943a92SSnehasish Kumar   for (auto &MBB : MF) {
1978d943a92SSnehasish Kumar     // With the 'all' option, every basic block is placed in a unique section.
1988d943a92SSnehasish Kumar     // With the 'list' option, every basic block is placed in a section
1998d943a92SSnehasish Kumar     // associated with its cluster, unless we want individual unique sections
200f70e39ecSRahman Lavaee     // for every basic block in this function (if FuncClusterInfo is empty).
2018d943a92SSnehasish Kumar     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
202f70e39ecSRahman Lavaee         FuncClusterInfo.empty()) {
2038d943a92SSnehasish Kumar       // If unique sections are desired for all basic blocks of the function, we
2043d6841b2SRahman Lavaee       // set every basic block's section ID equal to its original position in
2053d6841b2SRahman Lavaee       // the layout (which is equal to its number). This ensures that basic
2063d6841b2SRahman Lavaee       // blocks are ordered canonically.
2073d6841b2SRahman Lavaee       MBB.setSectionID(MBB.getNumber());
2083d6841b2SRahman Lavaee     } else {
209f70e39ecSRahman Lavaee       auto I = FuncClusterInfo.find(*MBB.getBBID());
210f70e39ecSRahman Lavaee       if (I != FuncClusterInfo.end()) {
2113d6841b2SRahman Lavaee         MBB.setSectionID(I->second.ClusterID);
2123d6841b2SRahman Lavaee       } else {
213ea06384bSDaniel Hoekwater         const TargetInstrInfo &TII =
214ea06384bSDaniel Hoekwater             *MBB.getParent()->getSubtarget().getInstrInfo();
215ea06384bSDaniel Hoekwater 
216ea06384bSDaniel Hoekwater         if (TII.isMBBSafeToSplitToCold(MBB)) {
2178d943a92SSnehasish Kumar           // BB goes into the special cold section if it is not specified in the
2188d943a92SSnehasish Kumar           // cluster info map.
2198d943a92SSnehasish Kumar           MBB.setSectionID(MBBSectionID::ColdSectionID);
2208d943a92SSnehasish Kumar         }
2213d6841b2SRahman Lavaee       }
222ea06384bSDaniel Hoekwater     }
2238d943a92SSnehasish Kumar 
2248d943a92SSnehasish Kumar     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
2258d943a92SSnehasish Kumar         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
2268d943a92SSnehasish Kumar       // If we already have one cluster containing eh_pads, this must be updated
2278d943a92SSnehasish Kumar       // to ExceptionSectionID. Otherwise, we set it equal to the current
2288d943a92SSnehasish Kumar       // section ID.
229d08f34b5SKazu Hirata       EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
2308d943a92SSnehasish Kumar                                         : MBB.getSectionID();
2318d943a92SSnehasish Kumar     }
2328d943a92SSnehasish Kumar   }
2338d943a92SSnehasish Kumar 
2348d943a92SSnehasish Kumar   // If EHPads are in more than one section, this places all of them in the
2358d943a92SSnehasish Kumar   // special exception section.
2368d943a92SSnehasish Kumar   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
2378d943a92SSnehasish Kumar     for (auto &MBB : MF)
2388d943a92SSnehasish Kumar       if (MBB.isEHPad())
2397a47ee51SKazu Hirata         MBB.setSectionID(*EHPadsSectionID);
24094faadacSSnehasish Kumar }
2418d943a92SSnehasish Kumar 
24294faadacSSnehasish Kumar void llvm::sortBasicBlocksAndUpdateBranches(
24394faadacSSnehasish Kumar     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
2443d6841b2SRahman Lavaee   [[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();
2453d6841b2SRahman Lavaee   SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());
2468d943a92SSnehasish Kumar   for (auto &MBB : MF)
247c9f32884SDaniel Hoekwater     PreLayoutFallThroughs[MBB.getNumber()] =
248c9f32884SDaniel Hoekwater         MBB.getFallThrough(/*JumpToFallThrough=*/false);
2498d943a92SSnehasish Kumar 
25094faadacSSnehasish Kumar   MF.sort(MBBCmp);
2513d6841b2SRahman Lavaee   assert(&MF.front() == EntryBlock &&
2523d6841b2SRahman Lavaee          "Entry block should not be displaced by basic block sections");
2538d943a92SSnehasish Kumar 
2548d943a92SSnehasish Kumar   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
2558d943a92SSnehasish Kumar   MF.assignBeginEndSections();
2568d943a92SSnehasish Kumar 
2578d943a92SSnehasish Kumar   // After reordering basic blocks, we must update basic block branches to
2588d943a92SSnehasish Kumar   // insert explicit fallthrough branches when required and optimize branches
2598d943a92SSnehasish Kumar   // when possible.
2608d943a92SSnehasish Kumar   updateBranches(MF, PreLayoutFallThroughs);
2618d943a92SSnehasish Kumar }
2628d943a92SSnehasish Kumar 
2638955950cSRahman Lavaee // If the exception section begins with a landing pad, that landing pad will
2648955950cSRahman Lavaee // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
2658955950cSRahman Lavaee // zero implies "no landing pad." This function inserts a NOP just before the EH
2663bb1ce23SARCHIT SAXENA // pad label to ensure a nonzero offset.
2673bb1ce23SARCHIT SAXENA void llvm::avoidZeroOffsetLandingPad(MachineFunction &MF) {
2688955950cSRahman Lavaee   for (auto &MBB : MF) {
2698955950cSRahman Lavaee     if (MBB.isBeginSection() && MBB.isEHPad()) {
2708955950cSRahman Lavaee       MachineBasicBlock::iterator MI = MBB.begin();
2718955950cSRahman Lavaee       while (!MI->isEHLabel())
2728955950cSRahman Lavaee         ++MI;
273ca72b0a7SDaniel Hoekwater       MF.getSubtarget().getInstrInfo()->insertNoop(MBB, MI);
2748955950cSRahman Lavaee     }
2758955950cSRahman Lavaee   }
2768955950cSRahman Lavaee }
2778955950cSRahman Lavaee 
278f70e39ecSRahman Lavaee bool llvm::hasInstrProfHashMismatch(MachineFunction &MF) {
279c32f3998SSriraman Tallam   if (!BBSectionsDetectSourceDrift)
280c32f3998SSriraman Tallam     return false;
281c32f3998SSriraman Tallam 
282c32f3998SSriraman Tallam   const char MetadataName[] = "instr_prof_hash_mismatch";
283c32f3998SSriraman Tallam   auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
284c32f3998SSriraman Tallam   if (Existing) {
285c32f3998SSriraman Tallam     MDTuple *Tuple = cast<MDTuple>(Existing);
2869e6d1f4bSKazu Hirata     for (const auto &N : Tuple->operands())
2875d3a8842SZain Jaffal       if (N.equalsStr(MetadataName))
288c32f3998SSriraman Tallam         return true;
289c32f3998SSriraman Tallam   }
290c32f3998SSriraman Tallam 
291c32f3998SSriraman Tallam   return false;
292c32f3998SSriraman Tallam }
293c32f3998SSriraman Tallam 
294acec6419SRahman Lavaee // Identify, arrange, and modify basic blocks which need separate sections
295acec6419SRahman Lavaee // according to the specification provided by the -fbasic-block-sections flag.
296acec6419SRahman Lavaee bool BasicBlockSections::handleBBSections(MachineFunction &MF) {
2978d943a92SSnehasish Kumar   auto BBSectionsType = MF.getTarget().getBBSectionsType();
298acec6419SRahman Lavaee   if (BBSectionsType == BasicBlockSection::None)
299acec6419SRahman Lavaee     return false;
300c32f3998SSriraman Tallam 
301c32f3998SSriraman Tallam   // Check for source drift. If the source has changed since the profiles
302c32f3998SSriraman Tallam   // were obtained, optimizing basic blocks might be sub-optimal.
303c32f3998SSriraman Tallam   // This only applies to BasicBlockSection::List as it creates
304c32f3998SSriraman Tallam   // clusters of basic blocks using basic block ids. Source drift can
305c32f3998SSriraman Tallam   // invalidate these groupings leading to sub-optimal code generation with
306c32f3998SSriraman Tallam   // regards to performance.
307c32f3998SSriraman Tallam   if (BBSectionsType == BasicBlockSection::List &&
308c32f3998SSriraman Tallam       hasInstrProfHashMismatch(MF))
309f70e39ecSRahman Lavaee     return false;
31069e47decSRahman Lavaee   // Renumber blocks before sorting them. This is useful for accessing the
31169e47decSRahman Lavaee   // original layout positions and finding the original fallthroughs.
3128d943a92SSnehasish Kumar   MF.RenumberBlocks();
3138d943a92SSnehasish Kumar 
314f70e39ecSRahman Lavaee   DenseMap<UniqueBBID, BBClusterInfo> FuncClusterInfo;
31528b91268SRahman Lavaee   if (BBSectionsType == BasicBlockSection::List) {
316f70e39ecSRahman Lavaee     auto [HasProfile, ClusterInfo] =
317f1ec0d12SNick Anderson         getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()
318f70e39ecSRahman Lavaee             .getClusterInfoForFunction(MF.getName());
31928b91268SRahman Lavaee     if (!HasProfile)
320f70e39ecSRahman Lavaee       return false;
321f70e39ecSRahman Lavaee     for (auto &BBClusterInfo : ClusterInfo) {
322f70e39ecSRahman Lavaee       FuncClusterInfo.try_emplace(BBClusterInfo.BBID, BBClusterInfo);
32328b91268SRahman Lavaee     }
32428b91268SRahman Lavaee   }
32528b91268SRahman Lavaee 
3268d943a92SSnehasish Kumar   MF.setBBSectionsType(BBSectionsType);
327f70e39ecSRahman Lavaee   assignSections(MF, FuncClusterInfo);
32894faadacSSnehasish Kumar 
329e1616ef9SRahman Lavaee   const MachineBasicBlock &EntryBB = MF.front();
330e1616ef9SRahman Lavaee   auto EntryBBSectionID = EntryBB.getSectionID();
33194faadacSSnehasish Kumar 
33294faadacSSnehasish Kumar   // Helper function for ordering BB sections as follows:
33394faadacSSnehasish Kumar   //   * Entry section (section including the entry block).
33494faadacSSnehasish Kumar   //   * Regular sections (in increasing order of their Number).
33594faadacSSnehasish Kumar   //     ...
33694faadacSSnehasish Kumar   //   * Exception section
33794faadacSSnehasish Kumar   //   * Cold section
33894faadacSSnehasish Kumar   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
33994faadacSSnehasish Kumar                                             const MBBSectionID &RHS) {
34094faadacSSnehasish Kumar     // We make sure that the section containing the entry block precedes all the
34194faadacSSnehasish Kumar     // other sections.
34294faadacSSnehasish Kumar     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
34394faadacSSnehasish Kumar       return LHS == EntryBBSectionID;
34494faadacSSnehasish Kumar     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
34594faadacSSnehasish Kumar   };
34694faadacSSnehasish Kumar 
34794faadacSSnehasish Kumar   // We sort all basic blocks to make sure the basic blocks of every cluster are
34894faadacSSnehasish Kumar   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
34994faadacSSnehasish Kumar   // increasing order of their section IDs, with the exception and the
35094faadacSSnehasish Kumar   // cold section placed at the end of the function.
351e1616ef9SRahman Lavaee   // Also, we force the entry block of the function to be placed at the
352e1616ef9SRahman Lavaee   // beginning of the function, regardless of the requested order.
35394faadacSSnehasish Kumar   auto Comparator = [&](const MachineBasicBlock &X,
35494faadacSSnehasish Kumar                         const MachineBasicBlock &Y) {
35594faadacSSnehasish Kumar     auto XSectionID = X.getSectionID();
35694faadacSSnehasish Kumar     auto YSectionID = Y.getSectionID();
35794faadacSSnehasish Kumar     if (XSectionID != YSectionID)
35894faadacSSnehasish Kumar       return MBBSectionOrder(XSectionID, YSectionID);
359e1616ef9SRahman Lavaee     // Make sure that the entry block is placed at the beginning.
360e1616ef9SRahman Lavaee     if (&X == &EntryBB || &Y == &EntryBB)
361e1616ef9SRahman Lavaee       return &X == &EntryBB;
36294faadacSSnehasish Kumar     // If the two basic block are in the same section, the order is decided by
36394faadacSSnehasish Kumar     // their position within the section.
36494faadacSSnehasish Kumar     if (XSectionID.Type == MBBSectionID::SectionType::Default)
365f70e39ecSRahman Lavaee       return FuncClusterInfo.lookup(*X.getBBID()).PositionInCluster <
366f70e39ecSRahman Lavaee              FuncClusterInfo.lookup(*Y.getBBID()).PositionInCluster;
36794faadacSSnehasish Kumar     return X.getNumber() < Y.getNumber();
36894faadacSSnehasish Kumar   };
36994faadacSSnehasish Kumar 
37094faadacSSnehasish Kumar   sortBasicBlocksAndUpdateBranches(MF, Comparator);
3718955950cSRahman Lavaee   avoidZeroOffsetLandingPad(MF);
3728d943a92SSnehasish Kumar   return true;
3738d943a92SSnehasish Kumar }
3748d943a92SSnehasish Kumar 
375acec6419SRahman Lavaee // When the BB address map needs to be generated, this renumbers basic blocks to
376acec6419SRahman Lavaee // make them appear in increasing order of their IDs in the function. This
377acec6419SRahman Lavaee // avoids the need to store basic block IDs in the BB address map section, since
378acec6419SRahman Lavaee // they can be determined implicitly.
379acec6419SRahman Lavaee bool BasicBlockSections::handleBBAddrMap(MachineFunction &MF) {
380acec6419SRahman Lavaee   if (!MF.getTarget().Options.BBAddrMap)
381acec6419SRahman Lavaee     return false;
382acec6419SRahman Lavaee   MF.RenumberBlocks();
383acec6419SRahman Lavaee   return true;
384acec6419SRahman Lavaee }
385acec6419SRahman Lavaee 
386acec6419SRahman Lavaee bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
387acec6419SRahman Lavaee   // First handle the basic block sections.
388acec6419SRahman Lavaee   auto R1 = handleBBSections(MF);
389acec6419SRahman Lavaee   // Handle basic block address map after basic block sections are finalized.
390acec6419SRahman Lavaee   auto R2 = handleBBAddrMap(MF);
391*d871b2e0SAlexis Engelke 
392*d871b2e0SAlexis Engelke   // We renumber blocks, so update the dominator tree we want to preserve.
393*d871b2e0SAlexis Engelke   if (auto *WP = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>())
394*d871b2e0SAlexis Engelke     WP->getDomTree().updateBlockNumbers();
395*d871b2e0SAlexis Engelke   if (auto *WP = getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>())
396*d871b2e0SAlexis Engelke     WP->getPostDomTree().updateBlockNumbers();
397*d871b2e0SAlexis Engelke 
398acec6419SRahman Lavaee   return R1 || R2;
399acec6419SRahman Lavaee }
400acec6419SRahman Lavaee 
4018d943a92SSnehasish Kumar void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
4028d943a92SSnehasish Kumar   AU.setPreservesAll();
403f1ec0d12SNick Anderson   AU.addRequired<BasicBlockSectionsProfileReaderWrapperPass>();
404*d871b2e0SAlexis Engelke   AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>();
405*d871b2e0SAlexis Engelke   AU.addUsedIfAvailable<MachinePostDominatorTreeWrapperPass>();
4068d943a92SSnehasish Kumar   MachineFunctionPass::getAnalysisUsage(AU);
4078d943a92SSnehasish Kumar }
4088d943a92SSnehasish Kumar 
40908cc0585SRahman Lavaee MachineFunctionPass *llvm::createBasicBlockSectionsPass() {
41008cc0585SRahman Lavaee   return new BasicBlockSections();
4118d943a92SSnehasish Kumar }
412