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