BasicBlockSections.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. //===-- BasicBlockSections.cpp ---=========--------------------------------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // BasicBlockSections implementation.
  10. //
  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.
  16. //
  17. // Basic Block Sections
  18. // ====================
  19. //
  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).
  29. //
  30. // 0 2
  31. // 1 3 5
  32. //
  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.
  39. //
  40. // There are a couple of challenges to be addressed:
  41. //
  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..
  46. //
  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.
  53. //
  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.
  59. //
  60. // Basic Block Labels
  61. // ==================
  62. //
  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``.
  68. //
  69. //===----------------------------------------------------------------------===//
  70. #include "llvm/ADT/SmallVector.h"
  71. #include "llvm/ADT/StringRef.h"
  72. #include "llvm/CodeGen/BasicBlockSectionUtils.h"
  73. #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
  74. #include "llvm/CodeGen/MachineFunction.h"
  75. #include "llvm/CodeGen/MachineFunctionPass.h"
  76. #include "llvm/CodeGen/Passes.h"
  77. #include "llvm/CodeGen/TargetInstrInfo.h"
  78. #include "llvm/InitializePasses.h"
  79. #include "llvm/Target/TargetMachine.h"
  80. #include <optional>
  81. using namespace llvm;
  82. // Placing the cold clusters in a separate section mitigates against poor
  83. // profiles and allows optimizations such as hugepage mapping to be applied at a
  84. // section granularity. Defaults to ".text.split." which is recognized by lld
  85. // via the `-z keep-text-section-prefix` flag.
  86. cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
  87. "bbsections-cold-text-prefix",
  88. cl::desc("The text prefix to use for cold basic block clusters"),
  89. cl::init(".text.split."), cl::Hidden);
  90. cl::opt<bool> BBSectionsDetectSourceDrift(
  91. "bbsections-detect-source-drift",
  92. cl::desc("This checks if there is a fdo instr. profile hash "
  93. "mismatch for this function"),
  94. cl::init(true), cl::Hidden);
  95. namespace {
  96. class BasicBlockSections : public MachineFunctionPass {
  97. public:
  98. static char ID;
  99. BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
  100. BasicBlockSections() : MachineFunctionPass(ID) {
  101. initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
  102. }
  103. StringRef getPassName() const override {
  104. return "Basic Block Sections Analysis";
  105. }
  106. void getAnalysisUsage(AnalysisUsage &AU) const override;
  107. /// Identify basic blocks that need separate sections and prepare to emit them
  108. /// accordingly.
  109. bool runOnMachineFunction(MachineFunction &MF) override;
  110. };
  111. } // end anonymous namespace
  112. char BasicBlockSections::ID = 0;
  113. INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
  114. "Prepares for basic block sections, by splitting functions "
  115. "into clusters of basic blocks.",
  116. false, false)
  117. // This function updates and optimizes the branching instructions of every basic
  118. // block in a given function to account for changes in the layout.
  119. static void
  120. updateBranches(MachineFunction &MF,
  121. const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {
  122. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  123. SmallVector<MachineOperand, 4> Cond;
  124. for (auto &MBB : MF) {
  125. auto NextMBBI = std::next(MBB.getIterator());
  126. auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
  127. // If this block had a fallthrough before we need an explicit unconditional
  128. // branch to that block if either
  129. // 1- the block ends a section, which means its next block may be
  130. // reorderd by the linker, or
  131. // 2- the fallthrough block is not adjacent to the block in the new
  132. // order.
  133. if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
  134. TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
  135. // We do not optimize branches for machine basic blocks ending sections, as
  136. // their adjacent block might be reordered by the linker.
  137. if (MBB.isEndSection())
  138. continue;
  139. // It might be possible to optimize branches by flipping the branch
  140. // condition.
  141. Cond.clear();
  142. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
  143. if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
  144. continue;
  145. MBB.updateTerminator(FTMBB);
  146. }
  147. }
  148. // This function provides the BBCluster information associated with a function.
  149. // Returns true if a valid association exists and false otherwise.
  150. bool getBBClusterInfoForFunction(
  151. const MachineFunction &MF,
  152. BasicBlockSectionsProfileReader *BBSectionsProfileReader,
  153. DenseMap<unsigned, BBClusterInfo> &V) {
  154. // Find the assoicated cluster information.
  155. std::pair<bool, SmallVector<BBClusterInfo, 4>> P =
  156. BBSectionsProfileReader->getBBClusterInfoForFunction(MF.getName());
  157. if (!P.first)
  158. return false;
  159. if (P.second.empty()) {
  160. // This indicates that sections are desired for all basic blocks of this
  161. // function. We clear the BBClusterInfo vector to denote this.
  162. V.clear();
  163. return true;
  164. }
  165. for (const BBClusterInfo &BBCI : P.second)
  166. V[BBCI.BBID] = BBCI;
  167. return true;
  168. }
  169. // This function sorts basic blocks according to the cluster's information.
  170. // All explicitly specified clusters of basic blocks will be ordered
  171. // accordingly. All non-specified BBs go into a separate "Cold" section.
  172. // Additionally, if exception handling landing pads end up in more than one
  173. // clusters, they are moved into a single "Exception" section. Eventually,
  174. // clusters are ordered in increasing order of their IDs, with the "Exception"
  175. // and "Cold" succeeding all other clusters.
  176. // FuncBBClusterInfo represent the cluster information for basic blocks. It
  177. // maps from BBID of basic blocks to their cluster information. If this is
  178. // empty, it means unique sections for all basic blocks in the function.
  179. static void
  180. assignSections(MachineFunction &MF,
  181. const DenseMap<unsigned, BBClusterInfo> &FuncBBClusterInfo) {
  182. assert(MF.hasBBSections() && "BB Sections is not set for function.");
  183. // This variable stores the section ID of the cluster containing eh_pads (if
  184. // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
  185. // set it equal to ExceptionSectionID.
  186. std::optional<MBBSectionID> EHPadsSectionID;
  187. for (auto &MBB : MF) {
  188. // With the 'all' option, every basic block is placed in a unique section.
  189. // With the 'list' option, every basic block is placed in a section
  190. // associated with its cluster, unless we want individual unique sections
  191. // for every basic block in this function (if FuncBBClusterInfo is empty).
  192. if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
  193. FuncBBClusterInfo.empty()) {
  194. // If unique sections are desired for all basic blocks of the function, we
  195. // set every basic block's section ID equal to its original position in
  196. // the layout (which is equal to its number). This ensures that basic
  197. // blocks are ordered canonically.
  198. MBB.setSectionID(MBB.getNumber());
  199. } else {
  200. // TODO: Replace `getBBIDOrNumber` with `getBBID` once version 1 is
  201. // deprecated.
  202. auto I = FuncBBClusterInfo.find(MBB.getBBIDOrNumber());
  203. if (I != FuncBBClusterInfo.end()) {
  204. MBB.setSectionID(I->second.ClusterID);
  205. } else {
  206. // BB goes into the special cold section if it is not specified in the
  207. // cluster info map.
  208. MBB.setSectionID(MBBSectionID::ColdSectionID);
  209. }
  210. }
  211. if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
  212. EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
  213. // If we already have one cluster containing eh_pads, this must be updated
  214. // to ExceptionSectionID. Otherwise, we set it equal to the current
  215. // section ID.
  216. EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
  217. : MBB.getSectionID();
  218. }
  219. }
  220. // If EHPads are in more than one section, this places all of them in the
  221. // special exception section.
  222. if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
  223. for (auto &MBB : MF)
  224. if (MBB.isEHPad())
  225. MBB.setSectionID(*EHPadsSectionID);
  226. }
  227. void llvm::sortBasicBlocksAndUpdateBranches(
  228. MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
  229. [[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();
  230. SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());
  231. for (auto &MBB : MF)
  232. PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
  233. MF.sort(MBBCmp);
  234. assert(&MF.front() == EntryBlock &&
  235. "Entry block should not be displaced by basic block sections");
  236. // Set IsBeginSection and IsEndSection according to the assigned section IDs.
  237. MF.assignBeginEndSections();
  238. // After reordering basic blocks, we must update basic block branches to
  239. // insert explicit fallthrough branches when required and optimize branches
  240. // when possible.
  241. updateBranches(MF, PreLayoutFallThroughs);
  242. }
  243. // If the exception section begins with a landing pad, that landing pad will
  244. // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
  245. // zero implies "no landing pad." This function inserts a NOP just before the EH
  246. // pad label to ensure a nonzero offset.
  247. void llvm::avoidZeroOffsetLandingPad(MachineFunction &MF) {
  248. for (auto &MBB : MF) {
  249. if (MBB.isBeginSection() && MBB.isEHPad()) {
  250. MachineBasicBlock::iterator MI = MBB.begin();
  251. while (!MI->isEHLabel())
  252. ++MI;
  253. MCInst Nop = MF.getSubtarget().getInstrInfo()->getNop();
  254. BuildMI(MBB, MI, DebugLoc(),
  255. MF.getSubtarget().getInstrInfo()->get(Nop.getOpcode()));
  256. }
  257. }
  258. }
  259. // This checks if the source of this function has drifted since this binary was
  260. // profiled previously. For now, we are piggy backing on what PGO does to
  261. // detect this with instrumented profiles. PGO emits an hash of the IR and
  262. // checks if the hash has changed. Advanced basic block layout is usually done
  263. // on top of PGO optimized binaries and hence this check works well in practice.
  264. static bool hasInstrProfHashMismatch(MachineFunction &MF) {
  265. if (!BBSectionsDetectSourceDrift)
  266. return false;
  267. const char MetadataName[] = "instr_prof_hash_mismatch";
  268. auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
  269. if (Existing) {
  270. MDTuple *Tuple = cast<MDTuple>(Existing);
  271. for (const auto &N : Tuple->operands())
  272. if (cast<MDString>(N.get())->getString() == MetadataName)
  273. return true;
  274. }
  275. return false;
  276. }
  277. bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
  278. auto BBSectionsType = MF.getTarget().getBBSectionsType();
  279. assert(BBSectionsType != BasicBlockSection::None &&
  280. "BB Sections not enabled!");
  281. // Check for source drift. If the source has changed since the profiles
  282. // were obtained, optimizing basic blocks might be sub-optimal.
  283. // This only applies to BasicBlockSection::List as it creates
  284. // clusters of basic blocks using basic block ids. Source drift can
  285. // invalidate these groupings leading to sub-optimal code generation with
  286. // regards to performance.
  287. if (BBSectionsType == BasicBlockSection::List &&
  288. hasInstrProfHashMismatch(MF))
  289. return true;
  290. // Renumber blocks before sorting them. This is useful during sorting,
  291. // basic blocks in the same section will retain the default order.
  292. // This renumbering should also be done for basic block labels to match the
  293. // profiles with the correct blocks.
  294. // For LLVM_BB_ADDR_MAP versions 2 and higher, this renumbering serves
  295. // the different purpose of accessing the original layout positions and
  296. // finding the original fallthroughs.
  297. // TODO: Change the above comment accordingly when version 1 is deprecated.
  298. MF.RenumberBlocks();
  299. if (BBSectionsType == BasicBlockSection::Labels) {
  300. MF.setBBSectionsType(BBSectionsType);
  301. return true;
  302. }
  303. BBSectionsProfileReader = &getAnalysis<BasicBlockSectionsProfileReader>();
  304. // Map from BBID of blocks to their cluster information.
  305. DenseMap<unsigned, BBClusterInfo> FuncBBClusterInfo;
  306. if (BBSectionsType == BasicBlockSection::List &&
  307. !getBBClusterInfoForFunction(MF, BBSectionsProfileReader,
  308. FuncBBClusterInfo))
  309. return true;
  310. MF.setBBSectionsType(BBSectionsType);
  311. assignSections(MF, FuncBBClusterInfo);
  312. // We make sure that the cluster including the entry basic block precedes all
  313. // other clusters.
  314. auto EntryBBSectionID = MF.front().getSectionID();
  315. // Helper function for ordering BB sections as follows:
  316. // * Entry section (section including the entry block).
  317. // * Regular sections (in increasing order of their Number).
  318. // ...
  319. // * Exception section
  320. // * Cold section
  321. auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
  322. const MBBSectionID &RHS) {
  323. // We make sure that the section containing the entry block precedes all the
  324. // other sections.
  325. if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
  326. return LHS == EntryBBSectionID;
  327. return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
  328. };
  329. // We sort all basic blocks to make sure the basic blocks of every cluster are
  330. // contiguous and ordered accordingly. Furthermore, clusters are ordered in
  331. // increasing order of their section IDs, with the exception and the
  332. // cold section placed at the end of the function.
  333. auto Comparator = [&](const MachineBasicBlock &X,
  334. const MachineBasicBlock &Y) {
  335. auto XSectionID = X.getSectionID();
  336. auto YSectionID = Y.getSectionID();
  337. if (XSectionID != YSectionID)
  338. return MBBSectionOrder(XSectionID, YSectionID);
  339. // If the two basic block are in the same section, the order is decided by
  340. // their position within the section.
  341. if (XSectionID.Type == MBBSectionID::SectionType::Default)
  342. return FuncBBClusterInfo.lookup(X.getBBIDOrNumber()).PositionInCluster <
  343. FuncBBClusterInfo.lookup(Y.getBBIDOrNumber()).PositionInCluster;
  344. return X.getNumber() < Y.getNumber();
  345. };
  346. sortBasicBlocksAndUpdateBranches(MF, Comparator);
  347. avoidZeroOffsetLandingPad(MF);
  348. return true;
  349. }
  350. void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
  351. AU.setPreservesAll();
  352. AU.addRequired<BasicBlockSectionsProfileReader>();
  353. MachineFunctionPass::getAnalysisUsage(AU);
  354. }
  355. MachineFunctionPass *llvm::createBasicBlockSectionsPass() {
  356. return new BasicBlockSections();
  357. }