MachineFunctionSplitter.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. //===-- MachineFunctionSplitter.cpp - Split machine functions //-----------===//
  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. // \file
  10. // Uses profile information to split out cold blocks.
  11. //
  12. // This pass splits out cold machine basic blocks from the parent function. This
  13. // implementation leverages the basic block section framework. Blocks marked
  14. // cold by this pass are grouped together in a separate section prefixed with
  15. // ".text.unlikely.*". The linker can then group these together as a cold
  16. // section. The split part of the function is a contiguous region identified by
  17. // the symbol "foo.cold". Grouping all cold blocks across functions together
  18. // decreases fragmentation and improves icache and itlb utilization. Note that
  19. // the overall changes to the binary size are negligible; only a small number of
  20. // additional jump instructions may be introduced.
  21. //
  22. // For the original RFC of this pass please see
  23. // https://groups.google.com/d/msg/llvm-dev/RUegaMg-iqc/wFAVxa6fCgAJ
  24. //===----------------------------------------------------------------------===//
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/Analysis/ProfileSummaryInfo.h"
  27. #include "llvm/CodeGen/BasicBlockSectionUtils.h"
  28. #include "llvm/CodeGen/MachineBasicBlock.h"
  29. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  30. #include "llvm/CodeGen/MachineFunction.h"
  31. #include "llvm/CodeGen/MachineFunctionPass.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/Passes.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/InitializePasses.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include <optional>
  38. using namespace llvm;
  39. // FIXME: This cutoff value is CPU dependent and should be moved to
  40. // TargetTransformInfo once we consider enabling this on other platforms.
  41. // The value is expressed as a ProfileSummaryInfo integer percentile cutoff.
  42. // Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split.
  43. // The default was empirically determined to be optimal when considering cutoff
  44. // values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on
  45. // Intel CPUs.
  46. static cl::opt<unsigned>
  47. PercentileCutoff("mfs-psi-cutoff",
  48. cl::desc("Percentile profile summary cutoff used to "
  49. "determine cold blocks. Unused if set to zero."),
  50. cl::init(999950), cl::Hidden);
  51. static cl::opt<unsigned> ColdCountThreshold(
  52. "mfs-count-threshold",
  53. cl::desc(
  54. "Minimum number of times a block must be executed to be retained."),
  55. cl::init(1), cl::Hidden);
  56. static cl::opt<bool> SplitAllEHCode(
  57. "mfs-split-ehcode",
  58. cl::desc("Splits all EH code and it's descendants by default."),
  59. cl::init(false), cl::Hidden);
  60. namespace {
  61. class MachineFunctionSplitter : public MachineFunctionPass {
  62. public:
  63. static char ID;
  64. MachineFunctionSplitter() : MachineFunctionPass(ID) {
  65. initializeMachineFunctionSplitterPass(*PassRegistry::getPassRegistry());
  66. }
  67. StringRef getPassName() const override {
  68. return "Machine Function Splitter Transformation";
  69. }
  70. void getAnalysisUsage(AnalysisUsage &AU) const override;
  71. bool runOnMachineFunction(MachineFunction &F) override;
  72. };
  73. } // end anonymous namespace
  74. /// setDescendantEHBlocksCold - This splits all EH pads and blocks reachable
  75. /// only by EH pad as cold. This will help mark EH pads statically cold instead
  76. /// of relying on profile data.
  77. static void
  78. setDescendantEHBlocksCold(SmallVectorImpl<MachineBasicBlock *> &EHBlocks,
  79. MachineFunction &MF) {
  80. MachineBasicBlock *StartBlock = &MF.front();
  81. // A block can be unknown if its not reachable from anywhere
  82. // EH if its only reachable from start blocks via some path through EH pads
  83. // NonEH if it's reachable from Non EH blocks as well.
  84. enum Status { Unknown = 0, EH = 1, NonEH = 2 };
  85. DenseSet<MachineBasicBlock *> WorkList;
  86. DenseMap<MachineBasicBlock *, Status> Statuses;
  87. auto getStatus = [&](MachineBasicBlock *MBB) {
  88. if (Statuses.find(MBB) != Statuses.end())
  89. return Statuses[MBB];
  90. else
  91. return Unknown;
  92. };
  93. auto checkPredecessors = [&](MachineBasicBlock *MBB, Status Stat) {
  94. for (auto *PredMBB : MBB->predecessors()) {
  95. Status PredStatus = getStatus(PredMBB);
  96. // If status of predecessor block has gone above current block
  97. // we update current blocks status.
  98. if (PredStatus > Stat)
  99. Stat = PredStatus;
  100. }
  101. return Stat;
  102. };
  103. auto addSuccesors = [&](MachineBasicBlock *MBB) {
  104. for (auto *SuccMBB : MBB->successors()) {
  105. if (!SuccMBB->isEHPad())
  106. WorkList.insert(SuccMBB);
  107. }
  108. };
  109. // Insert the successors of start block
  110. // and landing pads successor.
  111. Statuses[StartBlock] = NonEH;
  112. addSuccesors(StartBlock);
  113. for (auto *LP : EHBlocks) {
  114. addSuccesors(LP);
  115. Statuses[LP] = EH;
  116. }
  117. // Worklist iterative algorithm.
  118. while (!WorkList.empty()) {
  119. auto *MBB = *WorkList.begin();
  120. WorkList.erase(MBB);
  121. Status OldStatus = getStatus(MBB);
  122. // Check on predecessors and check for
  123. // Status update.
  124. Status NewStatus = checkPredecessors(MBB, OldStatus);
  125. // Did the block status change?
  126. bool changed = OldStatus != NewStatus;
  127. if (changed) {
  128. addSuccesors(MBB);
  129. Statuses[MBB] = NewStatus;
  130. }
  131. }
  132. for (auto Entry : Statuses) {
  133. if (Entry.second == EH)
  134. Entry.first->setSectionID(MBBSectionID::ColdSectionID);
  135. }
  136. }
  137. static bool isColdBlock(const MachineBasicBlock &MBB,
  138. const MachineBlockFrequencyInfo *MBFI,
  139. ProfileSummaryInfo *PSI) {
  140. std::optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB);
  141. if (!Count)
  142. return true;
  143. if (PercentileCutoff > 0) {
  144. return PSI->isColdCountNthPercentile(PercentileCutoff, *Count);
  145. }
  146. return (*Count < ColdCountThreshold);
  147. }
  148. bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) {
  149. // We target functions with profile data. Static information in the form
  150. // of exception handling code may be split to cold if user passes the
  151. // mfs-split-ehcode flag.
  152. bool UseProfileData = MF.getFunction().hasProfileData();
  153. if (!UseProfileData && !SplitAllEHCode)
  154. return false;
  155. // TODO: We don't split functions where a section attribute has been set
  156. // since the split part may not be placed in a contiguous region. It may also
  157. // be more beneficial to augment the linker to ensure contiguous layout of
  158. // split functions within the same section as specified by the attribute.
  159. if (MF.getFunction().hasSection() ||
  160. MF.getFunction().hasFnAttribute("implicit-section-name"))
  161. return false;
  162. // We don't want to proceed further for cold functions
  163. // or functions of unknown hotness. Lukewarm functions have no prefix.
  164. std::optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
  165. if (SectionPrefix &&
  166. (*SectionPrefix == "unlikely" || *SectionPrefix == "unknown")) {
  167. return false;
  168. }
  169. // Renumbering blocks here preserves the order of the blocks as
  170. // sortBasicBlocksAndUpdateBranches uses the numeric identifier to sort
  171. // blocks. Preserving the order of blocks is essential to retaining decisions
  172. // made by prior passes such as MachineBlockPlacement.
  173. MF.RenumberBlocks();
  174. MF.setBBSectionsType(BasicBlockSection::Preset);
  175. MachineBlockFrequencyInfo *MBFI = nullptr;
  176. ProfileSummaryInfo *PSI = nullptr;
  177. if (UseProfileData) {
  178. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  179. PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  180. }
  181. SmallVector<MachineBasicBlock *, 2> LandingPads;
  182. for (auto &MBB : MF) {
  183. if (MBB.isEntryBlock())
  184. continue;
  185. if (MBB.isEHPad())
  186. LandingPads.push_back(&MBB);
  187. else if (UseProfileData && isColdBlock(MBB, MBFI, PSI) && !SplitAllEHCode)
  188. MBB.setSectionID(MBBSectionID::ColdSectionID);
  189. }
  190. // Split all EH code and it's descendant statically by default.
  191. if (SplitAllEHCode)
  192. setDescendantEHBlocksCold(LandingPads, MF);
  193. // We only split out eh pads if all of them are cold.
  194. else {
  195. bool HasHotLandingPads = false;
  196. for (const MachineBasicBlock *LP : LandingPads) {
  197. if (!isColdBlock(*LP, MBFI, PSI))
  198. HasHotLandingPads = true;
  199. }
  200. if (!HasHotLandingPads) {
  201. for (MachineBasicBlock *LP : LandingPads)
  202. LP->setSectionID(MBBSectionID::ColdSectionID);
  203. }
  204. }
  205. auto Comparator = [](const MachineBasicBlock &X, const MachineBasicBlock &Y) {
  206. return X.getSectionID().Type < Y.getSectionID().Type;
  207. };
  208. llvm::sortBasicBlocksAndUpdateBranches(MF, Comparator);
  209. llvm::avoidZeroOffsetLandingPad(MF);
  210. return true;
  211. }
  212. void MachineFunctionSplitter::getAnalysisUsage(AnalysisUsage &AU) const {
  213. AU.addRequired<MachineModuleInfoWrapperPass>();
  214. AU.addRequired<MachineBlockFrequencyInfo>();
  215. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  216. }
  217. char MachineFunctionSplitter::ID = 0;
  218. INITIALIZE_PASS(MachineFunctionSplitter, "machine-function-splitter",
  219. "Split machine functions using profile information", false,
  220. false)
  221. MachineFunctionPass *llvm::createMachineFunctionSplitterPass() {
  222. return new MachineFunctionSplitter();
  223. }