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. Every cluster's section is labeled with a symbol to allow the 25 // linker to reorder the sections in any arbitrary sequence. A global order of 26 // these sections would encapsulate the function layout. 27 // 28 // There are a couple of challenges to be addressed: 29 // 30 // 1. The last basic block of every cluster should not have any implicit 31 // fallthrough to its next basic block, as it can be reordered by the linker. 32 // The compiler should make these fallthroughs explicit by adding 33 // unconditional jumps.. 34 // 35 // 2. All inter-cluster branch targets would now need to be resolved by the 36 // linker as they cannot be calculated during compile time. This is done 37 // using static relocations. Further, the compiler tries to use short branch 38 // instructions on some ISAs for small branch offsets. This is not possible 39 // for inter-cluster branches as the offset is not determined at compile 40 // time, and therefore, long branch instructions have to be used for those. 41 // 42 // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission 43 // needs special handling with basic block sections. DebugInfo needs to be 44 // emitted with more relocations as basic block sections can break a 45 // function into potentially several disjoint pieces, and CFI needs to be 46 // emitted per cluster. This also bloats the object file and binary sizes. 47 // 48 // Basic Block Labels 49 // ================== 50 // 51 // With -fbasic-block-sections=labels, or when a basic block is placed in a 52 // unique section, it is labelled with a symbol. This allows easy mapping of 53 // virtual addresses from PMU profiles back to the corresponding basic blocks. 54 // Since the number of basic blocks is large, the labeling bloats the symbol 55 // table sizes and the string table sizes significantly. While the binary size 56 // does increase, it does not affect performance as the symbol table is not 57 // loaded in memory during run-time. The string table size bloat is kept very 58 // minimal using a unary naming scheme that uses string suffix compression. The 59 // basic blocks for function foo are named "a.BB.foo", "aa.BB.foo", ... This 60 // turns out to be very good for string table sizes and the bloat in the string 61 // table size for a very large binary is ~8 %. The naming also allows using 62 // the --symbol-ordering-file option in LLD to arbitrarily reorder the 63 // sections. 64 // 65 //===----------------------------------------------------------------------===// 66 67 #include "llvm/ADT/Optional.h" 68 #include "llvm/ADT/SmallSet.h" 69 #include "llvm/ADT/SmallVector.h" 70 #include "llvm/ADT/StringMap.h" 71 #include "llvm/ADT/StringRef.h" 72 #include "llvm/CodeGen/MachineFunction.h" 73 #include "llvm/CodeGen/MachineFunctionPass.h" 74 #include "llvm/CodeGen/MachineModuleInfo.h" 75 #include "llvm/CodeGen/Passes.h" 76 #include "llvm/CodeGen/TargetInstrInfo.h" 77 #include "llvm/InitializePasses.h" 78 #include "llvm/Support/Error.h" 79 #include "llvm/Support/LineIterator.h" 80 #include "llvm/Support/MemoryBuffer.h" 81 #include "llvm/Target/TargetMachine.h" 82 83 using llvm::SmallSet; 84 using llvm::SmallVector; 85 using llvm::StringMap; 86 using llvm::StringRef; 87 using namespace llvm; 88 89 namespace { 90 91 // This struct represents the cluster information for a machine basic block. 92 struct BBClusterInfo { 93 // MachineBasicBlock ID. 94 unsigned MBBNumber; 95 // Cluster ID this basic block belongs to. 96 unsigned ClusterID; 97 // Position of basic block within the cluster. 98 unsigned PositionInCluster; 99 }; 100 101 using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>; 102 103 class BasicBlockSections : public MachineFunctionPass { 104 public: 105 static char ID; 106 107 // This contains the basic-block-sections profile. 108 const MemoryBuffer *MBuf = nullptr; 109 110 // This encapsulates the BB cluster information for the whole program. 111 // 112 // For every function name, it contains the cluster information for (all or 113 // some of) its basic blocks. The cluster information for every basic block 114 // includes its cluster ID along with the position of the basic block in that 115 // cluster. 116 ProgramBBClusterInfoMapTy ProgramBBClusterInfo; 117 118 // Some functions have alias names. We use this map to find the main alias 119 // name for which we have mapping in ProgramBBClusterInfo. 120 StringMap<StringRef> FuncAliasMap; 121 122 BasicBlockSections(const MemoryBuffer *Buf) 123 : MachineFunctionPass(ID), MBuf(Buf) { 124 initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry()); 125 }; 126 127 BasicBlockSections() : MachineFunctionPass(ID) { 128 initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry()); 129 } 130 131 StringRef getPassName() const override { 132 return "Basic Block Sections Analysis"; 133 } 134 135 void getAnalysisUsage(AnalysisUsage &AU) const override; 136 137 /// Read profiles of basic blocks if available here. 138 bool doInitialization(Module &M) override; 139 140 /// Identify basic blocks that need separate sections and prepare to emit them 141 /// accordingly. 142 bool runOnMachineFunction(MachineFunction &MF) override; 143 }; 144 145 } // end anonymous namespace 146 147 char BasicBlockSections::ID = 0; 148 INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare", 149 "Prepares for basic block sections, by splitting functions " 150 "into clusters of basic blocks.", 151 false, false) 152 153 // This function updates and optimizes the branching instructions of every basic 154 // block in a given function to account for changes in the layout. 155 static void updateBranches( 156 MachineFunction &MF, 157 const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) { 158 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 159 SmallVector<MachineOperand, 4> Cond; 160 for (auto &MBB : MF) { 161 auto NextMBBI = std::next(MBB.getIterator()); 162 auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()]; 163 // If this block had a fallthrough before we need an explicit unconditional 164 // branch to that block if either 165 // 1- the block ends a section, which means its next block may be 166 // reorderd by the linker, or 167 // 2- the fallthrough block is not adjacent to the block in the new 168 // order. 169 if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB)) 170 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 171 172 // We do not optimize branches for machine basic blocks ending sections, as 173 // their adjacent block might be reordered by the linker. 174 if (MBB.isEndSection()) 175 continue; 176 177 // It might be possible to optimize branches by flipping the branch 178 // condition. 179 Cond.clear(); 180 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 181 if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 182 continue; 183 MBB.updateTerminator(FTMBB); 184 } 185 } 186 187 // This function provides the BBCluster information associated with a function. 188 // Returns true if a valid association exists and false otherwise. 189 static bool getBBClusterInfoForFunction( 190 const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap, 191 const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo, 192 std::vector<Optional<BBClusterInfo>> &V) { 193 // Get the main alias name for the function. 194 auto FuncName = MF.getName(); 195 auto R = FuncAliasMap.find(FuncName); 196 StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second; 197 198 // Find the assoicated cluster information. 199 auto P = ProgramBBClusterInfo.find(AliasName); 200 if (P == ProgramBBClusterInfo.end()) 201 return false; 202 203 if (P->second.empty()) { 204 // This indicates that sections are desired for all basic blocks of this 205 // function. We clear the BBClusterInfo vector to denote this. 206 V.clear(); 207 return true; 208 } 209 210 V.resize(MF.getNumBlockIDs()); 211 for (auto bbClusterInfo : P->second) { 212 // Bail out if the cluster information contains invalid MBB numbers. 213 if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs()) 214 return false; 215 V[bbClusterInfo.MBBNumber] = bbClusterInfo; 216 } 217 return true; 218 } 219 220 // This function sorts basic blocks according to the cluster's information. 221 // All explicitly specified clusters of basic blocks will be ordered 222 // accordingly. All non-specified BBs go into a separate "Cold" section. 223 // Additionally, if exception handling landing pads end up in more than one 224 // clusters, they are moved into a single "Exception" section. Eventually, 225 // clusters are ordered in increasing order of their IDs, with the "Exception" 226 // and "Cold" succeeding all other clusters. 227 // FuncBBClusterInfo represent the cluster information for basic blocks. If this 228 // is empty, it means unique sections for all basic blocks in the function. 229 static bool assignSectionsAndSortBasicBlocks( 230 MachineFunction &MF, 231 const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) { 232 assert(MF.hasBBSections() && "BB Sections is not set for function."); 233 // This variable stores the section ID of the cluster containing eh_pads (if 234 // all eh_pads are one cluster). If more than one cluster contain eh_pads, we 235 // set it equal to ExceptionSectionID. 236 Optional<MBBSectionID> EHPadsSectionID; 237 238 for (auto &MBB : MF) { 239 // With the 'all' option, every basic block is placed in a unique section. 240 // With the 'list' option, every basic block is placed in a section 241 // associated with its cluster, unless we want individual unique sections 242 // for every basic block in this function (if FuncBBClusterInfo is empty). 243 if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All || 244 FuncBBClusterInfo.empty()) { 245 // If unique sections are desired for all basic blocks of the function, we 246 // set every basic block's section ID equal to its number (basic block 247 // id). This further ensures that basic blocks are ordered canonically. 248 MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())}); 249 } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue()) 250 MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID); 251 else { 252 // BB goes into the special cold section if it is not specified in the 253 // cluster info map. 254 MBB.setSectionID(MBBSectionID::ColdSectionID); 255 } 256 257 if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() && 258 EHPadsSectionID != MBBSectionID::ExceptionSectionID) { 259 // If we already have one cluster containing eh_pads, this must be updated 260 // to ExceptionSectionID. Otherwise, we set it equal to the current 261 // section ID. 262 EHPadsSectionID = EHPadsSectionID.hasValue() 263 ? MBBSectionID::ExceptionSectionID 264 : MBB.getSectionID(); 265 } 266 } 267 268 // If EHPads are in more than one section, this places all of them in the 269 // special exception section. 270 if (EHPadsSectionID == MBBSectionID::ExceptionSectionID) 271 for (auto &MBB : MF) 272 if (MBB.isEHPad()) 273 MBB.setSectionID(EHPadsSectionID.getValue()); 274 275 SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs( 276 MF.getNumBlockIDs()); 277 for (auto &MBB : MF) 278 PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 279 280 // We make sure that the cluster including the entry basic block precedes all 281 // other clusters. 282 auto EntryBBSectionID = MF.front().getSectionID(); 283 284 // Helper function for ordering BB sections as follows: 285 // * Entry section (section including the entry block). 286 // * Regular sections (in increasing order of their Number). 287 // ... 288 // * Exception section 289 // * Cold section 290 auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS, 291 const MBBSectionID &RHS) { 292 // We make sure that the section containing the entry block precedes all the 293 // other sections. 294 if (LHS == EntryBBSectionID || RHS == EntryBBSectionID) 295 return LHS == EntryBBSectionID; 296 return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type; 297 }; 298 299 // We sort all basic blocks to make sure the basic blocks of every cluster are 300 // contiguous and ordered accordingly. Furthermore, clusters are ordered in 301 // increasing order of their section IDs, with the exception and the 302 // cold section placed at the end of the function. 303 MF.sort([&](MachineBasicBlock &X, MachineBasicBlock &Y) { 304 auto XSectionID = X.getSectionID(); 305 auto YSectionID = Y.getSectionID(); 306 if (XSectionID != YSectionID) 307 return MBBSectionOrder(XSectionID, YSectionID); 308 // If the two basic block are in the same section, the order is decided by 309 // their position within the section. 310 if (XSectionID.Type == MBBSectionID::SectionType::Default) 311 return FuncBBClusterInfo[X.getNumber()]->PositionInCluster < 312 FuncBBClusterInfo[Y.getNumber()]->PositionInCluster; 313 return X.getNumber() < Y.getNumber(); 314 }); 315 316 // Set IsBeginSection and IsEndSection according to the assigned section IDs. 317 MF.assignBeginEndSections(); 318 319 // After reordering basic blocks, we must update basic block branches to 320 // insert explicit fallthrough branches when required and optimize branches 321 // when possible. 322 updateBranches(MF, PreLayoutFallThroughs); 323 324 return true; 325 } 326 327 bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) { 328 auto BBSectionsType = MF.getTarget().getBBSectionsType(); 329 assert(BBSectionsType != BasicBlockSection::None && 330 "BB Sections not enabled!"); 331 // Renumber blocks before sorting them for basic block sections. This is 332 // useful during sorting, basic blocks in the same section will retain the 333 // default order. This renumbering should also be done for basic block 334 // labels to match the profiles with the correct blocks. 335 MF.RenumberBlocks(); 336 337 if (BBSectionsType == BasicBlockSection::Labels) { 338 MF.setBBSectionsType(BBSectionsType); 339 MF.createBBLabels(); 340 return true; 341 } 342 343 std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo; 344 if (BBSectionsType == BasicBlockSection::List && 345 !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo, 346 FuncBBClusterInfo)) 347 return true; 348 MF.setBBSectionsType(BBSectionsType); 349 MF.createBBLabels(); 350 assignSectionsAndSortBasicBlocks(MF, FuncBBClusterInfo); 351 return true; 352 } 353 354 // Basic Block Sections can be enabled for a subset of machine basic blocks. 355 // This is done by passing a file containing names of functions for which basic 356 // block sections are desired. Additionally, machine basic block ids of the 357 // functions can also be specified for a finer granularity. Moreover, a cluster 358 // of basic blocks could be assigned to the same section. 359 // A file with basic block sections for all of function main and three blocks 360 // for function foo (of which 1 and 2 are placed in a cluster) looks like this: 361 // ---------------------------- 362 // list.txt: 363 // !main 364 // !foo 365 // !!1 2 366 // !!4 367 static Error getBBClusterInfo(const MemoryBuffer *MBuf, 368 ProgramBBClusterInfoMapTy &ProgramBBClusterInfo, 369 StringMap<StringRef> &FuncAliasMap) { 370 assert(MBuf); 371 line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#'); 372 373 auto invalidProfileError = [&](auto Message) { 374 return make_error<StringError>( 375 Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " + 376 Twine(LineIt.line_number()) + ": " + Message), 377 inconvertibleErrorCode()); 378 }; 379 380 auto FI = ProgramBBClusterInfo.end(); 381 382 // Current cluster ID corresponding to this function. 383 unsigned CurrentCluster = 0; 384 // Current position in the current cluster. 385 unsigned CurrentPosition = 0; 386 387 // Temporary set to ensure every basic block ID appears once in the clusters 388 // of a function. 389 SmallSet<unsigned, 4> FuncBBIDs; 390 391 for (; !LineIt.is_at_eof(); ++LineIt) { 392 StringRef S(*LineIt); 393 if (S[0] == '@') 394 continue; 395 // Check for the leading "!" 396 if (!S.consume_front("!") || S.empty()) 397 break; 398 // Check for second "!" which indicates a cluster of basic blocks. 399 if (S.consume_front("!")) { 400 if (FI == ProgramBBClusterInfo.end()) 401 return invalidProfileError( 402 "Cluster list does not follow a function name specifier."); 403 SmallVector<StringRef, 4> BBIndexes; 404 S.split(BBIndexes, ' '); 405 // Reset current cluster position. 406 CurrentPosition = 0; 407 for (auto BBIndexStr : BBIndexes) { 408 unsigned long long BBIndex; 409 if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex)) 410 return invalidProfileError(Twine("Unsigned integer expected: '") + 411 BBIndexStr + "'."); 412 if (!FuncBBIDs.insert(BBIndex).second) 413 return invalidProfileError(Twine("Duplicate basic block id found '") + 414 BBIndexStr + "'."); 415 if (!BBIndex && CurrentPosition) 416 return invalidProfileError("Entry BB (0) does not begin a cluster."); 417 418 FI->second.emplace_back(BBClusterInfo{ 419 ((unsigned)BBIndex), CurrentCluster, CurrentPosition++}); 420 } 421 CurrentCluster++; 422 } else { // This is a function name specifier. 423 // Function aliases are separated using '/'. We use the first function 424 // name for the cluster info mapping and delegate all other aliases to 425 // this one. 426 SmallVector<StringRef, 4> Aliases; 427 S.split(Aliases, '/'); 428 for (size_t i = 1; i < Aliases.size(); ++i) 429 FuncAliasMap.try_emplace(Aliases[i], Aliases.front()); 430 431 // Prepare for parsing clusters of this function name. 432 // Start a new cluster map for this function name. 433 FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first; 434 CurrentCluster = 0; 435 FuncBBIDs.clear(); 436 } 437 } 438 return Error::success(); 439 } 440 441 bool BasicBlockSections::doInitialization(Module &M) { 442 if (!MBuf) 443 return false; 444 if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap)) 445 report_fatal_error(std::move(Err)); 446 return false; 447 } 448 449 void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const { 450 AU.setPreservesAll(); 451 MachineFunctionPass::getAnalysisUsage(AU); 452 } 453 454 MachineFunctionPass * 455 llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) { 456 return new BasicBlockSections(Buf); 457 } 458