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