1 //===- bolt/Passes/BinaryPasses.cpp - Binary-level passes -----------------===// 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 multiple passes for binary optimization and analysis. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "bolt/Passes/BinaryPasses.h" 14 #include "bolt/Core/FunctionLayout.h" 15 #include "bolt/Core/ParallelUtilities.h" 16 #include "bolt/Passes/ReorderAlgorithm.h" 17 #include "bolt/Passes/ReorderFunctions.h" 18 #include "bolt/Utils/CommandLineOpts.h" 19 #include "llvm/Support/CommandLine.h" 20 #include <atomic> 21 #include <mutex> 22 #include <numeric> 23 #include <vector> 24 25 #define DEBUG_TYPE "bolt-opts" 26 27 using namespace llvm; 28 using namespace bolt; 29 30 static const char *dynoStatsOptName(const bolt::DynoStats::Category C) { 31 assert(C > bolt::DynoStats::FIRST_DYNO_STAT && 32 C < DynoStats::LAST_DYNO_STAT && "Unexpected dyno stat category."); 33 34 static std::string OptNames[bolt::DynoStats::LAST_DYNO_STAT + 1]; 35 36 OptNames[C] = bolt::DynoStats::Description(C); 37 38 std::replace(OptNames[C].begin(), OptNames[C].end(), ' ', '-'); 39 40 return OptNames[C].c_str(); 41 } 42 43 namespace opts { 44 45 extern cl::OptionCategory BoltCategory; 46 extern cl::OptionCategory BoltOptCategory; 47 48 extern cl::opt<unsigned> Verbosity; 49 extern cl::opt<bool> EnableBAT; 50 extern cl::opt<unsigned> ExecutionCountThreshold; 51 extern cl::opt<bool> UpdateDebugSections; 52 extern cl::opt<bolt::ReorderFunctions::ReorderType> ReorderFunctions; 53 54 enum DynoStatsSortOrder : char { 55 Ascending, 56 Descending 57 }; 58 59 static cl::opt<DynoStatsSortOrder> DynoStatsSortOrderOpt( 60 "print-sorted-by-order", 61 cl::desc("use ascending or descending order when printing functions " 62 "ordered by dyno stats"), 63 cl::init(DynoStatsSortOrder::Descending), cl::cat(BoltOptCategory)); 64 65 cl::list<std::string> 66 HotTextMoveSections("hot-text-move-sections", 67 cl::desc("list of sections containing functions used for hugifying hot text. " 68 "BOLT makes sure these functions are not placed on the same page as " 69 "the hot text. (default=\'.stub,.mover\')."), 70 cl::value_desc("sec1,sec2,sec3,..."), 71 cl::CommaSeparated, 72 cl::ZeroOrMore, 73 cl::cat(BoltCategory)); 74 75 bool isHotTextMover(const BinaryFunction &Function) { 76 for (std::string &SectionName : opts::HotTextMoveSections) { 77 if (Function.getOriginSectionName() && 78 *Function.getOriginSectionName() == SectionName) 79 return true; 80 } 81 82 return false; 83 } 84 85 static cl::opt<bool> MinBranchClusters( 86 "min-branch-clusters", 87 cl::desc("use a modified clustering algorithm geared towards minimizing " 88 "branches"), 89 cl::Hidden, cl::cat(BoltOptCategory)); 90 91 static cl::list<Peepholes::PeepholeOpts> Peepholes( 92 "peepholes", cl::CommaSeparated, cl::desc("enable peephole optimizations"), 93 cl::value_desc("opt1,opt2,opt3,..."), 94 cl::values(clEnumValN(Peepholes::PEEP_NONE, "none", "disable peepholes"), 95 clEnumValN(Peepholes::PEEP_DOUBLE_JUMPS, "double-jumps", 96 "remove double jumps when able"), 97 clEnumValN(Peepholes::PEEP_TAILCALL_TRAPS, "tailcall-traps", 98 "insert tail call traps"), 99 clEnumValN(Peepholes::PEEP_USELESS_BRANCHES, "useless-branches", 100 "remove useless conditional branches"), 101 clEnumValN(Peepholes::PEEP_ALL, "all", 102 "enable all peephole optimizations")), 103 cl::ZeroOrMore, cl::cat(BoltOptCategory)); 104 105 static cl::opt<unsigned> 106 PrintFuncStat("print-function-statistics", 107 cl::desc("print statistics about basic block ordering"), 108 cl::init(0), cl::cat(BoltOptCategory)); 109 110 static cl::opt<bool> PrintLargeFunctions( 111 "print-large-functions", 112 cl::desc("print functions that could not be overwritten due to excessive " 113 "size"), 114 cl::init(false), cl::cat(BoltOptCategory)); 115 116 static cl::list<bolt::DynoStats::Category> 117 PrintSortedBy("print-sorted-by", cl::CommaSeparated, 118 cl::desc("print functions sorted by order of dyno stats"), 119 cl::value_desc("key1,key2,key3,..."), 120 cl::values( 121 #define D(name, description, ...) \ 122 clEnumValN(bolt::DynoStats::name, dynoStatsOptName(bolt::DynoStats::name), \ 123 description), 124 REAL_DYNO_STATS 125 #undef D 126 clEnumValN(bolt::DynoStats::LAST_DYNO_STAT, "all", 127 "sorted by all names")), 128 cl::ZeroOrMore, cl::cat(BoltOptCategory)); 129 130 static cl::opt<bool> 131 PrintUnknown("print-unknown", 132 cl::desc("print names of functions with unknown control flow"), 133 cl::cat(BoltCategory), cl::Hidden); 134 135 static cl::opt<bool> 136 PrintUnknownCFG("print-unknown-cfg", 137 cl::desc("dump CFG of functions with unknown control flow"), 138 cl::cat(BoltCategory), cl::ReallyHidden); 139 140 // Please MSVC19 with a forward declaration: otherwise it reports an error about 141 // an undeclared variable inside a callback. 142 extern cl::opt<bolt::ReorderBasicBlocks::LayoutType> ReorderBlocks; 143 cl::opt<bolt::ReorderBasicBlocks::LayoutType> ReorderBlocks( 144 "reorder-blocks", cl::desc("change layout of basic blocks in a function"), 145 cl::init(bolt::ReorderBasicBlocks::LT_NONE), 146 cl::values( 147 clEnumValN(bolt::ReorderBasicBlocks::LT_NONE, "none", 148 "do not reorder basic blocks"), 149 clEnumValN(bolt::ReorderBasicBlocks::LT_REVERSE, "reverse", 150 "layout blocks in reverse order"), 151 clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE, "normal", 152 "perform optimal layout based on profile"), 153 clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_BRANCH, 154 "branch-predictor", 155 "perform optimal layout prioritizing branch " 156 "predictions"), 157 clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_CACHE, "cache", 158 "perform optimal layout prioritizing I-cache " 159 "behavior"), 160 clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_CACHE_PLUS, "cache+", 161 "perform layout optimizing I-cache behavior"), 162 clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_EXT_TSP, "ext-tsp", 163 "perform layout optimizing I-cache behavior"), 164 clEnumValN(bolt::ReorderBasicBlocks::LT_OPTIMIZE_SHUFFLE, 165 "cluster-shuffle", "perform random layout of clusters")), 166 cl::ZeroOrMore, cl::cat(BoltOptCategory), 167 cl::callback([](const bolt::ReorderBasicBlocks::LayoutType &option) { 168 if (option == bolt::ReorderBasicBlocks::LT_OPTIMIZE_CACHE_PLUS) { 169 errs() << "BOLT-WARNING: '-reorder-blocks=cache+' is deprecated, please" 170 << " use '-reorder-blocks=ext-tsp' instead\n"; 171 ReorderBlocks = bolt::ReorderBasicBlocks::LT_OPTIMIZE_EXT_TSP; 172 } 173 })); 174 175 static cl::opt<unsigned> ReportBadLayout( 176 "report-bad-layout", 177 cl::desc("print top <uint> functions with suboptimal code layout on input"), 178 cl::init(0), cl::Hidden, cl::cat(BoltOptCategory)); 179 180 static cl::opt<bool> 181 ReportStaleFuncs("report-stale", 182 cl::desc("print the list of functions with stale profile"), 183 cl::Hidden, cl::cat(BoltOptCategory)); 184 185 enum SctcModes : char { 186 SctcAlways, 187 SctcPreserveDirection, 188 SctcHeuristic 189 }; 190 191 static cl::opt<SctcModes> 192 SctcMode("sctc-mode", 193 cl::desc("mode for simplify conditional tail calls"), 194 cl::init(SctcAlways), 195 cl::values(clEnumValN(SctcAlways, "always", "always perform sctc"), 196 clEnumValN(SctcPreserveDirection, 197 "preserve", 198 "only perform sctc when branch direction is " 199 "preserved"), 200 clEnumValN(SctcHeuristic, 201 "heuristic", 202 "use branch prediction data to control sctc")), 203 cl::ZeroOrMore, 204 cl::cat(BoltOptCategory)); 205 206 static cl::opt<unsigned> 207 StaleThreshold("stale-threshold", 208 cl::desc( 209 "maximum percentage of stale functions to tolerate (default: 100)"), 210 cl::init(100), 211 cl::Hidden, 212 cl::cat(BoltOptCategory)); 213 214 static cl::opt<unsigned> TSPThreshold( 215 "tsp-threshold", 216 cl::desc( 217 "maximum number of hot basic blocks in a function for which to use " 218 "a precise TSP solution while re-ordering basic blocks"), 219 cl::init(10), cl::Hidden, cl::cat(BoltOptCategory)); 220 221 static cl::opt<unsigned> TopCalledLimit( 222 "top-called-limit", 223 cl::desc("maximum number of functions to print in top called " 224 "functions section"), 225 cl::init(100), cl::Hidden, cl::cat(BoltCategory)); 226 227 // Profile density options, synced with llvm-profgen/ProfileGenerator.cpp 228 static cl::opt<int> ProfileDensityCutOffHot( 229 "profile-density-cutoff-hot", cl::init(990000), 230 cl::desc("Total samples cutoff for functions used to calculate " 231 "profile density.")); 232 233 static cl::opt<double> ProfileDensityThreshold( 234 "profile-density-threshold", cl::init(60), 235 cl::desc("If the profile density is below the given threshold, it " 236 "will be suggested to increase the sampling rate."), 237 cl::Optional); 238 239 } // namespace opts 240 241 namespace llvm { 242 namespace bolt { 243 244 bool BinaryFunctionPass::shouldOptimize(const BinaryFunction &BF) const { 245 return BF.isSimple() && BF.getState() == BinaryFunction::State::CFG && 246 !BF.isIgnored(); 247 } 248 249 bool BinaryFunctionPass::shouldPrint(const BinaryFunction &BF) const { 250 return BF.isSimple() && !BF.isIgnored(); 251 } 252 253 void NormalizeCFG::runOnFunction(BinaryFunction &BF) { 254 uint64_t NumRemoved = 0; 255 uint64_t NumDuplicateEdges = 0; 256 uint64_t NeedsFixBranches = 0; 257 for (BinaryBasicBlock &BB : BF) { 258 if (!BB.empty()) 259 continue; 260 261 if (BB.isEntryPoint() || BB.isLandingPad()) 262 continue; 263 264 // Handle a dangling empty block. 265 if (BB.succ_size() == 0) { 266 // If an empty dangling basic block has a predecessor, it could be a 267 // result of codegen for __builtin_unreachable. In such case, do not 268 // remove the block. 269 if (BB.pred_size() == 0) { 270 BB.markValid(false); 271 ++NumRemoved; 272 } 273 continue; 274 } 275 276 // The block should have just one successor. 277 BinaryBasicBlock *Successor = BB.getSuccessor(); 278 assert(Successor && "invalid CFG encountered"); 279 280 // Redirect all predecessors to the successor block. 281 while (!BB.pred_empty()) { 282 BinaryBasicBlock *Predecessor = *BB.pred_begin(); 283 if (Predecessor->hasJumpTable()) 284 break; 285 286 if (Predecessor == Successor) 287 break; 288 289 BinaryBasicBlock::BinaryBranchInfo &BI = Predecessor->getBranchInfo(BB); 290 Predecessor->replaceSuccessor(&BB, Successor, BI.Count, 291 BI.MispredictedCount); 292 // We need to fix branches even if we failed to replace all successors 293 // and remove the block. 294 NeedsFixBranches = true; 295 } 296 297 if (BB.pred_empty()) { 298 BB.removeAllSuccessors(); 299 BB.markValid(false); 300 ++NumRemoved; 301 } 302 } 303 304 if (NumRemoved) 305 BF.eraseInvalidBBs(); 306 307 // Check for duplicate successors. Do it after the empty block elimination as 308 // we can get more duplicate successors. 309 for (BinaryBasicBlock &BB : BF) 310 if (!BB.hasJumpTable() && BB.succ_size() == 2 && 311 BB.getConditionalSuccessor(false) == BB.getConditionalSuccessor(true)) 312 ++NumDuplicateEdges; 313 314 // fixBranches() will get rid of duplicate edges and update jump instructions. 315 if (NumDuplicateEdges || NeedsFixBranches) 316 BF.fixBranches(); 317 318 NumDuplicateEdgesMerged += NumDuplicateEdges; 319 NumBlocksRemoved += NumRemoved; 320 } 321 322 Error NormalizeCFG::runOnFunctions(BinaryContext &BC) { 323 ParallelUtilities::runOnEachFunction( 324 BC, ParallelUtilities::SchedulingPolicy::SP_BB_LINEAR, 325 [&](BinaryFunction &BF) { runOnFunction(BF); }, 326 [&](const BinaryFunction &BF) { return !shouldOptimize(BF); }, 327 "NormalizeCFG"); 328 if (NumBlocksRemoved) 329 BC.outs() << "BOLT-INFO: removed " << NumBlocksRemoved << " empty block" 330 << (NumBlocksRemoved == 1 ? "" : "s") << '\n'; 331 if (NumDuplicateEdgesMerged) 332 BC.outs() << "BOLT-INFO: merged " << NumDuplicateEdgesMerged 333 << " duplicate CFG edge" 334 << (NumDuplicateEdgesMerged == 1 ? "" : "s") << '\n'; 335 return Error::success(); 336 } 337 338 void EliminateUnreachableBlocks::runOnFunction(BinaryFunction &Function) { 339 BinaryContext &BC = Function.getBinaryContext(); 340 unsigned Count; 341 uint64_t Bytes; 342 Function.markUnreachableBlocks(); 343 LLVM_DEBUG({ 344 for (BinaryBasicBlock &BB : Function) { 345 if (!BB.isValid()) { 346 dbgs() << "BOLT-INFO: UCE found unreachable block " << BB.getName() 347 << " in function " << Function << "\n"; 348 Function.dump(); 349 } 350 } 351 }); 352 BinaryContext::IndependentCodeEmitter Emitter = 353 BC.createIndependentMCCodeEmitter(); 354 std::tie(Count, Bytes) = Function.eraseInvalidBBs(Emitter.MCE.get()); 355 DeletedBlocks += Count; 356 DeletedBytes += Bytes; 357 if (Count) { 358 auto L = BC.scopeLock(); 359 Modified.insert(&Function); 360 if (opts::Verbosity > 0) 361 BC.outs() << "BOLT-INFO: removed " << Count 362 << " dead basic block(s) accounting for " << Bytes 363 << " bytes in function " << Function << '\n'; 364 } 365 } 366 367 Error EliminateUnreachableBlocks::runOnFunctions(BinaryContext &BC) { 368 ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) { 369 runOnFunction(BF); 370 }; 371 372 ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) { 373 return !shouldOptimize(BF) || BF.getLayout().block_empty(); 374 }; 375 376 ParallelUtilities::runOnEachFunction( 377 BC, ParallelUtilities::SchedulingPolicy::SP_CONSTANT, WorkFun, 378 SkipPredicate, "elimininate-unreachable"); 379 380 if (DeletedBlocks) 381 BC.outs() << "BOLT-INFO: UCE removed " << DeletedBlocks << " blocks and " 382 << DeletedBytes << " bytes of code\n"; 383 return Error::success(); 384 } 385 386 bool ReorderBasicBlocks::shouldPrint(const BinaryFunction &BF) const { 387 return (BinaryFunctionPass::shouldPrint(BF) && 388 opts::ReorderBlocks != ReorderBasicBlocks::LT_NONE); 389 } 390 391 bool ReorderBasicBlocks::shouldOptimize(const BinaryFunction &BF) const { 392 // Apply execution count threshold 393 if (BF.getKnownExecutionCount() < opts::ExecutionCountThreshold) 394 return false; 395 396 return BinaryFunctionPass::shouldOptimize(BF); 397 } 398 399 Error ReorderBasicBlocks::runOnFunctions(BinaryContext &BC) { 400 if (opts::ReorderBlocks == ReorderBasicBlocks::LT_NONE) 401 return Error::success(); 402 403 std::atomic_uint64_t ModifiedFuncCount(0); 404 std::mutex FunctionEditDistanceMutex; 405 DenseMap<const BinaryFunction *, uint64_t> FunctionEditDistance; 406 407 ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) { 408 SmallVector<const BinaryBasicBlock *, 0> OldBlockOrder; 409 if (opts::PrintFuncStat > 0) 410 llvm::copy(BF.getLayout().blocks(), std::back_inserter(OldBlockOrder)); 411 412 const bool LayoutChanged = 413 modifyFunctionLayout(BF, opts::ReorderBlocks, opts::MinBranchClusters); 414 if (LayoutChanged) { 415 ModifiedFuncCount.fetch_add(1, std::memory_order_relaxed); 416 if (opts::PrintFuncStat > 0) { 417 const uint64_t Distance = BF.getLayout().getEditDistance(OldBlockOrder); 418 std::lock_guard<std::mutex> Lock(FunctionEditDistanceMutex); 419 FunctionEditDistance[&BF] = Distance; 420 } 421 } 422 }; 423 424 ParallelUtilities::PredicateTy SkipFunc = [&](const BinaryFunction &BF) { 425 return !shouldOptimize(BF); 426 }; 427 428 ParallelUtilities::runOnEachFunction( 429 BC, ParallelUtilities::SchedulingPolicy::SP_BB_LINEAR, WorkFun, SkipFunc, 430 "ReorderBasicBlocks"); 431 const size_t NumAllProfiledFunctions = 432 BC.NumProfiledFuncs + BC.NumStaleProfileFuncs; 433 434 BC.outs() << "BOLT-INFO: basic block reordering modified layout of " 435 << format( 436 "%zu functions (%.2lf%% of profiled, %.2lf%% of total)\n", 437 ModifiedFuncCount.load(std::memory_order_relaxed), 438 100.0 * ModifiedFuncCount.load(std::memory_order_relaxed) / 439 NumAllProfiledFunctions, 440 100.0 * ModifiedFuncCount.load(std::memory_order_relaxed) / 441 BC.getBinaryFunctions().size()); 442 443 if (opts::PrintFuncStat > 0) { 444 raw_ostream &OS = BC.outs(); 445 // Copy all the values into vector in order to sort them 446 std::map<uint64_t, BinaryFunction &> ScoreMap; 447 auto &BFs = BC.getBinaryFunctions(); 448 for (auto It = BFs.begin(); It != BFs.end(); ++It) 449 ScoreMap.insert(std::pair<uint64_t, BinaryFunction &>( 450 It->second.getFunctionScore(), It->second)); 451 452 OS << "\nBOLT-INFO: Printing Function Statistics:\n\n"; 453 OS << " There are " << BFs.size() << " functions in total. \n"; 454 OS << " Number of functions being modified: " 455 << ModifiedFuncCount.load(std::memory_order_relaxed) << "\n"; 456 OS << " User asks for detailed information on top " 457 << opts::PrintFuncStat << " functions. (Ranked by function score)" 458 << "\n\n"; 459 uint64_t I = 0; 460 for (std::map<uint64_t, BinaryFunction &>::reverse_iterator Rit = 461 ScoreMap.rbegin(); 462 Rit != ScoreMap.rend() && I < opts::PrintFuncStat; ++Rit, ++I) { 463 BinaryFunction &Function = Rit->second; 464 465 OS << " Information for function of top: " << (I + 1) << ": \n"; 466 OS << " Function Score is: " << Function.getFunctionScore() 467 << "\n"; 468 OS << " There are " << Function.size() 469 << " number of blocks in this function.\n"; 470 OS << " There are " << Function.getInstructionCount() 471 << " number of instructions in this function.\n"; 472 OS << " The edit distance for this function is: " 473 << FunctionEditDistance.lookup(&Function) << "\n\n"; 474 } 475 } 476 return Error::success(); 477 } 478 479 bool ReorderBasicBlocks::modifyFunctionLayout(BinaryFunction &BF, 480 LayoutType Type, 481 bool MinBranchClusters) const { 482 if (BF.size() == 0 || Type == LT_NONE) 483 return false; 484 485 BinaryFunction::BasicBlockOrderType NewLayout; 486 std::unique_ptr<ReorderAlgorithm> Algo; 487 488 // Cannot do optimal layout without profile. 489 if (Type != LT_REVERSE && !BF.hasValidProfile()) 490 return false; 491 492 if (Type == LT_REVERSE) { 493 Algo.reset(new ReverseReorderAlgorithm()); 494 } else if (BF.size() <= opts::TSPThreshold && Type != LT_OPTIMIZE_SHUFFLE) { 495 // Work on optimal solution if problem is small enough 496 LLVM_DEBUG(dbgs() << "finding optimal block layout for " << BF << "\n"); 497 Algo.reset(new TSPReorderAlgorithm()); 498 } else { 499 LLVM_DEBUG(dbgs() << "running block layout heuristics on " << BF << "\n"); 500 501 std::unique_ptr<ClusterAlgorithm> CAlgo; 502 if (MinBranchClusters) 503 CAlgo.reset(new MinBranchGreedyClusterAlgorithm()); 504 else 505 CAlgo.reset(new PHGreedyClusterAlgorithm()); 506 507 switch (Type) { 508 case LT_OPTIMIZE: 509 Algo.reset(new OptimizeReorderAlgorithm(std::move(CAlgo))); 510 break; 511 512 case LT_OPTIMIZE_BRANCH: 513 Algo.reset(new OptimizeBranchReorderAlgorithm(std::move(CAlgo))); 514 break; 515 516 case LT_OPTIMIZE_CACHE: 517 Algo.reset(new OptimizeCacheReorderAlgorithm(std::move(CAlgo))); 518 break; 519 520 case LT_OPTIMIZE_EXT_TSP: 521 Algo.reset(new ExtTSPReorderAlgorithm()); 522 break; 523 524 case LT_OPTIMIZE_SHUFFLE: 525 Algo.reset(new RandomClusterReorderAlgorithm(std::move(CAlgo))); 526 break; 527 528 default: 529 llvm_unreachable("unexpected layout type"); 530 } 531 } 532 533 Algo->reorderBasicBlocks(BF, NewLayout); 534 535 return BF.getLayout().update(NewLayout); 536 } 537 538 Error FixupBranches::runOnFunctions(BinaryContext &BC) { 539 for (auto &It : BC.getBinaryFunctions()) { 540 BinaryFunction &Function = It.second; 541 if (!BC.shouldEmit(Function) || !Function.isSimple()) 542 continue; 543 544 Function.fixBranches(); 545 } 546 return Error::success(); 547 } 548 549 Error FinalizeFunctions::runOnFunctions(BinaryContext &BC) { 550 std::atomic<bool> HasFatal{false}; 551 ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) { 552 if (!BF.finalizeCFIState()) { 553 if (BC.HasRelocations) { 554 BC.errs() << "BOLT-ERROR: unable to fix CFI state for function " << BF 555 << ". Exiting.\n"; 556 HasFatal = true; 557 return; 558 } 559 BF.setSimple(false); 560 return; 561 } 562 563 BF.setFinalized(); 564 565 // Update exception handling information. 566 BF.updateEHRanges(); 567 }; 568 569 ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) { 570 return !BC.shouldEmit(BF); 571 }; 572 573 ParallelUtilities::runOnEachFunction( 574 BC, ParallelUtilities::SchedulingPolicy::SP_CONSTANT, WorkFun, 575 SkipPredicate, "FinalizeFunctions"); 576 if (HasFatal) 577 return createFatalBOLTError("finalize CFI state failure"); 578 return Error::success(); 579 } 580 581 Error CheckLargeFunctions::runOnFunctions(BinaryContext &BC) { 582 if (BC.HasRelocations) 583 return Error::success(); 584 585 // If the function wouldn't fit, mark it as non-simple. Otherwise, we may emit 586 // incorrect meta data. 587 ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) { 588 uint64_t HotSize, ColdSize; 589 std::tie(HotSize, ColdSize) = 590 BC.calculateEmittedSize(BF, /*FixBranches=*/false); 591 if (HotSize > BF.getMaxSize()) { 592 if (opts::PrintLargeFunctions) 593 BC.outs() << "BOLT-INFO: " << BF << " size exceeds allocated space by " 594 << (HotSize - BF.getMaxSize()) << " bytes\n"; 595 BF.setSimple(false); 596 } 597 }; 598 599 ParallelUtilities::PredicateTy SkipFunc = [&](const BinaryFunction &BF) { 600 return !shouldOptimize(BF); 601 }; 602 603 ParallelUtilities::runOnEachFunction( 604 BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun, 605 SkipFunc, "CheckLargeFunctions"); 606 607 return Error::success(); 608 } 609 610 bool CheckLargeFunctions::shouldOptimize(const BinaryFunction &BF) const { 611 // Unlike other passes, allow functions in non-CFG state. 612 return BF.isSimple() && !BF.isIgnored(); 613 } 614 615 Error LowerAnnotations::runOnFunctions(BinaryContext &BC) { 616 // Convert GnuArgsSize annotations into CFIs. 617 for (BinaryFunction *BF : BC.getAllBinaryFunctions()) { 618 for (FunctionFragment &FF : BF->getLayout().fragments()) { 619 // Reset at the start of the new fragment. 620 int64_t CurrentGnuArgsSize = 0; 621 622 for (BinaryBasicBlock *const BB : FF) { 623 for (auto II = BB->begin(); II != BB->end(); ++II) { 624 if (!BF->usesGnuArgsSize() || !BC.MIB->isInvoke(*II)) 625 continue; 626 627 const int64_t NewGnuArgsSize = BC.MIB->getGnuArgsSize(*II); 628 assert(NewGnuArgsSize >= 0 && "Expected non-negative GNU_args_size."); 629 if (NewGnuArgsSize == CurrentGnuArgsSize) 630 continue; 631 632 auto InsertII = BF->addCFIInstruction( 633 BB, II, 634 MCCFIInstruction::createGnuArgsSize(nullptr, NewGnuArgsSize)); 635 CurrentGnuArgsSize = NewGnuArgsSize; 636 II = std::next(InsertII); 637 } 638 } 639 } 640 } 641 return Error::success(); 642 } 643 644 // Check for dirty state in MCSymbol objects that might be a consequence 645 // of running calculateEmittedSize() in parallel, during split functions 646 // pass. If an inconsistent state is found (symbol already registered or 647 // already defined), clean it. 648 Error CleanMCState::runOnFunctions(BinaryContext &BC) { 649 MCContext &Ctx = *BC.Ctx; 650 for (const auto &SymMapEntry : Ctx.getSymbols()) { 651 const MCSymbol *S = SymMapEntry.getValue().Symbol; 652 if (!S) 653 continue; 654 if (S->isDefined()) { 655 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Symbol \"" << S->getName() 656 << "\" is already defined\n"); 657 const_cast<MCSymbol *>(S)->setUndefined(); 658 } 659 if (S->isRegistered()) { 660 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Symbol \"" << S->getName() 661 << "\" is already registered\n"); 662 const_cast<MCSymbol *>(S)->setIsRegistered(false); 663 } 664 LLVM_DEBUG(if (S->isVariable()) { 665 dbgs() << "BOLT-DEBUG: Symbol \"" << S->getName() << "\" is variable\n"; 666 }); 667 } 668 return Error::success(); 669 } 670 671 // This peephole fixes jump instructions that jump to another basic 672 // block with a single jump instruction, e.g. 673 // 674 // B0: ... 675 // jmp B1 (or jcc B1) 676 // 677 // B1: jmp B2 678 // 679 // -> 680 // 681 // B0: ... 682 // jmp B2 (or jcc B2) 683 // 684 static uint64_t fixDoubleJumps(BinaryFunction &Function, bool MarkInvalid) { 685 uint64_t NumDoubleJumps = 0; 686 687 MCContext *Ctx = Function.getBinaryContext().Ctx.get(); 688 MCPlusBuilder *MIB = Function.getBinaryContext().MIB.get(); 689 for (BinaryBasicBlock &BB : Function) { 690 auto checkAndPatch = [&](BinaryBasicBlock *Pred, BinaryBasicBlock *Succ, 691 const MCSymbol *SuccSym, 692 std::optional<uint32_t> Offset) { 693 // Ignore infinite loop jumps or fallthrough tail jumps. 694 if (Pred == Succ || Succ == &BB) 695 return false; 696 697 if (Succ) { 698 const MCSymbol *TBB = nullptr; 699 const MCSymbol *FBB = nullptr; 700 MCInst *CondBranch = nullptr; 701 MCInst *UncondBranch = nullptr; 702 bool Res = Pred->analyzeBranch(TBB, FBB, CondBranch, UncondBranch); 703 if (!Res) { 704 LLVM_DEBUG(dbgs() << "analyzeBranch failed in peepholes in block:\n"; 705 Pred->dump()); 706 return false; 707 } 708 Pred->replaceSuccessor(&BB, Succ); 709 710 // We must patch up any existing branch instructions to match up 711 // with the new successor. 712 assert((CondBranch || (!CondBranch && Pred->succ_size() == 1)) && 713 "Predecessor block has inconsistent number of successors"); 714 if (CondBranch && MIB->getTargetSymbol(*CondBranch) == BB.getLabel()) { 715 MIB->replaceBranchTarget(*CondBranch, Succ->getLabel(), Ctx); 716 } else if (UncondBranch && 717 MIB->getTargetSymbol(*UncondBranch) == BB.getLabel()) { 718 MIB->replaceBranchTarget(*UncondBranch, Succ->getLabel(), Ctx); 719 } else if (!UncondBranch) { 720 assert(Function.getLayout().getBasicBlockAfter(Pred, false) != Succ && 721 "Don't add an explicit jump to a fallthrough block."); 722 Pred->addBranchInstruction(Succ); 723 } 724 } else { 725 // Succ will be null in the tail call case. In this case we 726 // need to explicitly add a tail call instruction. 727 MCInst *Branch = Pred->getLastNonPseudoInstr(); 728 if (Branch && MIB->isUnconditionalBranch(*Branch)) { 729 assert(MIB->getTargetSymbol(*Branch) == BB.getLabel()); 730 Pred->removeSuccessor(&BB); 731 Pred->eraseInstruction(Pred->findInstruction(Branch)); 732 Pred->addTailCallInstruction(SuccSym); 733 if (Offset) { 734 MCInst *TailCall = Pred->getLastNonPseudoInstr(); 735 assert(TailCall); 736 MIB->setOffset(*TailCall, *Offset); 737 } 738 } else { 739 return false; 740 } 741 } 742 743 ++NumDoubleJumps; 744 LLVM_DEBUG(dbgs() << "Removed double jump in " << Function << " from " 745 << Pred->getName() << " -> " << BB.getName() << " to " 746 << Pred->getName() << " -> " << SuccSym->getName() 747 << (!Succ ? " (tail)\n" : "\n")); 748 749 return true; 750 }; 751 752 if (BB.getNumNonPseudos() != 1 || BB.isLandingPad()) 753 continue; 754 755 MCInst *Inst = BB.getFirstNonPseudoInstr(); 756 const bool IsTailCall = MIB->isTailCall(*Inst); 757 758 if (!MIB->isUnconditionalBranch(*Inst) && !IsTailCall) 759 continue; 760 761 // If we operate after SCTC make sure it's not a conditional tail call. 762 if (IsTailCall && MIB->isConditionalBranch(*Inst)) 763 continue; 764 765 const MCSymbol *SuccSym = MIB->getTargetSymbol(*Inst); 766 BinaryBasicBlock *Succ = BB.getSuccessor(); 767 768 if (((!Succ || &BB == Succ) && !IsTailCall) || (IsTailCall && !SuccSym)) 769 continue; 770 771 std::vector<BinaryBasicBlock *> Preds = {BB.pred_begin(), BB.pred_end()}; 772 773 for (BinaryBasicBlock *Pred : Preds) { 774 if (Pred->isLandingPad()) 775 continue; 776 777 if (Pred->getSuccessor() == &BB || 778 (Pred->getConditionalSuccessor(true) == &BB && !IsTailCall) || 779 Pred->getConditionalSuccessor(false) == &BB) 780 if (checkAndPatch(Pred, Succ, SuccSym, MIB->getOffset(*Inst)) && 781 MarkInvalid) 782 BB.markValid(BB.pred_size() != 0 || BB.isLandingPad() || 783 BB.isEntryPoint()); 784 } 785 } 786 787 return NumDoubleJumps; 788 } 789 790 bool SimplifyConditionalTailCalls::shouldRewriteBranch( 791 const BinaryBasicBlock *PredBB, const MCInst &CondBranch, 792 const BinaryBasicBlock *BB, const bool DirectionFlag) { 793 if (BeenOptimized.count(PredBB)) 794 return false; 795 796 const bool IsForward = BinaryFunction::isForwardBranch(PredBB, BB); 797 798 if (IsForward) 799 ++NumOrigForwardBranches; 800 else 801 ++NumOrigBackwardBranches; 802 803 if (opts::SctcMode == opts::SctcAlways) 804 return true; 805 806 if (opts::SctcMode == opts::SctcPreserveDirection) 807 return IsForward == DirectionFlag; 808 809 const ErrorOr<std::pair<double, double>> Frequency = 810 PredBB->getBranchStats(BB); 811 812 // It's ok to rewrite the conditional branch if the new target will be 813 // a backward branch. 814 815 // If no data available for these branches, then it should be ok to 816 // do the optimization since it will reduce code size. 817 if (Frequency.getError()) 818 return true; 819 820 // TODO: should this use misprediction frequency instead? 821 const bool Result = (IsForward && Frequency.get().first >= 0.5) || 822 (!IsForward && Frequency.get().first <= 0.5); 823 824 return Result == DirectionFlag; 825 } 826 827 uint64_t SimplifyConditionalTailCalls::fixTailCalls(BinaryFunction &BF) { 828 // Need updated indices to correctly detect branch' direction. 829 BF.getLayout().updateLayoutIndices(); 830 BF.markUnreachableBlocks(); 831 832 MCPlusBuilder *MIB = BF.getBinaryContext().MIB.get(); 833 MCContext *Ctx = BF.getBinaryContext().Ctx.get(); 834 uint64_t NumLocalCTCCandidates = 0; 835 uint64_t NumLocalCTCs = 0; 836 uint64_t LocalCTCTakenCount = 0; 837 uint64_t LocalCTCExecCount = 0; 838 std::vector<std::pair<BinaryBasicBlock *, const BinaryBasicBlock *>> 839 NeedsUncondBranch; 840 841 // Will block be deleted by UCE? 842 auto isValid = [](const BinaryBasicBlock *BB) { 843 return (BB->pred_size() != 0 || BB->isLandingPad() || BB->isEntryPoint()); 844 }; 845 846 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) { 847 // Locate BB with a single direct tail-call instruction. 848 if (BB->getNumNonPseudos() != 1) 849 continue; 850 851 MCInst *Instr = BB->getFirstNonPseudoInstr(); 852 if (!MIB->isTailCall(*Instr) || MIB->isConditionalBranch(*Instr)) 853 continue; 854 855 const MCSymbol *CalleeSymbol = MIB->getTargetSymbol(*Instr); 856 if (!CalleeSymbol) 857 continue; 858 859 // Detect direction of the possible conditional tail call. 860 const bool IsForwardCTC = BF.isForwardCall(CalleeSymbol); 861 862 // Iterate through all predecessors. 863 for (BinaryBasicBlock *PredBB : BB->predecessors()) { 864 BinaryBasicBlock *CondSucc = PredBB->getConditionalSuccessor(true); 865 if (!CondSucc) 866 continue; 867 868 ++NumLocalCTCCandidates; 869 870 const MCSymbol *TBB = nullptr; 871 const MCSymbol *FBB = nullptr; 872 MCInst *CondBranch = nullptr; 873 MCInst *UncondBranch = nullptr; 874 bool Result = PredBB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch); 875 876 // analyzeBranch() can fail due to unusual branch instructions, e.g. jrcxz 877 if (!Result) { 878 LLVM_DEBUG(dbgs() << "analyzeBranch failed in SCTC in block:\n"; 879 PredBB->dump()); 880 continue; 881 } 882 883 assert(Result && "internal error analyzing conditional branch"); 884 assert(CondBranch && "conditional branch expected"); 885 886 // Skip dynamic branches for now. 887 if (BF.getBinaryContext().MIB->isDynamicBranch(*CondBranch)) 888 continue; 889 890 // It's possible that PredBB is also a successor to BB that may have 891 // been processed by a previous iteration of the SCTC loop, in which 892 // case it may have been marked invalid. We should skip rewriting in 893 // this case. 894 if (!PredBB->isValid()) { 895 assert(PredBB->isSuccessor(BB) && 896 "PredBB should be valid if it is not a successor to BB"); 897 continue; 898 } 899 900 // We don't want to reverse direction of the branch in new order 901 // without further profile analysis. 902 const bool DirectionFlag = CondSucc == BB ? IsForwardCTC : !IsForwardCTC; 903 if (!shouldRewriteBranch(PredBB, *CondBranch, BB, DirectionFlag)) 904 continue; 905 906 // Record this block so that we don't try to optimize it twice. 907 BeenOptimized.insert(PredBB); 908 909 uint64_t Count = 0; 910 if (CondSucc != BB) { 911 // Patch the new target address into the conditional branch. 912 MIB->reverseBranchCondition(*CondBranch, CalleeSymbol, Ctx); 913 // Since we reversed the condition on the branch we need to change 914 // the target for the unconditional branch or add a unconditional 915 // branch to the old target. This has to be done manually since 916 // fixupBranches is not called after SCTC. 917 NeedsUncondBranch.emplace_back(PredBB, CondSucc); 918 Count = PredBB->getFallthroughBranchInfo().Count; 919 } else { 920 // Change destination of the conditional branch. 921 MIB->replaceBranchTarget(*CondBranch, CalleeSymbol, Ctx); 922 Count = PredBB->getTakenBranchInfo().Count; 923 } 924 const uint64_t CTCTakenFreq = 925 Count == BinaryBasicBlock::COUNT_NO_PROFILE ? 0 : Count; 926 927 // Annotate it, so "isCall" returns true for this jcc 928 MIB->setConditionalTailCall(*CondBranch); 929 // Add info about the conditional tail call frequency, otherwise this 930 // info will be lost when we delete the associated BranchInfo entry 931 auto &CTCAnnotation = 932 MIB->getOrCreateAnnotationAs<uint64_t>(*CondBranch, "CTCTakenCount"); 933 CTCAnnotation = CTCTakenFreq; 934 // Preserve Offset annotation, used in BAT. 935 // Instr is a direct tail call instruction that was created when CTCs are 936 // first expanded, and has the original CTC offset set. 937 if (std::optional<uint32_t> Offset = MIB->getOffset(*Instr)) 938 MIB->setOffset(*CondBranch, *Offset); 939 940 // Remove the unused successor which may be eliminated later 941 // if there are no other users. 942 PredBB->removeSuccessor(BB); 943 // Update BB execution count 944 if (CTCTakenFreq && CTCTakenFreq <= BB->getKnownExecutionCount()) 945 BB->setExecutionCount(BB->getExecutionCount() - CTCTakenFreq); 946 else if (CTCTakenFreq > BB->getKnownExecutionCount()) 947 BB->setExecutionCount(0); 948 949 ++NumLocalCTCs; 950 LocalCTCTakenCount += CTCTakenFreq; 951 LocalCTCExecCount += PredBB->getKnownExecutionCount(); 952 } 953 954 // Remove the block from CFG if all predecessors were removed. 955 BB->markValid(isValid(BB)); 956 } 957 958 // Add unconditional branches at the end of BBs to new successors 959 // as long as the successor is not a fallthrough. 960 for (auto &Entry : NeedsUncondBranch) { 961 BinaryBasicBlock *PredBB = Entry.first; 962 const BinaryBasicBlock *CondSucc = Entry.second; 963 964 const MCSymbol *TBB = nullptr; 965 const MCSymbol *FBB = nullptr; 966 MCInst *CondBranch = nullptr; 967 MCInst *UncondBranch = nullptr; 968 PredBB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch); 969 970 // Find the next valid block. Invalid blocks will be deleted 971 // so they shouldn't be considered fallthrough targets. 972 const BinaryBasicBlock *NextBlock = 973 BF.getLayout().getBasicBlockAfter(PredBB, false); 974 while (NextBlock && !isValid(NextBlock)) 975 NextBlock = BF.getLayout().getBasicBlockAfter(NextBlock, false); 976 977 // Get the unconditional successor to this block. 978 const BinaryBasicBlock *PredSucc = PredBB->getSuccessor(); 979 assert(PredSucc && "The other branch should be a tail call"); 980 981 const bool HasFallthrough = (NextBlock && PredSucc == NextBlock); 982 983 if (UncondBranch) { 984 if (HasFallthrough) 985 PredBB->eraseInstruction(PredBB->findInstruction(UncondBranch)); 986 else 987 MIB->replaceBranchTarget(*UncondBranch, CondSucc->getLabel(), Ctx); 988 } else if (!HasFallthrough) { 989 MCInst Branch; 990 MIB->createUncondBranch(Branch, CondSucc->getLabel(), Ctx); 991 PredBB->addInstruction(Branch); 992 } 993 } 994 995 if (NumLocalCTCs > 0) { 996 NumDoubleJumps += fixDoubleJumps(BF, true); 997 // Clean-up unreachable tail-call blocks. 998 const std::pair<unsigned, uint64_t> Stats = BF.eraseInvalidBBs(); 999 DeletedBlocks += Stats.first; 1000 DeletedBytes += Stats.second; 1001 1002 assert(BF.validateCFG()); 1003 } 1004 1005 LLVM_DEBUG(dbgs() << "BOLT: created " << NumLocalCTCs 1006 << " conditional tail calls from a total of " 1007 << NumLocalCTCCandidates << " candidates in function " << BF 1008 << ". CTCs execution count for this function is " 1009 << LocalCTCExecCount << " and CTC taken count is " 1010 << LocalCTCTakenCount << "\n";); 1011 1012 NumTailCallsPatched += NumLocalCTCs; 1013 NumCandidateTailCalls += NumLocalCTCCandidates; 1014 CTCExecCount += LocalCTCExecCount; 1015 CTCTakenCount += LocalCTCTakenCount; 1016 1017 return NumLocalCTCs > 0; 1018 } 1019 1020 Error SimplifyConditionalTailCalls::runOnFunctions(BinaryContext &BC) { 1021 if (!BC.isX86()) 1022 return Error::success(); 1023 1024 for (auto &It : BC.getBinaryFunctions()) { 1025 BinaryFunction &Function = It.second; 1026 1027 if (!shouldOptimize(Function)) 1028 continue; 1029 1030 if (fixTailCalls(Function)) { 1031 Modified.insert(&Function); 1032 Function.setHasCanonicalCFG(false); 1033 } 1034 } 1035 1036 if (NumTailCallsPatched) 1037 BC.outs() << "BOLT-INFO: SCTC: patched " << NumTailCallsPatched 1038 << " tail calls (" << NumOrigForwardBranches << " forward)" 1039 << " tail calls (" << NumOrigBackwardBranches << " backward)" 1040 << " from a total of " << NumCandidateTailCalls 1041 << " while removing " << NumDoubleJumps << " double jumps" 1042 << " and removing " << DeletedBlocks << " basic blocks" 1043 << " totalling " << DeletedBytes 1044 << " bytes of code. CTCs total execution count is " 1045 << CTCExecCount << " and the number of times CTCs are taken is " 1046 << CTCTakenCount << "\n"; 1047 return Error::success(); 1048 } 1049 1050 uint64_t ShortenInstructions::shortenInstructions(BinaryFunction &Function) { 1051 uint64_t Count = 0; 1052 const BinaryContext &BC = Function.getBinaryContext(); 1053 for (BinaryBasicBlock &BB : Function) { 1054 for (MCInst &Inst : BB) { 1055 // Skip shortening instructions with Size annotation. 1056 if (BC.MIB->getSize(Inst)) 1057 continue; 1058 1059 MCInst OriginalInst; 1060 if (opts::Verbosity > 2) 1061 OriginalInst = Inst; 1062 1063 if (!BC.MIB->shortenInstruction(Inst, *BC.STI)) 1064 continue; 1065 1066 if (opts::Verbosity > 2) { 1067 BC.scopeLock(); 1068 BC.outs() << "BOLT-INFO: shortening:\nBOLT-INFO: "; 1069 BC.printInstruction(BC.outs(), OriginalInst, 0, &Function); 1070 BC.outs() << "BOLT-INFO: to:"; 1071 BC.printInstruction(BC.outs(), Inst, 0, &Function); 1072 } 1073 1074 ++Count; 1075 } 1076 } 1077 1078 return Count; 1079 } 1080 1081 Error ShortenInstructions::runOnFunctions(BinaryContext &BC) { 1082 std::atomic<uint64_t> NumShortened{0}; 1083 if (!BC.isX86()) 1084 return Error::success(); 1085 1086 ParallelUtilities::runOnEachFunction( 1087 BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, 1088 [&](BinaryFunction &BF) { NumShortened += shortenInstructions(BF); }, 1089 nullptr, "ShortenInstructions"); 1090 1091 if (NumShortened) 1092 BC.outs() << "BOLT-INFO: " << NumShortened 1093 << " instructions were shortened\n"; 1094 return Error::success(); 1095 } 1096 1097 void Peepholes::addTailcallTraps(BinaryFunction &Function) { 1098 MCPlusBuilder *MIB = Function.getBinaryContext().MIB.get(); 1099 for (BinaryBasicBlock &BB : Function) { 1100 MCInst *Inst = BB.getLastNonPseudoInstr(); 1101 if (Inst && MIB->isTailCall(*Inst) && MIB->isIndirectBranch(*Inst)) { 1102 MCInst Trap; 1103 MIB->createTrap(Trap); 1104 BB.addInstruction(Trap); 1105 ++TailCallTraps; 1106 } 1107 } 1108 } 1109 1110 void Peepholes::removeUselessCondBranches(BinaryFunction &Function) { 1111 for (BinaryBasicBlock &BB : Function) { 1112 if (BB.succ_size() != 2) 1113 continue; 1114 1115 BinaryBasicBlock *CondBB = BB.getConditionalSuccessor(true); 1116 BinaryBasicBlock *UncondBB = BB.getConditionalSuccessor(false); 1117 if (CondBB != UncondBB) 1118 continue; 1119 1120 const MCSymbol *TBB = nullptr; 1121 const MCSymbol *FBB = nullptr; 1122 MCInst *CondBranch = nullptr; 1123 MCInst *UncondBranch = nullptr; 1124 bool Result = BB.analyzeBranch(TBB, FBB, CondBranch, UncondBranch); 1125 1126 // analyzeBranch() can fail due to unusual branch instructions, 1127 // e.g. jrcxz, or jump tables (indirect jump). 1128 if (!Result || !CondBranch) 1129 continue; 1130 1131 BB.removeDuplicateConditionalSuccessor(CondBranch); 1132 ++NumUselessCondBranches; 1133 } 1134 } 1135 1136 Error Peepholes::runOnFunctions(BinaryContext &BC) { 1137 const char Opts = 1138 std::accumulate(opts::Peepholes.begin(), opts::Peepholes.end(), 0, 1139 [](const char A, const PeepholeOpts B) { return A | B; }); 1140 if (Opts == PEEP_NONE) 1141 return Error::success(); 1142 1143 for (auto &It : BC.getBinaryFunctions()) { 1144 BinaryFunction &Function = It.second; 1145 if (shouldOptimize(Function)) { 1146 if (Opts & PEEP_DOUBLE_JUMPS) 1147 NumDoubleJumps += fixDoubleJumps(Function, false); 1148 if (Opts & PEEP_TAILCALL_TRAPS) 1149 addTailcallTraps(Function); 1150 if (Opts & PEEP_USELESS_BRANCHES) 1151 removeUselessCondBranches(Function); 1152 assert(Function.validateCFG()); 1153 } 1154 } 1155 BC.outs() << "BOLT-INFO: Peephole: " << NumDoubleJumps 1156 << " double jumps patched.\n" 1157 << "BOLT-INFO: Peephole: " << TailCallTraps 1158 << " tail call traps inserted.\n" 1159 << "BOLT-INFO: Peephole: " << NumUselessCondBranches 1160 << " useless conditional branches removed.\n"; 1161 return Error::success(); 1162 } 1163 1164 bool SimplifyRODataLoads::simplifyRODataLoads(BinaryFunction &BF) { 1165 BinaryContext &BC = BF.getBinaryContext(); 1166 MCPlusBuilder *MIB = BC.MIB.get(); 1167 1168 uint64_t NumLocalLoadsSimplified = 0; 1169 uint64_t NumDynamicLocalLoadsSimplified = 0; 1170 uint64_t NumLocalLoadsFound = 0; 1171 uint64_t NumDynamicLocalLoadsFound = 0; 1172 1173 for (BinaryBasicBlock *BB : BF.getLayout().blocks()) { 1174 for (MCInst &Inst : *BB) { 1175 unsigned Opcode = Inst.getOpcode(); 1176 const MCInstrDesc &Desc = BC.MII->get(Opcode); 1177 1178 // Skip instructions that do not load from memory. 1179 if (!Desc.mayLoad()) 1180 continue; 1181 1182 // Try to statically evaluate the target memory address; 1183 uint64_t TargetAddress; 1184 1185 if (MIB->hasPCRelOperand(Inst)) { 1186 // Try to find the symbol that corresponds to the PC-relative operand. 1187 MCOperand *DispOpI = MIB->getMemOperandDisp(Inst); 1188 assert(DispOpI != Inst.end() && "expected PC-relative displacement"); 1189 assert(DispOpI->isExpr() && 1190 "found PC-relative with non-symbolic displacement"); 1191 1192 // Get displacement symbol. 1193 const MCSymbol *DisplSymbol; 1194 uint64_t DisplOffset; 1195 1196 std::tie(DisplSymbol, DisplOffset) = 1197 MIB->getTargetSymbolInfo(DispOpI->getExpr()); 1198 1199 if (!DisplSymbol) 1200 continue; 1201 1202 // Look up the symbol address in the global symbols map of the binary 1203 // context object. 1204 BinaryData *BD = BC.getBinaryDataByName(DisplSymbol->getName()); 1205 if (!BD) 1206 continue; 1207 TargetAddress = BD->getAddress() + DisplOffset; 1208 } else if (!MIB->evaluateMemOperandTarget(Inst, TargetAddress)) { 1209 continue; 1210 } 1211 1212 // Get the contents of the section containing the target address of the 1213 // memory operand. We are only interested in read-only sections. 1214 ErrorOr<BinarySection &> DataSection = 1215 BC.getSectionForAddress(TargetAddress); 1216 if (!DataSection || DataSection->isWritable()) 1217 continue; 1218 1219 if (BC.getRelocationAt(TargetAddress) || 1220 BC.getDynamicRelocationAt(TargetAddress)) 1221 continue; 1222 1223 uint32_t Offset = TargetAddress - DataSection->getAddress(); 1224 StringRef ConstantData = DataSection->getContents(); 1225 1226 ++NumLocalLoadsFound; 1227 if (BB->hasProfile()) 1228 NumDynamicLocalLoadsFound += BB->getExecutionCount(); 1229 1230 if (MIB->replaceMemOperandWithImm(Inst, ConstantData, Offset)) { 1231 ++NumLocalLoadsSimplified; 1232 if (BB->hasProfile()) 1233 NumDynamicLocalLoadsSimplified += BB->getExecutionCount(); 1234 } 1235 } 1236 } 1237 1238 NumLoadsFound += NumLocalLoadsFound; 1239 NumDynamicLoadsFound += NumDynamicLocalLoadsFound; 1240 NumLoadsSimplified += NumLocalLoadsSimplified; 1241 NumDynamicLoadsSimplified += NumDynamicLocalLoadsSimplified; 1242 1243 return NumLocalLoadsSimplified > 0; 1244 } 1245 1246 Error SimplifyRODataLoads::runOnFunctions(BinaryContext &BC) { 1247 for (auto &It : BC.getBinaryFunctions()) { 1248 BinaryFunction &Function = It.second; 1249 if (shouldOptimize(Function) && simplifyRODataLoads(Function)) 1250 Modified.insert(&Function); 1251 } 1252 1253 BC.outs() << "BOLT-INFO: simplified " << NumLoadsSimplified << " out of " 1254 << NumLoadsFound << " loads from a statically computed address.\n" 1255 << "BOLT-INFO: dynamic loads simplified: " 1256 << NumDynamicLoadsSimplified << "\n" 1257 << "BOLT-INFO: dynamic loads found: " << NumDynamicLoadsFound 1258 << "\n"; 1259 return Error::success(); 1260 } 1261 1262 Error AssignSections::runOnFunctions(BinaryContext &BC) { 1263 for (BinaryFunction *Function : BC.getInjectedBinaryFunctions()) { 1264 Function->setCodeSectionName(BC.getInjectedCodeSectionName()); 1265 Function->setColdCodeSectionName(BC.getInjectedColdCodeSectionName()); 1266 } 1267 1268 // In non-relocation mode functions have pre-assigned section names. 1269 if (!BC.HasRelocations) 1270 return Error::success(); 1271 1272 const bool UseColdSection = 1273 BC.NumProfiledFuncs > 0 || 1274 opts::ReorderFunctions == ReorderFunctions::RT_USER; 1275 for (auto &BFI : BC.getBinaryFunctions()) { 1276 BinaryFunction &Function = BFI.second; 1277 if (opts::isHotTextMover(Function)) { 1278 Function.setCodeSectionName(BC.getHotTextMoverSectionName()); 1279 Function.setColdCodeSectionName(BC.getHotTextMoverSectionName()); 1280 continue; 1281 } 1282 1283 if (!UseColdSection || Function.hasValidIndex()) 1284 Function.setCodeSectionName(BC.getMainCodeSectionName()); 1285 else 1286 Function.setCodeSectionName(BC.getColdCodeSectionName()); 1287 1288 if (Function.isSplit()) 1289 Function.setColdCodeSectionName(BC.getColdCodeSectionName()); 1290 } 1291 return Error::success(); 1292 } 1293 1294 Error PrintProfileStats::runOnFunctions(BinaryContext &BC) { 1295 double FlowImbalanceMean = 0.0; 1296 size_t NumBlocksConsidered = 0; 1297 double WorstBias = 0.0; 1298 const BinaryFunction *WorstBiasFunc = nullptr; 1299 1300 // For each function CFG, we fill an IncomingMap with the sum of the frequency 1301 // of incoming edges for each BB. Likewise for each OutgoingMap and the sum 1302 // of the frequency of outgoing edges. 1303 using FlowMapTy = std::unordered_map<const BinaryBasicBlock *, uint64_t>; 1304 std::unordered_map<const BinaryFunction *, FlowMapTy> TotalIncomingMaps; 1305 std::unordered_map<const BinaryFunction *, FlowMapTy> TotalOutgoingMaps; 1306 1307 // Compute mean 1308 for (const auto &BFI : BC.getBinaryFunctions()) { 1309 const BinaryFunction &Function = BFI.second; 1310 if (Function.empty() || !Function.isSimple()) 1311 continue; 1312 FlowMapTy &IncomingMap = TotalIncomingMaps[&Function]; 1313 FlowMapTy &OutgoingMap = TotalOutgoingMaps[&Function]; 1314 for (const BinaryBasicBlock &BB : Function) { 1315 uint64_t TotalOutgoing = 0ULL; 1316 auto SuccBIIter = BB.branch_info_begin(); 1317 for (BinaryBasicBlock *Succ : BB.successors()) { 1318 uint64_t Count = SuccBIIter->Count; 1319 if (Count == BinaryBasicBlock::COUNT_NO_PROFILE || Count == 0) { 1320 ++SuccBIIter; 1321 continue; 1322 } 1323 TotalOutgoing += Count; 1324 IncomingMap[Succ] += Count; 1325 ++SuccBIIter; 1326 } 1327 OutgoingMap[&BB] = TotalOutgoing; 1328 } 1329 1330 size_t NumBlocks = 0; 1331 double Mean = 0.0; 1332 for (const BinaryBasicBlock &BB : Function) { 1333 // Do not compute score for low frequency blocks, entry or exit blocks 1334 if (IncomingMap[&BB] < 100 || OutgoingMap[&BB] == 0 || BB.isEntryPoint()) 1335 continue; 1336 ++NumBlocks; 1337 const double Difference = (double)OutgoingMap[&BB] - IncomingMap[&BB]; 1338 Mean += fabs(Difference / IncomingMap[&BB]); 1339 } 1340 1341 FlowImbalanceMean += Mean; 1342 NumBlocksConsidered += NumBlocks; 1343 if (!NumBlocks) 1344 continue; 1345 double FuncMean = Mean / NumBlocks; 1346 if (FuncMean > WorstBias) { 1347 WorstBias = FuncMean; 1348 WorstBiasFunc = &Function; 1349 } 1350 } 1351 if (NumBlocksConsidered > 0) 1352 FlowImbalanceMean /= NumBlocksConsidered; 1353 1354 // Compute standard deviation 1355 NumBlocksConsidered = 0; 1356 double FlowImbalanceVar = 0.0; 1357 for (const auto &BFI : BC.getBinaryFunctions()) { 1358 const BinaryFunction &Function = BFI.second; 1359 if (Function.empty() || !Function.isSimple()) 1360 continue; 1361 FlowMapTy &IncomingMap = TotalIncomingMaps[&Function]; 1362 FlowMapTy &OutgoingMap = TotalOutgoingMaps[&Function]; 1363 for (const BinaryBasicBlock &BB : Function) { 1364 if (IncomingMap[&BB] < 100 || OutgoingMap[&BB] == 0) 1365 continue; 1366 ++NumBlocksConsidered; 1367 const double Difference = (double)OutgoingMap[&BB] - IncomingMap[&BB]; 1368 FlowImbalanceVar += 1369 pow(fabs(Difference / IncomingMap[&BB]) - FlowImbalanceMean, 2); 1370 } 1371 } 1372 if (NumBlocksConsidered) { 1373 FlowImbalanceVar /= NumBlocksConsidered; 1374 FlowImbalanceVar = sqrt(FlowImbalanceVar); 1375 } 1376 1377 // Report to user 1378 BC.outs() << format("BOLT-INFO: Profile bias score: %.4lf%% StDev: %.4lf%%\n", 1379 (100.0 * FlowImbalanceMean), (100.0 * FlowImbalanceVar)); 1380 if (WorstBiasFunc && opts::Verbosity >= 1) { 1381 BC.outs() << "Worst average bias observed in " 1382 << WorstBiasFunc->getPrintName() << "\n"; 1383 LLVM_DEBUG(WorstBiasFunc->dump()); 1384 } 1385 return Error::success(); 1386 } 1387 1388 Error PrintProgramStats::runOnFunctions(BinaryContext &BC) { 1389 uint64_t NumRegularFunctions = 0; 1390 uint64_t NumStaleProfileFunctions = 0; 1391 uint64_t NumAllStaleFunctions = 0; 1392 uint64_t NumInferredFunctions = 0; 1393 uint64_t NumNonSimpleProfiledFunctions = 0; 1394 uint64_t NumUnknownControlFlowFunctions = 0; 1395 uint64_t TotalSampleCount = 0; 1396 uint64_t StaleSampleCount = 0; 1397 uint64_t InferredSampleCount = 0; 1398 std::vector<const BinaryFunction *> ProfiledFunctions; 1399 std::vector<std::pair<double, uint64_t>> FuncDensityList; 1400 const char *StaleFuncsHeader = "BOLT-INFO: Functions with stale profile:\n"; 1401 for (auto &BFI : BC.getBinaryFunctions()) { 1402 const BinaryFunction &Function = BFI.second; 1403 1404 // Ignore PLT functions for stats. 1405 if (Function.isPLTFunction()) 1406 continue; 1407 1408 // Adjustment for BAT mode: the profile for BOLT split fragments is combined 1409 // so only count the hot fragment. 1410 const uint64_t Address = Function.getAddress(); 1411 bool IsHotParentOfBOLTSplitFunction = !Function.getFragments().empty() && 1412 BAT && BAT->isBATFunction(Address) && 1413 !BAT->fetchParentAddress(Address); 1414 1415 ++NumRegularFunctions; 1416 1417 // In BOLTed binaries split functions are non-simple (due to non-relocation 1418 // mode), but the original function is known to be simple and we have a 1419 // valid profile for it. 1420 if (!Function.isSimple() && !IsHotParentOfBOLTSplitFunction) { 1421 if (Function.hasProfile()) 1422 ++NumNonSimpleProfiledFunctions; 1423 continue; 1424 } 1425 1426 if (Function.hasUnknownControlFlow()) { 1427 if (opts::PrintUnknownCFG) 1428 Function.dump(); 1429 else if (opts::PrintUnknown) 1430 BC.errs() << "function with unknown control flow: " << Function << '\n'; 1431 1432 ++NumUnknownControlFlowFunctions; 1433 } 1434 1435 if (!Function.hasProfile()) 1436 continue; 1437 1438 uint64_t SampleCount = Function.getRawBranchCount(); 1439 TotalSampleCount += SampleCount; 1440 1441 if (Function.hasValidProfile()) { 1442 ProfiledFunctions.push_back(&Function); 1443 if (Function.hasInferredProfile()) { 1444 ++NumInferredFunctions; 1445 InferredSampleCount += SampleCount; 1446 ++NumAllStaleFunctions; 1447 } 1448 } else { 1449 if (opts::ReportStaleFuncs) { 1450 BC.outs() << StaleFuncsHeader; 1451 StaleFuncsHeader = ""; 1452 BC.outs() << " " << Function << '\n'; 1453 } 1454 ++NumStaleProfileFunctions; 1455 StaleSampleCount += SampleCount; 1456 ++NumAllStaleFunctions; 1457 } 1458 1459 if (opts::ShowDensity) { 1460 uint64_t Size = Function.getSize(); 1461 // In case of BOLT split functions registered in BAT, executed traces are 1462 // automatically attributed to the main fragment. Add up function sizes 1463 // for all fragments. 1464 if (IsHotParentOfBOLTSplitFunction) 1465 for (const BinaryFunction *Fragment : Function.getFragments()) 1466 Size += Fragment->getSize(); 1467 double Density = (double)1.0 * Function.getSampleCountInBytes() / Size; 1468 FuncDensityList.emplace_back(Density, SampleCount); 1469 LLVM_DEBUG(BC.outs() << Function << ": executed bytes " 1470 << Function.getSampleCountInBytes() << ", size (b) " 1471 << Size << ", density " << Density 1472 << ", sample count " << SampleCount << '\n'); 1473 } 1474 } 1475 BC.NumProfiledFuncs = ProfiledFunctions.size(); 1476 BC.NumStaleProfileFuncs = NumStaleProfileFunctions; 1477 1478 const size_t NumAllProfiledFunctions = 1479 ProfiledFunctions.size() + NumStaleProfileFunctions; 1480 BC.outs() << "BOLT-INFO: " << NumAllProfiledFunctions << " out of " 1481 << NumRegularFunctions << " functions in the binary (" 1482 << format("%.1f", NumAllProfiledFunctions / 1483 (float)NumRegularFunctions * 100.0f) 1484 << "%) have non-empty execution profile\n"; 1485 if (NumNonSimpleProfiledFunctions) { 1486 BC.outs() << "BOLT-INFO: " << NumNonSimpleProfiledFunctions << " function" 1487 << (NumNonSimpleProfiledFunctions == 1 ? "" : "s") 1488 << " with profile could not be optimized\n"; 1489 } 1490 if (NumAllStaleFunctions) { 1491 const float PctStale = 1492 NumAllStaleFunctions / (float)NumAllProfiledFunctions * 100.0f; 1493 const float PctStaleFuncsWithEqualBlockCount = 1494 (float)BC.Stats.NumStaleFuncsWithEqualBlockCount / 1495 NumAllStaleFunctions * 100.0f; 1496 const float PctStaleBlocksWithEqualIcount = 1497 (float)BC.Stats.NumStaleBlocksWithEqualIcount / 1498 BC.Stats.NumStaleBlocks * 100.0f; 1499 auto printErrorOrWarning = [&]() { 1500 if (PctStale > opts::StaleThreshold) 1501 BC.errs() << "BOLT-ERROR: "; 1502 else 1503 BC.errs() << "BOLT-WARNING: "; 1504 }; 1505 printErrorOrWarning(); 1506 BC.errs() << NumAllStaleFunctions 1507 << format(" (%.1f%% of all profiled)", PctStale) << " function" 1508 << (NumAllStaleFunctions == 1 ? "" : "s") 1509 << " have invalid (possibly stale) profile." 1510 " Use -report-stale to see the list.\n"; 1511 if (TotalSampleCount > 0) { 1512 printErrorOrWarning(); 1513 BC.errs() << (StaleSampleCount + InferredSampleCount) << " out of " 1514 << TotalSampleCount << " samples in the binary (" 1515 << format("%.1f", 1516 ((100.0f * (StaleSampleCount + InferredSampleCount)) / 1517 TotalSampleCount)) 1518 << "%) belong to functions with invalid" 1519 " (possibly stale) profile.\n"; 1520 } 1521 BC.outs() << "BOLT-INFO: " << BC.Stats.NumStaleFuncsWithEqualBlockCount 1522 << " stale function" 1523 << (BC.Stats.NumStaleFuncsWithEqualBlockCount == 1 ? "" : "s") 1524 << format(" (%.1f%% of all stale)", 1525 PctStaleFuncsWithEqualBlockCount) 1526 << " have matching block count.\n"; 1527 BC.outs() << "BOLT-INFO: " << BC.Stats.NumStaleBlocksWithEqualIcount 1528 << " stale block" 1529 << (BC.Stats.NumStaleBlocksWithEqualIcount == 1 ? "" : "s") 1530 << format(" (%.1f%% of all stale)", PctStaleBlocksWithEqualIcount) 1531 << " have matching icount.\n"; 1532 if (PctStale > opts::StaleThreshold) { 1533 return createFatalBOLTError( 1534 Twine("BOLT-ERROR: stale functions exceed specified threshold of ") + 1535 Twine(opts::StaleThreshold.getValue()) + Twine("%. Exiting.\n")); 1536 } 1537 } 1538 if (NumInferredFunctions) { 1539 BC.outs() << format( 1540 "BOLT-INFO: inferred profile for %d (%.2f%% of profiled, " 1541 "%.2f%% of stale) functions responsible for %.2f%% samples" 1542 " (%zu out of %zu)\n", 1543 NumInferredFunctions, 1544 100.0 * NumInferredFunctions / NumAllProfiledFunctions, 1545 100.0 * NumInferredFunctions / NumAllStaleFunctions, 1546 100.0 * InferredSampleCount / TotalSampleCount, InferredSampleCount, 1547 TotalSampleCount); 1548 BC.outs() << format( 1549 "BOLT-INFO: inference found an exact match for %.2f%% of basic blocks" 1550 " (%zu out of %zu stale) responsible for %.2f%% samples" 1551 " (%zu out of %zu stale)\n", 1552 100.0 * BC.Stats.NumExactMatchedBlocks / BC.Stats.NumStaleBlocks, 1553 BC.Stats.NumExactMatchedBlocks, BC.Stats.NumStaleBlocks, 1554 100.0 * BC.Stats.ExactMatchedSampleCount / BC.Stats.StaleSampleCount, 1555 BC.Stats.ExactMatchedSampleCount, BC.Stats.StaleSampleCount); 1556 BC.outs() << format( 1557 "BOLT-INFO: inference found an exact pseudo probe match for %.2f%% of " 1558 "basic blocks (%zu out of %zu stale) responsible for %.2f%% samples" 1559 " (%zu out of %zu stale)\n", 1560 100.0 * BC.Stats.NumPseudoProbeExactMatchedBlocks / 1561 BC.Stats.NumStaleBlocks, 1562 BC.Stats.NumPseudoProbeExactMatchedBlocks, BC.Stats.NumStaleBlocks, 1563 100.0 * BC.Stats.PseudoProbeExactMatchedSampleCount / 1564 BC.Stats.StaleSampleCount, 1565 BC.Stats.PseudoProbeExactMatchedSampleCount, BC.Stats.StaleSampleCount); 1566 BC.outs() << format( 1567 "BOLT-INFO: inference found a loose pseudo probe match for %.2f%% of " 1568 "basic blocks (%zu out of %zu stale) responsible for %.2f%% samples" 1569 " (%zu out of %zu stale)\n", 1570 100.0 * BC.Stats.NumPseudoProbeLooseMatchedBlocks / 1571 BC.Stats.NumStaleBlocks, 1572 BC.Stats.NumPseudoProbeLooseMatchedBlocks, BC.Stats.NumStaleBlocks, 1573 100.0 * BC.Stats.PseudoProbeLooseMatchedSampleCount / 1574 BC.Stats.StaleSampleCount, 1575 BC.Stats.PseudoProbeLooseMatchedSampleCount, BC.Stats.StaleSampleCount); 1576 BC.outs() << format( 1577 "BOLT-INFO: inference found a call match for %.2f%% of basic " 1578 "blocks" 1579 " (%zu out of %zu stale) responsible for %.2f%% samples" 1580 " (%zu out of %zu stale)\n", 1581 100.0 * BC.Stats.NumCallMatchedBlocks / BC.Stats.NumStaleBlocks, 1582 BC.Stats.NumCallMatchedBlocks, BC.Stats.NumStaleBlocks, 1583 100.0 * BC.Stats.CallMatchedSampleCount / BC.Stats.StaleSampleCount, 1584 BC.Stats.CallMatchedSampleCount, BC.Stats.StaleSampleCount); 1585 BC.outs() << format( 1586 "BOLT-INFO: inference found a loose match for %.2f%% of basic " 1587 "blocks" 1588 " (%zu out of %zu stale) responsible for %.2f%% samples" 1589 " (%zu out of %zu stale)\n", 1590 100.0 * BC.Stats.NumLooseMatchedBlocks / BC.Stats.NumStaleBlocks, 1591 BC.Stats.NumLooseMatchedBlocks, BC.Stats.NumStaleBlocks, 1592 100.0 * BC.Stats.LooseMatchedSampleCount / BC.Stats.StaleSampleCount, 1593 BC.Stats.LooseMatchedSampleCount, BC.Stats.StaleSampleCount); 1594 } 1595 1596 if (const uint64_t NumUnusedObjects = BC.getNumUnusedProfiledObjects()) { 1597 BC.outs() << "BOLT-INFO: profile for " << NumUnusedObjects 1598 << " objects was ignored\n"; 1599 } 1600 1601 if (ProfiledFunctions.size() > 10) { 1602 if (opts::Verbosity >= 1) { 1603 BC.outs() << "BOLT-INFO: top called functions are:\n"; 1604 llvm::sort(ProfiledFunctions, 1605 [](const BinaryFunction *A, const BinaryFunction *B) { 1606 return B->getExecutionCount() < A->getExecutionCount(); 1607 }); 1608 auto SFI = ProfiledFunctions.begin(); 1609 auto SFIend = ProfiledFunctions.end(); 1610 for (unsigned I = 0u; I < opts::TopCalledLimit && SFI != SFIend; 1611 ++SFI, ++I) 1612 BC.outs() << " " << **SFI << " : " << (*SFI)->getExecutionCount() 1613 << '\n'; 1614 } 1615 } 1616 1617 if (!opts::PrintSortedBy.empty()) { 1618 std::vector<BinaryFunction *> Functions; 1619 std::map<const BinaryFunction *, DynoStats> Stats; 1620 1621 for (auto &BFI : BC.getBinaryFunctions()) { 1622 BinaryFunction &BF = BFI.second; 1623 if (shouldOptimize(BF) && BF.hasValidProfile()) { 1624 Functions.push_back(&BF); 1625 Stats.emplace(&BF, getDynoStats(BF)); 1626 } 1627 } 1628 1629 const bool SortAll = 1630 llvm::is_contained(opts::PrintSortedBy, DynoStats::LAST_DYNO_STAT); 1631 1632 const bool Ascending = 1633 opts::DynoStatsSortOrderOpt == opts::DynoStatsSortOrder::Ascending; 1634 1635 std::function<bool(const DynoStats &, const DynoStats &)> 1636 DynoStatsComparator = 1637 SortAll ? [](const DynoStats &StatsA, 1638 const DynoStats &StatsB) { return StatsA < StatsB; } 1639 : [](const DynoStats &StatsA, const DynoStats &StatsB) { 1640 return StatsA.lessThan(StatsB, opts::PrintSortedBy); 1641 }; 1642 1643 llvm::stable_sort(Functions, 1644 [Ascending, &Stats, DynoStatsComparator]( 1645 const BinaryFunction *A, const BinaryFunction *B) { 1646 auto StatsItr = Stats.find(A); 1647 assert(StatsItr != Stats.end()); 1648 const DynoStats &StatsA = StatsItr->second; 1649 1650 StatsItr = Stats.find(B); 1651 assert(StatsItr != Stats.end()); 1652 const DynoStats &StatsB = StatsItr->second; 1653 1654 return Ascending ? DynoStatsComparator(StatsA, StatsB) 1655 : DynoStatsComparator(StatsB, StatsA); 1656 }); 1657 1658 BC.outs() << "BOLT-INFO: top functions sorted by "; 1659 if (SortAll) { 1660 BC.outs() << "dyno stats"; 1661 } else { 1662 BC.outs() << "("; 1663 bool PrintComma = false; 1664 for (const DynoStats::Category Category : opts::PrintSortedBy) { 1665 if (PrintComma) 1666 BC.outs() << ", "; 1667 BC.outs() << DynoStats::Description(Category); 1668 PrintComma = true; 1669 } 1670 BC.outs() << ")"; 1671 } 1672 1673 BC.outs() << " are:\n"; 1674 auto SFI = Functions.begin(); 1675 for (unsigned I = 0; I < 100 && SFI != Functions.end(); ++SFI, ++I) { 1676 const DynoStats Stats = getDynoStats(**SFI); 1677 BC.outs() << " " << **SFI; 1678 if (!SortAll) { 1679 BC.outs() << " ("; 1680 bool PrintComma = false; 1681 for (const DynoStats::Category Category : opts::PrintSortedBy) { 1682 if (PrintComma) 1683 BC.outs() << ", "; 1684 BC.outs() << dynoStatsOptName(Category) << "=" << Stats[Category]; 1685 PrintComma = true; 1686 } 1687 BC.outs() << ")"; 1688 } 1689 BC.outs() << "\n"; 1690 } 1691 } 1692 1693 if (!BC.TrappedFunctions.empty()) { 1694 BC.errs() << "BOLT-WARNING: " << BC.TrappedFunctions.size() << " function" 1695 << (BC.TrappedFunctions.size() > 1 ? "s" : "") 1696 << " will trap on entry. Use -trap-avx512=0 to disable" 1697 " traps."; 1698 if (opts::Verbosity >= 1 || BC.TrappedFunctions.size() <= 5) { 1699 BC.errs() << '\n'; 1700 for (const BinaryFunction *Function : BC.TrappedFunctions) 1701 BC.errs() << " " << *Function << '\n'; 1702 } else { 1703 BC.errs() << " Use -v=1 to see the list.\n"; 1704 } 1705 } 1706 1707 // Collect and print information about suboptimal code layout on input. 1708 if (opts::ReportBadLayout) { 1709 std::vector<BinaryFunction *> SuboptimalFuncs; 1710 for (auto &BFI : BC.getBinaryFunctions()) { 1711 BinaryFunction &BF = BFI.second; 1712 if (!BF.hasValidProfile()) 1713 continue; 1714 1715 const uint64_t HotThreshold = 1716 std::max<uint64_t>(BF.getKnownExecutionCount(), 1); 1717 bool HotSeen = false; 1718 for (const BinaryBasicBlock *BB : BF.getLayout().rblocks()) { 1719 if (!HotSeen && BB->getKnownExecutionCount() > HotThreshold) { 1720 HotSeen = true; 1721 continue; 1722 } 1723 if (HotSeen && BB->getKnownExecutionCount() == 0) { 1724 SuboptimalFuncs.push_back(&BF); 1725 break; 1726 } 1727 } 1728 } 1729 1730 if (!SuboptimalFuncs.empty()) { 1731 llvm::sort(SuboptimalFuncs, 1732 [](const BinaryFunction *A, const BinaryFunction *B) { 1733 return A->getKnownExecutionCount() / A->getSize() > 1734 B->getKnownExecutionCount() / B->getSize(); 1735 }); 1736 1737 BC.outs() << "BOLT-INFO: " << SuboptimalFuncs.size() 1738 << " functions have " 1739 "cold code in the middle of hot code. Top functions are:\n"; 1740 for (unsigned I = 0; 1741 I < std::min(static_cast<size_t>(opts::ReportBadLayout), 1742 SuboptimalFuncs.size()); 1743 ++I) 1744 SuboptimalFuncs[I]->print(BC.outs()); 1745 } 1746 } 1747 1748 if (NumUnknownControlFlowFunctions) { 1749 BC.outs() << "BOLT-INFO: " << NumUnknownControlFlowFunctions 1750 << " functions have instructions with unknown control flow"; 1751 if (!opts::PrintUnknown) 1752 BC.outs() << ". Use -print-unknown to see the list."; 1753 BC.outs() << '\n'; 1754 } 1755 1756 if (opts::ShowDensity) { 1757 double Density = 0.0; 1758 // Sorted by the density in descending order. 1759 llvm::stable_sort(FuncDensityList, 1760 [&](const std::pair<double, uint64_t> &A, 1761 const std::pair<double, uint64_t> &B) { 1762 if (A.first != B.first) 1763 return A.first > B.first; 1764 return A.second < B.second; 1765 }); 1766 1767 uint64_t AccumulatedSamples = 0; 1768 uint32_t I = 0; 1769 assert(opts::ProfileDensityCutOffHot <= 1000000 && 1770 "The cutoff value is greater than 1000000(100%)"); 1771 while (AccumulatedSamples < 1772 TotalSampleCount * 1773 static_cast<float>(opts::ProfileDensityCutOffHot) / 1774 1000000 && 1775 I < FuncDensityList.size()) { 1776 AccumulatedSamples += FuncDensityList[I].second; 1777 Density = FuncDensityList[I].first; 1778 I++; 1779 } 1780 if (Density == 0.0) { 1781 BC.errs() << "BOLT-WARNING: the output profile is empty or the " 1782 "--profile-density-cutoff-hot option is " 1783 "set too low. Please check your command.\n"; 1784 } else if (Density < opts::ProfileDensityThreshold) { 1785 BC.errs() 1786 << "BOLT-WARNING: BOLT is estimated to optimize better with " 1787 << format("%.1f", opts::ProfileDensityThreshold / Density) 1788 << "x more samples. Please consider increasing sampling rate or " 1789 "profiling for longer duration to get more samples.\n"; 1790 } 1791 1792 BC.outs() << "BOLT-INFO: Functions with density >= " 1793 << format("%.1f", Density) << " account for " 1794 << format("%.2f", 1795 static_cast<double>(opts::ProfileDensityCutOffHot) / 1796 10000) 1797 << "% total sample counts.\n"; 1798 } 1799 return Error::success(); 1800 } 1801 1802 Error InstructionLowering::runOnFunctions(BinaryContext &BC) { 1803 for (auto &BFI : BC.getBinaryFunctions()) 1804 for (BinaryBasicBlock &BB : BFI.second) 1805 for (MCInst &Instruction : BB) 1806 BC.MIB->lowerTailCall(Instruction); 1807 return Error::success(); 1808 } 1809 1810 Error StripRepRet::runOnFunctions(BinaryContext &BC) { 1811 if (!BC.isX86()) 1812 return Error::success(); 1813 1814 uint64_t NumPrefixesRemoved = 0; 1815 uint64_t NumBytesSaved = 0; 1816 for (auto &BFI : BC.getBinaryFunctions()) { 1817 for (BinaryBasicBlock &BB : BFI.second) { 1818 auto LastInstRIter = BB.getLastNonPseudo(); 1819 if (LastInstRIter == BB.rend() || !BC.MIB->isReturn(*LastInstRIter) || 1820 !BC.MIB->deleteREPPrefix(*LastInstRIter)) 1821 continue; 1822 1823 NumPrefixesRemoved += BB.getKnownExecutionCount(); 1824 ++NumBytesSaved; 1825 } 1826 } 1827 1828 if (NumBytesSaved) 1829 BC.outs() << "BOLT-INFO: removed " << NumBytesSaved 1830 << " 'repz' prefixes" 1831 " with estimated execution count of " 1832 << NumPrefixesRemoved << " times.\n"; 1833 return Error::success(); 1834 } 1835 1836 Error InlineMemcpy::runOnFunctions(BinaryContext &BC) { 1837 if (!BC.isX86()) 1838 return Error::success(); 1839 1840 uint64_t NumInlined = 0; 1841 uint64_t NumInlinedDyno = 0; 1842 for (auto &BFI : BC.getBinaryFunctions()) { 1843 for (BinaryBasicBlock &BB : BFI.second) { 1844 for (auto II = BB.begin(); II != BB.end(); ++II) { 1845 MCInst &Inst = *II; 1846 1847 if (!BC.MIB->isCall(Inst) || MCPlus::getNumPrimeOperands(Inst) != 1 || 1848 !Inst.getOperand(0).isExpr()) 1849 continue; 1850 1851 const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(Inst); 1852 if (CalleeSymbol->getName() != "memcpy" && 1853 CalleeSymbol->getName() != "memcpy@PLT" && 1854 CalleeSymbol->getName() != "_memcpy8") 1855 continue; 1856 1857 const bool IsMemcpy8 = (CalleeSymbol->getName() == "_memcpy8"); 1858 const bool IsTailCall = BC.MIB->isTailCall(Inst); 1859 1860 const InstructionListType NewCode = 1861 BC.MIB->createInlineMemcpy(IsMemcpy8); 1862 II = BB.replaceInstruction(II, NewCode); 1863 std::advance(II, NewCode.size() - 1); 1864 if (IsTailCall) { 1865 MCInst Return; 1866 BC.MIB->createReturn(Return); 1867 II = BB.insertInstruction(std::next(II), std::move(Return)); 1868 } 1869 1870 ++NumInlined; 1871 NumInlinedDyno += BB.getKnownExecutionCount(); 1872 } 1873 } 1874 } 1875 1876 if (NumInlined) { 1877 BC.outs() << "BOLT-INFO: inlined " << NumInlined << " memcpy() calls"; 1878 if (NumInlinedDyno) 1879 BC.outs() << ". The calls were executed " << NumInlinedDyno 1880 << " times based on profile."; 1881 BC.outs() << '\n'; 1882 } 1883 return Error::success(); 1884 } 1885 1886 bool SpecializeMemcpy1::shouldOptimize(const BinaryFunction &Function) const { 1887 if (!BinaryFunctionPass::shouldOptimize(Function)) 1888 return false; 1889 1890 for (const std::string &FunctionSpec : Spec) { 1891 StringRef FunctionName = StringRef(FunctionSpec).split(':').first; 1892 if (Function.hasNameRegex(FunctionName)) 1893 return true; 1894 } 1895 1896 return false; 1897 } 1898 1899 std::set<size_t> SpecializeMemcpy1::getCallSitesToOptimize( 1900 const BinaryFunction &Function) const { 1901 StringRef SitesString; 1902 for (const std::string &FunctionSpec : Spec) { 1903 StringRef FunctionName; 1904 std::tie(FunctionName, SitesString) = StringRef(FunctionSpec).split(':'); 1905 if (Function.hasNameRegex(FunctionName)) 1906 break; 1907 SitesString = ""; 1908 } 1909 1910 std::set<size_t> Sites; 1911 SmallVector<StringRef, 4> SitesVec; 1912 SitesString.split(SitesVec, ':'); 1913 for (StringRef SiteString : SitesVec) { 1914 if (SiteString.empty()) 1915 continue; 1916 size_t Result; 1917 if (!SiteString.getAsInteger(10, Result)) 1918 Sites.emplace(Result); 1919 } 1920 1921 return Sites; 1922 } 1923 1924 Error SpecializeMemcpy1::runOnFunctions(BinaryContext &BC) { 1925 if (!BC.isX86()) 1926 return Error::success(); 1927 1928 uint64_t NumSpecialized = 0; 1929 uint64_t NumSpecializedDyno = 0; 1930 for (auto &BFI : BC.getBinaryFunctions()) { 1931 BinaryFunction &Function = BFI.second; 1932 if (!shouldOptimize(Function)) 1933 continue; 1934 1935 std::set<size_t> CallsToOptimize = getCallSitesToOptimize(Function); 1936 auto shouldOptimize = [&](size_t N) { 1937 return CallsToOptimize.empty() || CallsToOptimize.count(N); 1938 }; 1939 1940 std::vector<BinaryBasicBlock *> Blocks(Function.pbegin(), Function.pend()); 1941 size_t CallSiteID = 0; 1942 for (BinaryBasicBlock *CurBB : Blocks) { 1943 for (auto II = CurBB->begin(); II != CurBB->end(); ++II) { 1944 MCInst &Inst = *II; 1945 1946 if (!BC.MIB->isCall(Inst) || MCPlus::getNumPrimeOperands(Inst) != 1 || 1947 !Inst.getOperand(0).isExpr()) 1948 continue; 1949 1950 const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(Inst); 1951 if (CalleeSymbol->getName() != "memcpy" && 1952 CalleeSymbol->getName() != "memcpy@PLT") 1953 continue; 1954 1955 if (BC.MIB->isTailCall(Inst)) 1956 continue; 1957 1958 ++CallSiteID; 1959 1960 if (!shouldOptimize(CallSiteID)) 1961 continue; 1962 1963 // Create a copy of a call to memcpy(dest, src, size). 1964 MCInst MemcpyInstr = Inst; 1965 1966 BinaryBasicBlock *OneByteMemcpyBB = CurBB->splitAt(II); 1967 1968 BinaryBasicBlock *NextBB = nullptr; 1969 if (OneByteMemcpyBB->getNumNonPseudos() > 1) { 1970 NextBB = OneByteMemcpyBB->splitAt(OneByteMemcpyBB->begin()); 1971 NextBB->eraseInstruction(NextBB->begin()); 1972 } else { 1973 NextBB = OneByteMemcpyBB->getSuccessor(); 1974 OneByteMemcpyBB->eraseInstruction(OneByteMemcpyBB->begin()); 1975 assert(NextBB && "unexpected call to memcpy() with no return"); 1976 } 1977 1978 BinaryBasicBlock *MemcpyBB = Function.addBasicBlock(); 1979 MemcpyBB->setOffset(CurBB->getInputOffset()); 1980 InstructionListType CmpJCC = 1981 BC.MIB->createCmpJE(BC.MIB->getIntArgRegister(2), 1, 1982 OneByteMemcpyBB->getLabel(), BC.Ctx.get()); 1983 CurBB->addInstructions(CmpJCC); 1984 CurBB->addSuccessor(MemcpyBB); 1985 1986 MemcpyBB->addInstruction(std::move(MemcpyInstr)); 1987 MemcpyBB->addSuccessor(NextBB); 1988 MemcpyBB->setCFIState(NextBB->getCFIState()); 1989 MemcpyBB->setExecutionCount(0); 1990 1991 // To prevent the actual call from being moved to cold, we set its 1992 // execution count to 1. 1993 if (CurBB->getKnownExecutionCount() > 0) 1994 MemcpyBB->setExecutionCount(1); 1995 1996 InstructionListType OneByteMemcpy = BC.MIB->createOneByteMemcpy(); 1997 OneByteMemcpyBB->addInstructions(OneByteMemcpy); 1998 1999 ++NumSpecialized; 2000 NumSpecializedDyno += CurBB->getKnownExecutionCount(); 2001 2002 CurBB = NextBB; 2003 2004 // Note: we don't expect the next instruction to be a call to memcpy. 2005 II = CurBB->begin(); 2006 } 2007 } 2008 } 2009 2010 if (NumSpecialized) { 2011 BC.outs() << "BOLT-INFO: specialized " << NumSpecialized 2012 << " memcpy() call sites for size 1"; 2013 if (NumSpecializedDyno) 2014 BC.outs() << ". The calls were executed " << NumSpecializedDyno 2015 << " times based on profile."; 2016 BC.outs() << '\n'; 2017 } 2018 return Error::success(); 2019 } 2020 2021 void RemoveNops::runOnFunction(BinaryFunction &BF) { 2022 const BinaryContext &BC = BF.getBinaryContext(); 2023 for (BinaryBasicBlock &BB : BF) { 2024 for (int64_t I = BB.size() - 1; I >= 0; --I) { 2025 MCInst &Inst = BB.getInstructionAtIndex(I); 2026 if (BC.MIB->isNoop(Inst) && BC.MIB->hasAnnotation(Inst, "NOP")) 2027 BB.eraseInstructionAtIndex(I); 2028 } 2029 } 2030 } 2031 2032 Error RemoveNops::runOnFunctions(BinaryContext &BC) { 2033 ParallelUtilities::WorkFuncTy WorkFun = [&](BinaryFunction &BF) { 2034 runOnFunction(BF); 2035 }; 2036 2037 ParallelUtilities::PredicateTy SkipFunc = [&](const BinaryFunction &BF) { 2038 return BF.shouldPreserveNops(); 2039 }; 2040 2041 ParallelUtilities::runOnEachFunction( 2042 BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun, 2043 SkipFunc, "RemoveNops"); 2044 return Error::success(); 2045 } 2046 2047 } // namespace bolt 2048 } // namespace llvm 2049