1e8d8bef9SDimitry Andric //===-- MachineFunctionSplitter.cpp - Split machine functions //-----------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // \file
10e8d8bef9SDimitry Andric // Uses profile information to split out cold blocks.
11e8d8bef9SDimitry Andric //
12e8d8bef9SDimitry Andric // This pass splits out cold machine basic blocks from the parent function. This
13e8d8bef9SDimitry Andric // implementation leverages the basic block section framework. Blocks marked
14e8d8bef9SDimitry Andric // cold by this pass are grouped together in a separate section prefixed with
15e8d8bef9SDimitry Andric // ".text.unlikely.*". The linker can then group these together as a cold
16e8d8bef9SDimitry Andric // section. The split part of the function is a contiguous region identified by
17e8d8bef9SDimitry Andric // the symbol "foo.cold". Grouping all cold blocks across functions together
18e8d8bef9SDimitry Andric // decreases fragmentation and improves icache and itlb utilization. Note that
19e8d8bef9SDimitry Andric // the overall changes to the binary size are negligible; only a small number of
20e8d8bef9SDimitry Andric // additional jump instructions may be introduced.
21e8d8bef9SDimitry Andric //
22e8d8bef9SDimitry Andric // For the original RFC of this pass please see
23e8d8bef9SDimitry Andric // https://groups.google.com/d/msg/llvm-dev/RUegaMg-iqc/wFAVxa6fCgAJ
24e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
25e8d8bef9SDimitry Andric 
26fe6060f1SDimitry Andric #include "llvm/ADT/SmallVector.h"
27e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
28e8d8bef9SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
29e8d8bef9SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
30e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
31e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
33e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
34e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
35e8d8bef9SDimitry Andric #include "llvm/CodeGen/Passes.h"
36e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
37e8d8bef9SDimitry Andric #include "llvm/IR/Module.h"
38e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
39e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h"
40e8d8bef9SDimitry Andric 
41e8d8bef9SDimitry Andric using namespace llvm;
42e8d8bef9SDimitry Andric 
43e8d8bef9SDimitry Andric // FIXME: This cutoff value is CPU dependent and should be moved to
44e8d8bef9SDimitry Andric // TargetTransformInfo once we consider enabling this on other platforms.
45e8d8bef9SDimitry Andric // The value is expressed as a ProfileSummaryInfo integer percentile cutoff.
46e8d8bef9SDimitry Andric // Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split.
47e8d8bef9SDimitry Andric // The default was empirically determined to be optimal when considering cutoff
48e8d8bef9SDimitry Andric // values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on
49e8d8bef9SDimitry Andric // Intel CPUs.
50e8d8bef9SDimitry Andric static cl::opt<unsigned>
51e8d8bef9SDimitry Andric     PercentileCutoff("mfs-psi-cutoff",
52e8d8bef9SDimitry Andric                      cl::desc("Percentile profile summary cutoff used to "
53e8d8bef9SDimitry Andric                               "determine cold blocks. Unused if set to zero."),
54e8d8bef9SDimitry Andric                      cl::init(999950), cl::Hidden);
55e8d8bef9SDimitry Andric 
56e8d8bef9SDimitry Andric static cl::opt<unsigned> ColdCountThreshold(
57e8d8bef9SDimitry Andric     "mfs-count-threshold",
58e8d8bef9SDimitry Andric     cl::desc(
59e8d8bef9SDimitry Andric         "Minimum number of times a block must be executed to be retained."),
60e8d8bef9SDimitry Andric     cl::init(1), cl::Hidden);
61e8d8bef9SDimitry Andric 
62e8d8bef9SDimitry Andric namespace {
63e8d8bef9SDimitry Andric 
64e8d8bef9SDimitry Andric class MachineFunctionSplitter : public MachineFunctionPass {
65e8d8bef9SDimitry Andric public:
66e8d8bef9SDimitry Andric   static char ID;
67e8d8bef9SDimitry Andric   MachineFunctionSplitter() : MachineFunctionPass(ID) {
68e8d8bef9SDimitry Andric     initializeMachineFunctionSplitterPass(*PassRegistry::getPassRegistry());
69e8d8bef9SDimitry Andric   }
70e8d8bef9SDimitry Andric 
71e8d8bef9SDimitry Andric   StringRef getPassName() const override {
72e8d8bef9SDimitry Andric     return "Machine Function Splitter Transformation";
73e8d8bef9SDimitry Andric   }
74e8d8bef9SDimitry Andric 
75e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
76e8d8bef9SDimitry Andric 
77e8d8bef9SDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
78e8d8bef9SDimitry Andric };
79e8d8bef9SDimitry Andric } // end anonymous namespace
80e8d8bef9SDimitry Andric 
81fe6060f1SDimitry Andric static bool isColdBlock(const MachineBasicBlock &MBB,
82e8d8bef9SDimitry Andric                         const MachineBlockFrequencyInfo *MBFI,
83e8d8bef9SDimitry Andric                         ProfileSummaryInfo *PSI) {
84e8d8bef9SDimitry Andric   Optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB);
85e8d8bef9SDimitry Andric   if (!Count.hasValue())
86e8d8bef9SDimitry Andric     return true;
87e8d8bef9SDimitry Andric 
88e8d8bef9SDimitry Andric   if (PercentileCutoff > 0) {
89e8d8bef9SDimitry Andric     return PSI->isColdCountNthPercentile(PercentileCutoff, *Count);
90e8d8bef9SDimitry Andric   }
91e8d8bef9SDimitry Andric   return (*Count < ColdCountThreshold);
92e8d8bef9SDimitry Andric }
93e8d8bef9SDimitry Andric 
94e8d8bef9SDimitry Andric bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) {
95e8d8bef9SDimitry Andric   // TODO: We only target functions with profile data. Static information may
96e8d8bef9SDimitry Andric   // also be considered but we don't see performance improvements yet.
97e8d8bef9SDimitry Andric   if (!MF.getFunction().hasProfileData())
98e8d8bef9SDimitry Andric     return false;
99e8d8bef9SDimitry Andric 
100e8d8bef9SDimitry Andric   // TODO: We don't split functions where a section attribute has been set
101e8d8bef9SDimitry Andric   // since the split part may not be placed in a contiguous region. It may also
102e8d8bef9SDimitry Andric   // be more beneficial to augment the linker to ensure contiguous layout of
103e8d8bef9SDimitry Andric   // split functions within the same section as specified by the attribute.
104fe6060f1SDimitry Andric   if (MF.getFunction().hasSection() ||
105fe6060f1SDimitry Andric       MF.getFunction().hasFnAttribute("implicit-section-name"))
106e8d8bef9SDimitry Andric     return false;
107e8d8bef9SDimitry Andric 
108e8d8bef9SDimitry Andric   // We don't want to proceed further for cold functions
109e8d8bef9SDimitry Andric   // or functions of unknown hotness. Lukewarm functions have no prefix.
110e8d8bef9SDimitry Andric   Optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
111e8d8bef9SDimitry Andric   if (SectionPrefix.hasValue() &&
112e8d8bef9SDimitry Andric       (SectionPrefix.getValue().equals("unlikely") ||
113e8d8bef9SDimitry Andric        SectionPrefix.getValue().equals("unknown"))) {
114e8d8bef9SDimitry Andric     return false;
115e8d8bef9SDimitry Andric   }
116e8d8bef9SDimitry Andric 
117e8d8bef9SDimitry Andric   // Renumbering blocks here preserves the order of the blocks as
118e8d8bef9SDimitry Andric   // sortBasicBlocksAndUpdateBranches uses the numeric identifier to sort
119e8d8bef9SDimitry Andric   // blocks. Preserving the order of blocks is essential to retaining decisions
120e8d8bef9SDimitry Andric   // made by prior passes such as MachineBlockPlacement.
121e8d8bef9SDimitry Andric   MF.RenumberBlocks();
122e8d8bef9SDimitry Andric   MF.setBBSectionsType(BasicBlockSection::Preset);
123e8d8bef9SDimitry Andric   auto *MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
124e8d8bef9SDimitry Andric   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
125e8d8bef9SDimitry Andric 
126fe6060f1SDimitry Andric   SmallVector<MachineBasicBlock *, 2> LandingPads;
127e8d8bef9SDimitry Andric   for (auto &MBB : MF) {
128fe6060f1SDimitry Andric     if (MBB.isEntryBlock())
129e8d8bef9SDimitry Andric       continue;
130fe6060f1SDimitry Andric 
131fe6060f1SDimitry Andric     if (MBB.isEHPad())
132fe6060f1SDimitry Andric       LandingPads.push_back(&MBB);
133fe6060f1SDimitry Andric     else if (isColdBlock(MBB, MBFI, PSI))
134e8d8bef9SDimitry Andric       MBB.setSectionID(MBBSectionID::ColdSectionID);
135e8d8bef9SDimitry Andric   }
136e8d8bef9SDimitry Andric 
137fe6060f1SDimitry Andric   // We only split out eh pads if all of them are cold.
138fe6060f1SDimitry Andric   bool HasHotLandingPads = false;
139fe6060f1SDimitry Andric   for (const MachineBasicBlock *LP : LandingPads) {
140fe6060f1SDimitry Andric     if (!isColdBlock(*LP, MBFI, PSI))
141fe6060f1SDimitry Andric       HasHotLandingPads = true;
142fe6060f1SDimitry Andric   }
143fe6060f1SDimitry Andric   if (!HasHotLandingPads) {
144fe6060f1SDimitry Andric     for (MachineBasicBlock *LP : LandingPads)
145fe6060f1SDimitry Andric       LP->setSectionID(MBBSectionID::ColdSectionID);
146fe6060f1SDimitry Andric   }
147fe6060f1SDimitry Andric 
148e8d8bef9SDimitry Andric   auto Comparator = [](const MachineBasicBlock &X, const MachineBasicBlock &Y) {
149e8d8bef9SDimitry Andric     return X.getSectionID().Type < Y.getSectionID().Type;
150e8d8bef9SDimitry Andric   };
151e8d8bef9SDimitry Andric   llvm::sortBasicBlocksAndUpdateBranches(MF, Comparator);
152e8d8bef9SDimitry Andric 
153e8d8bef9SDimitry Andric   return true;
154e8d8bef9SDimitry Andric }
155e8d8bef9SDimitry Andric 
156e8d8bef9SDimitry Andric void MachineFunctionSplitter::getAnalysisUsage(AnalysisUsage &AU) const {
157e8d8bef9SDimitry Andric   AU.addRequired<MachineModuleInfoWrapperPass>();
158e8d8bef9SDimitry Andric   AU.addRequired<MachineBlockFrequencyInfo>();
159e8d8bef9SDimitry Andric   AU.addRequired<ProfileSummaryInfoWrapperPass>();
160e8d8bef9SDimitry Andric }
161e8d8bef9SDimitry Andric 
162e8d8bef9SDimitry Andric char MachineFunctionSplitter::ID = 0;
163e8d8bef9SDimitry Andric INITIALIZE_PASS(MachineFunctionSplitter, "machine-function-splitter",
164e8d8bef9SDimitry Andric                 "Split machine functions using profile information", false,
165e8d8bef9SDimitry Andric                 false)
166e8d8bef9SDimitry Andric 
167e8d8bef9SDimitry Andric MachineFunctionPass *llvm::createMachineFunctionSplitterPass() {
168e8d8bef9SDimitry Andric   return new MachineFunctionSplitter();
169e8d8bef9SDimitry Andric }
170