1 //===- bolt/Passes/ReorderFunctions.cpp - Function reordering pass --------===// 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 // This file implements ReorderFunctions class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "bolt/Passes/ReorderFunctions.h" 14 #include "bolt/Passes/HFSort.h" 15 #include "llvm/Support/CommandLine.h" 16 #include <fstream> 17 18 #define DEBUG_TYPE "hfsort" 19 20 using namespace llvm; 21 22 namespace opts { 23 24 extern cl::OptionCategory BoltOptCategory; 25 extern cl::opt<unsigned> Verbosity; 26 extern cl::opt<uint32_t> RandomSeed; 27 28 extern size_t padFunction(const bolt::BinaryFunction &Function); 29 30 cl::opt<bolt::ReorderFunctions::ReorderType> 31 ReorderFunctions("reorder-functions", 32 cl::desc("reorder and cluster functions (works only with relocations)"), 33 cl::init(bolt::ReorderFunctions::RT_NONE), 34 cl::values(clEnumValN(bolt::ReorderFunctions::RT_NONE, 35 "none", 36 "do not reorder functions"), 37 clEnumValN(bolt::ReorderFunctions::RT_EXEC_COUNT, 38 "exec-count", 39 "order by execution count"), 40 clEnumValN(bolt::ReorderFunctions::RT_HFSORT, 41 "hfsort", 42 "use hfsort algorithm"), 43 clEnumValN(bolt::ReorderFunctions::RT_HFSORT_PLUS, 44 "hfsort+", 45 "use hfsort+ algorithm"), 46 clEnumValN(bolt::ReorderFunctions::RT_PETTIS_HANSEN, 47 "pettis-hansen", 48 "use Pettis-Hansen algorithm"), 49 clEnumValN(bolt::ReorderFunctions::RT_RANDOM, 50 "random", 51 "reorder functions randomly"), 52 clEnumValN(bolt::ReorderFunctions::RT_USER, 53 "user", 54 "use function order specified by -function-order")), 55 cl::ZeroOrMore, 56 cl::cat(BoltOptCategory)); 57 58 static cl::opt<bool> ReorderFunctionsUseHotSize( 59 "reorder-functions-use-hot-size", 60 cl::desc("use a function's hot size when doing clustering"), cl::init(true), 61 cl::cat(BoltOptCategory)); 62 63 static cl::opt<std::string> 64 FunctionOrderFile("function-order", 65 cl::desc("file containing an ordered list of functions to use for function " 66 "reordering"), 67 cl::cat(BoltOptCategory)); 68 69 static cl::opt<std::string> 70 GenerateFunctionOrderFile("generate-function-order", 71 cl::desc("file to dump the ordered list of functions to use for function " 72 "reordering"), 73 cl::cat(BoltOptCategory)); 74 75 static cl::opt<std::string> 76 LinkSectionsFile("generate-link-sections", 77 cl::desc("generate a list of function sections in a format suitable for " 78 "inclusion in a linker script"), 79 cl::cat(BoltOptCategory)); 80 81 static cl::opt<bool> 82 UseEdgeCounts("use-edge-counts", 83 cl::desc("use edge count data when doing clustering"), 84 cl::init(true), cl::cat(BoltOptCategory)); 85 86 static cl::opt<bool> 87 CgFromPerfData("cg-from-perf-data", 88 cl::desc("use perf data directly when constructing the call graph" 89 " for stale functions"), 90 cl::init(true), 91 cl::ZeroOrMore, 92 cl::cat(BoltOptCategory)); 93 94 static cl::opt<bool> CgIgnoreRecursiveCalls( 95 "cg-ignore-recursive-calls", 96 cl::desc("ignore recursive calls when constructing the call graph"), 97 cl::init(true), cl::cat(BoltOptCategory)); 98 99 static cl::opt<bool> 100 CgUseSplitHotSize("cg-use-split-hot-size", 101 cl::desc("use hot/cold data on basic blocks to determine hot sizes for " 102 "call graph functions"), 103 cl::init(false), 104 cl::ZeroOrMore, 105 cl::cat(BoltOptCategory)); 106 107 } // namespace opts 108 109 namespace llvm { 110 namespace bolt { 111 112 using NodeId = CallGraph::NodeId; 113 using Arc = CallGraph::Arc; 114 using Node = CallGraph::Node; 115 116 void ReorderFunctions::reorder(std::vector<Cluster> &&Clusters, 117 std::map<uint64_t, BinaryFunction> &BFs) { 118 std::vector<uint64_t> FuncAddr(Cg.numNodes()); // Just for computing stats 119 uint64_t TotalSize = 0; 120 uint32_t Index = 0; 121 122 // Set order of hot functions based on clusters. 123 for (const Cluster &Cluster : Clusters) { 124 for (const NodeId FuncId : Cluster.targets()) { 125 Cg.nodeIdToFunc(FuncId)->setIndex(Index++); 126 FuncAddr[FuncId] = TotalSize; 127 TotalSize += Cg.size(FuncId); 128 } 129 } 130 131 if (opts::ReorderFunctions == RT_NONE) 132 return; 133 134 if (opts::Verbosity == 0) { 135 #ifndef NDEBUG 136 if (!DebugFlag || !isCurrentDebugType("hfsort")) 137 return; 138 #else 139 return; 140 #endif 141 } 142 143 bool PrintDetailed = opts::Verbosity > 1; 144 #ifndef NDEBUG 145 PrintDetailed |= 146 (DebugFlag && isCurrentDebugType("hfsort") && opts::Verbosity > 0); 147 #endif 148 TotalSize = 0; 149 uint64_t CurPage = 0; 150 uint64_t Hotfuncs = 0; 151 double TotalDistance = 0; 152 double TotalCalls = 0; 153 double TotalCalls64B = 0; 154 double TotalCalls4KB = 0; 155 double TotalCalls2MB = 0; 156 if (PrintDetailed) 157 outs() << "BOLT-INFO: Function reordering page layout\n" 158 << "BOLT-INFO: ============== page 0 ==============\n"; 159 for (Cluster &Cluster : Clusters) { 160 if (PrintDetailed) 161 outs() << format( 162 "BOLT-INFO: -------- density = %.3lf (%u / %u) --------\n", 163 Cluster.density(), Cluster.samples(), Cluster.size()); 164 165 for (NodeId FuncId : Cluster.targets()) { 166 if (Cg.samples(FuncId) > 0) { 167 Hotfuncs++; 168 169 if (PrintDetailed) 170 outs() << "BOLT-INFO: hot func " << *Cg.nodeIdToFunc(FuncId) << " (" 171 << Cg.size(FuncId) << ")\n"; 172 173 uint64_t Dist = 0; 174 uint64_t Calls = 0; 175 for (NodeId Dst : Cg.successors(FuncId)) { 176 if (FuncId == Dst) // ignore recursive calls in stats 177 continue; 178 const Arc &Arc = *Cg.findArc(FuncId, Dst); 179 const auto D = std::abs(FuncAddr[Arc.dst()] - 180 (FuncAddr[FuncId] + Arc.avgCallOffset())); 181 const double W = Arc.weight(); 182 if (D < 64 && PrintDetailed && opts::Verbosity > 2) 183 outs() << "BOLT-INFO: short (" << D << "B) call:\n" 184 << "BOLT-INFO: Src: " << *Cg.nodeIdToFunc(FuncId) << "\n" 185 << "BOLT-INFO: Dst: " << *Cg.nodeIdToFunc(Dst) << "\n" 186 << "BOLT-INFO: Weight = " << W << "\n" 187 << "BOLT-INFO: AvgOffset = " << Arc.avgCallOffset() << "\n"; 188 Calls += W; 189 if (D < 64) TotalCalls64B += W; 190 if (D < 4096) TotalCalls4KB += W; 191 if (D < (2 << 20)) TotalCalls2MB += W; 192 Dist += Arc.weight() * D; 193 if (PrintDetailed) 194 outs() << format("BOLT-INFO: arc: %u [@%lu+%.1lf] -> %u [@%lu]: " 195 "weight = %.0lf, callDist = %f\n", 196 Arc.src(), 197 FuncAddr[Arc.src()], 198 Arc.avgCallOffset(), 199 Arc.dst(), 200 FuncAddr[Arc.dst()], 201 Arc.weight(), D); 202 } 203 TotalCalls += Calls; 204 TotalDistance += Dist; 205 TotalSize += Cg.size(FuncId); 206 207 if (PrintDetailed) { 208 outs() << format("BOLT-INFO: start = %6u : avgCallDist = %lu : ", 209 TotalSize, Calls ? Dist / Calls : 0) 210 << Cg.nodeIdToFunc(FuncId)->getPrintName() << '\n'; 211 const uint64_t NewPage = TotalSize / HugePageSize; 212 if (NewPage != CurPage) { 213 CurPage = NewPage; 214 outs() << format( 215 "BOLT-INFO: ============== page %u ==============\n", CurPage); 216 } 217 } 218 } 219 } 220 } 221 outs() << "BOLT-INFO: Function reordering stats\n" 222 << format("BOLT-INFO: Number of hot functions: %u\n" 223 "BOLT-INFO: Number of clusters: %lu\n", 224 Hotfuncs, Clusters.size()) 225 << format("BOLT-INFO: Final average call distance = %.1lf " 226 "(%.0lf / %.0lf)\n", 227 TotalCalls ? TotalDistance / TotalCalls : 0, TotalDistance, 228 TotalCalls) 229 << format("BOLT-INFO: Total Calls = %.0lf\n", TotalCalls); 230 if (TotalCalls) 231 outs() << format("BOLT-INFO: Total Calls within 64B = %.0lf (%.2lf%%)\n", 232 TotalCalls64B, 100 * TotalCalls64B / TotalCalls) 233 << format("BOLT-INFO: Total Calls within 4KB = %.0lf (%.2lf%%)\n", 234 TotalCalls4KB, 100 * TotalCalls4KB / TotalCalls) 235 << format("BOLT-INFO: Total Calls within 2MB = %.0lf (%.2lf%%)\n", 236 TotalCalls2MB, 100 * TotalCalls2MB / TotalCalls); 237 } 238 239 namespace { 240 241 std::vector<std::string> readFunctionOrderFile() { 242 std::vector<std::string> FunctionNames; 243 std::ifstream FuncsFile(opts::FunctionOrderFile, std::ios::in); 244 if (!FuncsFile) { 245 errs() << "Ordered functions file \"" << opts::FunctionOrderFile 246 << "\" can't be opened.\n"; 247 exit(1); 248 } 249 std::string FuncName; 250 while (std::getline(FuncsFile, FuncName)) 251 FunctionNames.push_back(FuncName); 252 return FunctionNames; 253 } 254 255 } 256 257 void ReorderFunctions::runOnFunctions(BinaryContext &BC) { 258 auto &BFs = BC.getBinaryFunctions(); 259 if (opts::ReorderFunctions != RT_NONE && 260 opts::ReorderFunctions != RT_EXEC_COUNT && 261 opts::ReorderFunctions != RT_USER) { 262 Cg = buildCallGraph(BC, 263 [](const BinaryFunction &BF) { 264 if (!BF.hasProfile()) 265 return true; 266 if (BF.getState() != BinaryFunction::State::CFG) 267 return true; 268 return false; 269 }, 270 opts::CgFromPerfData, 271 false, // IncludeColdCalls 272 opts::ReorderFunctionsUseHotSize, 273 opts::CgUseSplitHotSize, 274 opts::UseEdgeCounts, 275 opts::CgIgnoreRecursiveCalls); 276 Cg.normalizeArcWeights(); 277 } 278 279 std::vector<Cluster> Clusters; 280 281 switch (opts::ReorderFunctions) { 282 case RT_NONE: 283 break; 284 case RT_EXEC_COUNT: 285 { 286 std::vector<BinaryFunction *> SortedFunctions(BFs.size()); 287 uint32_t Index = 0; 288 std::transform(BFs.begin(), 289 BFs.end(), 290 SortedFunctions.begin(), 291 [](std::pair<const uint64_t, BinaryFunction> &BFI) { 292 return &BFI.second; 293 }); 294 std::stable_sort(SortedFunctions.begin(), SortedFunctions.end(), 295 [&](const BinaryFunction *A, const BinaryFunction *B) { 296 if (A->isIgnored()) 297 return false; 298 const size_t PadA = opts::padFunction(*A); 299 const size_t PadB = opts::padFunction(*B); 300 if (!PadA || !PadB) { 301 if (PadA) 302 return true; 303 if (PadB) 304 return false; 305 } 306 return !A->hasProfile() && 307 (B->hasProfile() || 308 (A->getExecutionCount() > B->getExecutionCount())); 309 }); 310 for (BinaryFunction *BF : SortedFunctions) 311 if (BF->hasProfile()) 312 BF->setIndex(Index++); 313 } 314 break; 315 case RT_HFSORT: 316 Clusters = clusterize(Cg); 317 break; 318 case RT_HFSORT_PLUS: 319 Clusters = hfsortPlus(Cg); 320 break; 321 case RT_PETTIS_HANSEN: 322 Clusters = pettisAndHansen(Cg); 323 break; 324 case RT_RANDOM: 325 std::srand(opts::RandomSeed); 326 Clusters = randomClusters(Cg); 327 break; 328 case RT_USER: 329 { 330 uint32_t Index = 0; 331 for (const std::string &Function : readFunctionOrderFile()) { 332 std::vector<uint64_t> FuncAddrs; 333 334 BinaryData *BD = BC.getBinaryDataByName(Function); 335 if (!BD) { 336 uint32_t LocalID = 1; 337 while(1) { 338 // If we can't find the main symbol name, look for alternates. 339 const std::string FuncName = 340 Function + "/" + std::to_string(LocalID); 341 BD = BC.getBinaryDataByName(FuncName); 342 if (BD) 343 FuncAddrs.push_back(BD->getAddress()); 344 else 345 break; 346 LocalID++; 347 } 348 } else { 349 FuncAddrs.push_back(BD->getAddress()); 350 } 351 352 if (FuncAddrs.empty()) { 353 errs() << "BOLT-WARNING: Reorder functions: can't find function for " 354 << Function << ".\n"; 355 continue; 356 } 357 358 for (const uint64_t FuncAddr : FuncAddrs) { 359 const BinaryData *FuncBD = BC.getBinaryDataAtAddress(FuncAddr); 360 assert(FuncBD); 361 362 BinaryFunction *BF = BC.getFunctionForSymbol(FuncBD->getSymbol()); 363 if (!BF) { 364 errs() << "BOLT-WARNING: Reorder functions: can't find function for " 365 << Function << ".\n"; 366 break; 367 } 368 if (!BF->hasValidIndex()) 369 BF->setIndex(Index++); 370 else if (opts::Verbosity > 0) 371 errs() << "BOLT-WARNING: Duplicate reorder entry for " << Function 372 << ".\n"; 373 } 374 } 375 } 376 break; 377 } 378 379 reorder(std::move(Clusters), BFs); 380 381 std::unique_ptr<std::ofstream> FuncsFile; 382 if (!opts::GenerateFunctionOrderFile.empty()) { 383 FuncsFile = std::make_unique<std::ofstream>(opts::GenerateFunctionOrderFile, 384 std::ios::out); 385 if (!FuncsFile) { 386 errs() << "BOLT-ERROR: ordered functions file " 387 << opts::GenerateFunctionOrderFile << " cannot be opened\n"; 388 exit(1); 389 } 390 } 391 392 std::unique_ptr<std::ofstream> LinkSectionsFile; 393 if (!opts::LinkSectionsFile.empty()) { 394 LinkSectionsFile = 395 std::make_unique<std::ofstream>(opts::LinkSectionsFile, std::ios::out); 396 if (!LinkSectionsFile) { 397 errs() << "BOLT-ERROR: link sections file " << opts::LinkSectionsFile 398 << " cannot be opened\n"; 399 exit(1); 400 } 401 } 402 403 if (FuncsFile || LinkSectionsFile) { 404 std::vector<BinaryFunction *> SortedFunctions(BFs.size()); 405 std::transform(BFs.begin(), BFs.end(), SortedFunctions.begin(), 406 [](std::pair<const uint64_t, BinaryFunction> &BFI) { 407 return &BFI.second; 408 }); 409 410 // Sort functions by index. 411 std::stable_sort( 412 SortedFunctions.begin(), 413 SortedFunctions.end(), 414 [](const BinaryFunction *A, const BinaryFunction *B) { 415 if (A->hasValidIndex() && B->hasValidIndex()) 416 return A->getIndex() < B->getIndex(); 417 if (A->hasValidIndex() && !B->hasValidIndex()) 418 return true; 419 if (!A->hasValidIndex() && B->hasValidIndex()) 420 return false; 421 return A->getAddress() < B->getAddress(); 422 }); 423 424 for (const BinaryFunction *Func : SortedFunctions) { 425 if (!Func->hasValidIndex()) 426 break; 427 if (Func->isPLTFunction()) 428 continue; 429 430 if (FuncsFile) 431 *FuncsFile << Func->getOneName().str() << '\n'; 432 433 if (LinkSectionsFile) { 434 const char *Indent = ""; 435 std::vector<StringRef> AllNames = Func->getNames(); 436 std::sort(AllNames.begin(), AllNames.end()); 437 for (StringRef Name : AllNames) { 438 const size_t SlashPos = Name.find('/'); 439 if (SlashPos != std::string::npos) { 440 // Avoid duplicates for local functions. 441 if (Name.find('/', SlashPos + 1) != std::string::npos) 442 continue; 443 Name = Name.substr(0, SlashPos); 444 } 445 *LinkSectionsFile << Indent << ".text." << Name.str() << '\n'; 446 Indent = " "; 447 } 448 } 449 } 450 451 if (FuncsFile) { 452 FuncsFile->close(); 453 outs() << "BOLT-INFO: dumped function order to " 454 << opts::GenerateFunctionOrderFile << '\n'; 455 } 456 457 if (LinkSectionsFile) { 458 LinkSectionsFile->close(); 459 outs() << "BOLT-INFO: dumped linker section order to " 460 << opts::LinkSectionsFile << '\n'; 461 } 462 } 463 } 464 465 } // namespace bolt 466 } // namespace llvm 467