xref: /llvm-project/llvm/lib/CodeGen/MachineFunctionSplitter.cpp (revision 735ab61ac828bd61398e6847d60e308fdf2b54ec)
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 
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/EHUtils.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/CodeGen/BasicBlockSectionUtils.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/InitializePasses.h"
40 #include "llvm/Support/CommandLine.h"
41 #include <optional>
42 
43 using namespace llvm;
44 
45 // FIXME: This cutoff value is CPU dependent and should be moved to
46 // TargetTransformInfo once we consider enabling this on other platforms.
47 // The value is expressed as a ProfileSummaryInfo integer percentile cutoff.
48 // Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split.
49 // The default was empirically determined to be optimal when considering cutoff
50 // values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on
51 // Intel CPUs.
52 static cl::opt<unsigned>
53     PercentileCutoff("mfs-psi-cutoff",
54                      cl::desc("Percentile profile summary cutoff used to "
55                               "determine cold blocks. Unused if set to zero."),
56                      cl::init(999950), cl::Hidden);
57 
58 static cl::opt<unsigned> ColdCountThreshold(
59     "mfs-count-threshold",
60     cl::desc(
61         "Minimum number of times a block must be executed to be retained."),
62     cl::init(1), cl::Hidden);
63 
64 static cl::opt<bool> SplitAllEHCode(
65     "mfs-split-ehcode",
66     cl::desc("Splits all EH code and it's descendants by default."),
67     cl::init(false), cl::Hidden);
68 
69 namespace {
70 
71 class MachineFunctionSplitter : public MachineFunctionPass {
72 public:
73   static char ID;
74   MachineFunctionSplitter() : MachineFunctionPass(ID) {
75     initializeMachineFunctionSplitterPass(*PassRegistry::getPassRegistry());
76   }
77 
78   StringRef getPassName() const override {
79     return "Machine Function Splitter Transformation";
80   }
81 
82   void getAnalysisUsage(AnalysisUsage &AU) const override;
83 
84   bool runOnMachineFunction(MachineFunction &F) override;
85 };
86 } // end anonymous namespace
87 
88 /// setDescendantEHBlocksCold - This splits all EH pads and blocks reachable
89 /// only by EH pad as cold. This will help mark EH pads statically cold
90 /// instead of relying on profile data.
91 static void setDescendantEHBlocksCold(MachineFunction &MF) {
92   DenseSet<MachineBasicBlock *> EHBlocks;
93   computeEHOnlyBlocks(MF, EHBlocks);
94   for (auto Block : EHBlocks) {
95     Block->setSectionID(MBBSectionID::ColdSectionID);
96   }
97 }
98 
99 static void finishAdjustingBasicBlocksAndLandingPads(MachineFunction &MF) {
100   auto Comparator = [](const MachineBasicBlock &X, const MachineBasicBlock &Y) {
101     return X.getSectionID().Type < Y.getSectionID().Type;
102   };
103   llvm::sortBasicBlocksAndUpdateBranches(MF, Comparator);
104   llvm::avoidZeroOffsetLandingPad(MF);
105 }
106 
107 static bool isColdBlock(const MachineBasicBlock &MBB,
108                         const MachineBlockFrequencyInfo *MBFI,
109                         ProfileSummaryInfo *PSI) {
110   std::optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB);
111   // For instrumentation profiles and sample profiles, we use different ways
112   // to judge whether a block is cold and should be split.
113   if (PSI->hasInstrumentationProfile() || PSI->hasCSInstrumentationProfile()) {
114     // If using instrument profile, which is deemed "accurate", no count means
115     // cold.
116     if (!Count)
117       return true;
118     if (PercentileCutoff > 0)
119       return PSI->isColdCountNthPercentile(PercentileCutoff, *Count);
120     // Fallthrough to end of function.
121   } else if (PSI->hasSampleProfile()) {
122     // For sample profile, no count means "do not judege coldness".
123     if (!Count)
124       return false;
125   }
126 
127   return (*Count < ColdCountThreshold);
128 }
129 
130 bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) {
131   // We target functions with profile data. Static information in the form
132   // of exception handling code may be split to cold if user passes the
133   // mfs-split-ehcode flag.
134   bool UseProfileData = MF.getFunction().hasProfileData();
135   if (!UseProfileData && !SplitAllEHCode)
136     return false;
137 
138   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
139   if (!TII.isFunctionSafeToSplit(MF))
140     return false;
141 
142   // Renumbering blocks here preserves the order of the blocks as
143   // sortBasicBlocksAndUpdateBranches uses the numeric identifier to sort
144   // blocks. Preserving the order of blocks is essential to retaining decisions
145   // made by prior passes such as MachineBlockPlacement.
146   MF.RenumberBlocks();
147   MF.setBBSectionsType(BasicBlockSection::Preset);
148 
149   MachineBlockFrequencyInfo *MBFI = nullptr;
150   ProfileSummaryInfo *PSI = nullptr;
151   if (UseProfileData) {
152     MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
153     PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
154     // If we don't have a good profile (sample profile is not deemed
155     // as a "good profile") and the function is not hot, then early
156     // return. (Because we can only trust hot functions when profile
157     // quality is not good.)
158     if (PSI->hasSampleProfile() && !PSI->isFunctionHotInCallGraph(&MF, *MBFI)) {
159       // Split all EH code and it's descendant statically by default.
160       if (SplitAllEHCode)
161         setDescendantEHBlocksCold(MF);
162       finishAdjustingBasicBlocksAndLandingPads(MF);
163       return true;
164     }
165   }
166 
167   SmallVector<MachineBasicBlock *, 2> LandingPads;
168   for (auto &MBB : MF) {
169     if (MBB.isEntryBlock())
170       continue;
171 
172     if (MBB.isEHPad())
173       LandingPads.push_back(&MBB);
174     else if (UseProfileData && isColdBlock(MBB, MBFI, PSI) &&
175              TII.isMBBSafeToSplitToCold(MBB) && !SplitAllEHCode)
176       MBB.setSectionID(MBBSectionID::ColdSectionID);
177   }
178 
179   // Split all EH code and it's descendant statically by default.
180   if (SplitAllEHCode)
181     setDescendantEHBlocksCold(MF);
182   // We only split out eh pads if all of them are cold.
183   else {
184     // Here we have UseProfileData == true.
185     bool HasHotLandingPads = false;
186     for (const MachineBasicBlock *LP : LandingPads) {
187       if (!isColdBlock(*LP, MBFI, PSI) || !TII.isMBBSafeToSplitToCold(*LP))
188         HasHotLandingPads = true;
189     }
190     if (!HasHotLandingPads) {
191       for (MachineBasicBlock *LP : LandingPads)
192         LP->setSectionID(MBBSectionID::ColdSectionID);
193     }
194   }
195 
196   finishAdjustingBasicBlocksAndLandingPads(MF);
197   return true;
198 }
199 
200 void MachineFunctionSplitter::getAnalysisUsage(AnalysisUsage &AU) const {
201   AU.addRequired<MachineModuleInfoWrapperPass>();
202   AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
203   AU.addRequired<ProfileSummaryInfoWrapperPass>();
204 }
205 
206 char MachineFunctionSplitter::ID = 0;
207 INITIALIZE_PASS(MachineFunctionSplitter, "machine-function-splitter",
208                 "Split machine functions using profile information", false,
209                 false)
210 
211 MachineFunctionPass *llvm::createMachineFunctionSplitterPass() {
212   return new MachineFunctionSplitter();
213 }
214