1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===// 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 the BinaryFunction class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "bolt/Core/BinaryFunction.h" 14 #include "bolt/Core/BinaryBasicBlock.h" 15 #include "bolt/Core/BinaryDomTree.h" 16 #include "bolt/Core/DynoStats.h" 17 #include "bolt/Core/HashUtilities.h" 18 #include "bolt/Core/MCPlusBuilder.h" 19 #include "bolt/Utils/NameResolver.h" 20 #include "bolt/Utils/NameShortener.h" 21 #include "bolt/Utils/Utils.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallSet.h" 24 #include "llvm/ADT/StringExtras.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Demangle/Demangle.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCAsmLayout.h" 29 #include "llvm/MC/MCContext.h" 30 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 31 #include "llvm/MC/MCExpr.h" 32 #include "llvm/MC/MCInst.h" 33 #include "llvm/MC/MCInstPrinter.h" 34 #include "llvm/MC/MCRegisterInfo.h" 35 #include "llvm/MC/MCSymbol.h" 36 #include "llvm/Object/ObjectFile.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/GraphWriter.h" 40 #include "llvm/Support/LEB128.h" 41 #include "llvm/Support/Regex.h" 42 #include "llvm/Support/Timer.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include <functional> 45 #include <limits> 46 #include <numeric> 47 #include <string> 48 49 #define DEBUG_TYPE "bolt" 50 51 using namespace llvm; 52 using namespace bolt; 53 54 namespace opts { 55 56 extern cl::OptionCategory BoltCategory; 57 extern cl::OptionCategory BoltOptCategory; 58 extern cl::OptionCategory BoltRelocCategory; 59 60 extern cl::opt<bool> EnableBAT; 61 extern cl::opt<bool> Instrument; 62 extern cl::opt<bool> StrictMode; 63 extern cl::opt<bool> UpdateDebugSections; 64 extern cl::opt<unsigned> Verbosity; 65 66 extern bool processAllFunctions(); 67 68 cl::opt<bool> CheckEncoding( 69 "check-encoding", 70 cl::desc("perform verification of LLVM instruction encoding/decoding. " 71 "Every instruction in the input is decoded and re-encoded. " 72 "If the resulting bytes do not match the input, a warning message " 73 "is printed."), 74 cl::Hidden, cl::cat(BoltCategory)); 75 76 static cl::opt<bool> DotToolTipCode( 77 "dot-tooltip-code", 78 cl::desc("add basic block instructions as tool tips on nodes"), cl::Hidden, 79 cl::cat(BoltCategory)); 80 81 cl::opt<JumpTableSupportLevel> 82 JumpTables("jump-tables", 83 cl::desc("jump tables support (default=basic)"), 84 cl::init(JTS_BASIC), 85 cl::values( 86 clEnumValN(JTS_NONE, "none", 87 "do not optimize functions with jump tables"), 88 clEnumValN(JTS_BASIC, "basic", 89 "optimize functions with jump tables"), 90 clEnumValN(JTS_MOVE, "move", 91 "move jump tables to a separate section"), 92 clEnumValN(JTS_SPLIT, "split", 93 "split jump tables section into hot and cold based on " 94 "function execution frequency"), 95 clEnumValN(JTS_AGGRESSIVE, "aggressive", 96 "aggressively split jump tables section based on usage " 97 "of the tables")), 98 cl::ZeroOrMore, 99 cl::cat(BoltOptCategory)); 100 101 static cl::opt<bool> NoScan( 102 "no-scan", 103 cl::desc( 104 "do not scan cold functions for external references (may result in " 105 "slower binary)"), 106 cl::Hidden, cl::cat(BoltOptCategory)); 107 108 cl::opt<bool> 109 PreserveBlocksAlignment("preserve-blocks-alignment", 110 cl::desc("try to preserve basic block alignment"), 111 cl::cat(BoltOptCategory)); 112 113 cl::opt<bool> 114 PrintDynoStats("dyno-stats", 115 cl::desc("print execution info based on profile"), 116 cl::cat(BoltCategory)); 117 118 static cl::opt<bool> 119 PrintDynoStatsOnly("print-dyno-stats-only", 120 cl::desc("while printing functions output dyno-stats and skip instructions"), 121 cl::init(false), 122 cl::Hidden, 123 cl::cat(BoltCategory)); 124 125 static cl::list<std::string> 126 PrintOnly("print-only", 127 cl::CommaSeparated, 128 cl::desc("list of functions to print"), 129 cl::value_desc("func1,func2,func3,..."), 130 cl::Hidden, 131 cl::cat(BoltCategory)); 132 133 cl::opt<bool> 134 TimeBuild("time-build", 135 cl::desc("print time spent constructing binary functions"), 136 cl::Hidden, cl::cat(BoltCategory)); 137 138 cl::opt<bool> 139 TrapOnAVX512("trap-avx512", 140 cl::desc("in relocation mode trap upon entry to any function that uses " 141 "AVX-512 instructions"), 142 cl::init(false), 143 cl::ZeroOrMore, 144 cl::Hidden, 145 cl::cat(BoltCategory)); 146 147 bool shouldPrint(const BinaryFunction &Function) { 148 if (Function.isIgnored()) 149 return false; 150 151 if (PrintOnly.empty()) 152 return true; 153 154 for (std::string &Name : opts::PrintOnly) { 155 if (Function.hasNameRegex(Name)) { 156 return true; 157 } 158 } 159 160 return false; 161 } 162 163 } // namespace opts 164 165 namespace llvm { 166 namespace bolt { 167 168 constexpr unsigned BinaryFunction::MinAlign; 169 170 template <typename R> static bool emptyRange(const R &Range) { 171 return Range.begin() == Range.end(); 172 } 173 174 /// Gets debug line information for the instruction located at the given 175 /// address in the original binary. The SMLoc's pointer is used 176 /// to point to this information, which is represented by a 177 /// DebugLineTableRowRef. The returned pointer is null if no debug line 178 /// information for this instruction was found. 179 static SMLoc findDebugLineInformationForInstructionAt( 180 uint64_t Address, DWARFUnit *Unit, 181 const DWARFDebugLine::LineTable *LineTable) { 182 // We use the pointer in SMLoc to store an instance of DebugLineTableRowRef, 183 // which occupies 64 bits. Thus, we can only proceed if the struct fits into 184 // the pointer itself. 185 assert(sizeof(decltype(SMLoc().getPointer())) >= 186 sizeof(DebugLineTableRowRef) && 187 "Cannot fit instruction debug line information into SMLoc's pointer"); 188 189 SMLoc NullResult = DebugLineTableRowRef::NULL_ROW.toSMLoc(); 190 uint32_t RowIndex = LineTable->lookupAddress( 191 {Address, object::SectionedAddress::UndefSection}); 192 if (RowIndex == LineTable->UnknownRowIndex) 193 return NullResult; 194 195 assert(RowIndex < LineTable->Rows.size() && 196 "Line Table lookup returned invalid index."); 197 198 decltype(SMLoc().getPointer()) Ptr; 199 DebugLineTableRowRef *InstructionLocation = 200 reinterpret_cast<DebugLineTableRowRef *>(&Ptr); 201 202 InstructionLocation->DwCompileUnitIndex = Unit->getOffset(); 203 InstructionLocation->RowIndex = RowIndex + 1; 204 205 return SMLoc::getFromPointer(Ptr); 206 } 207 208 static std::string buildSectionName(StringRef Prefix, StringRef Name, 209 const BinaryContext &BC) { 210 if (BC.isELF()) 211 return (Prefix + Name).str(); 212 static NameShortener NS; 213 return (Prefix + Twine(NS.getID(Name))).str(); 214 } 215 216 static raw_ostream &operator<<(raw_ostream &OS, 217 const BinaryFunction::State State) { 218 switch (State) { 219 case BinaryFunction::State::Empty: OS << "empty"; break; 220 case BinaryFunction::State::Disassembled: OS << "disassembled"; break; 221 case BinaryFunction::State::CFG: OS << "CFG constructed"; break; 222 case BinaryFunction::State::CFG_Finalized: OS << "CFG finalized"; break; 223 case BinaryFunction::State::EmittedCFG: OS << "emitted with CFG"; break; 224 case BinaryFunction::State::Emitted: OS << "emitted"; break; 225 } 226 227 return OS; 228 } 229 230 std::string BinaryFunction::buildCodeSectionName(StringRef Name, 231 const BinaryContext &BC) { 232 return buildSectionName(BC.isELF() ? ".local.text." : ".l.text.", Name, BC); 233 } 234 235 std::string BinaryFunction::buildColdCodeSectionName(StringRef Name, 236 const BinaryContext &BC) { 237 return buildSectionName(BC.isELF() ? ".local.cold.text." : ".l.c.text.", Name, 238 BC); 239 } 240 241 uint64_t BinaryFunction::Count = 0; 242 243 std::optional<StringRef> 244 BinaryFunction::hasNameRegex(const StringRef Name) const { 245 const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str(); 246 Regex MatchName(RegexName); 247 return forEachName( 248 [&MatchName](StringRef Name) { return MatchName.match(Name); }); 249 } 250 251 std::optional<StringRef> 252 BinaryFunction::hasRestoredNameRegex(const StringRef Name) const { 253 const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str(); 254 Regex MatchName(RegexName); 255 return forEachName([&MatchName](StringRef Name) { 256 return MatchName.match(NameResolver::restore(Name)); 257 }); 258 } 259 260 std::string BinaryFunction::getDemangledName() const { 261 StringRef MangledName = NameResolver::restore(getOneName()); 262 return demangle(MangledName.str()); 263 } 264 265 BinaryBasicBlock * 266 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset) { 267 if (Offset > Size) 268 return nullptr; 269 270 if (BasicBlockOffsets.empty()) 271 return nullptr; 272 273 /* 274 * This is commented out because it makes BOLT too slow. 275 * assert(std::is_sorted(BasicBlockOffsets.begin(), 276 * BasicBlockOffsets.end(), 277 * CompareBasicBlockOffsets()))); 278 */ 279 auto I = 280 llvm::upper_bound(BasicBlockOffsets, BasicBlockOffset(Offset, nullptr), 281 CompareBasicBlockOffsets()); 282 assert(I != BasicBlockOffsets.begin() && "first basic block not at offset 0"); 283 --I; 284 BinaryBasicBlock *BB = I->second; 285 return (Offset < BB->getOffset() + BB->getOriginalSize()) ? BB : nullptr; 286 } 287 288 void BinaryFunction::markUnreachableBlocks() { 289 std::stack<BinaryBasicBlock *> Stack; 290 291 for (BinaryBasicBlock &BB : blocks()) 292 BB.markValid(false); 293 294 // Add all entries and landing pads as roots. 295 for (BinaryBasicBlock *BB : BasicBlocks) { 296 if (isEntryPoint(*BB) || BB->isLandingPad()) { 297 Stack.push(BB); 298 BB->markValid(true); 299 continue; 300 } 301 // FIXME: 302 // Also mark BBs with indirect jumps as reachable, since we do not 303 // support removing unused jump tables yet (GH-issue20). 304 for (const MCInst &Inst : *BB) { 305 if (BC.MIB->getJumpTable(Inst)) { 306 Stack.push(BB); 307 BB->markValid(true); 308 break; 309 } 310 } 311 } 312 313 // Determine reachable BBs from the entry point 314 while (!Stack.empty()) { 315 BinaryBasicBlock *BB = Stack.top(); 316 Stack.pop(); 317 for (BinaryBasicBlock *Succ : BB->successors()) { 318 if (Succ->isValid()) 319 continue; 320 Succ->markValid(true); 321 Stack.push(Succ); 322 } 323 } 324 } 325 326 // Any unnecessary fallthrough jumps revealed after calling eraseInvalidBBs 327 // will be cleaned up by fixBranches(). 328 std::pair<unsigned, uint64_t> BinaryFunction::eraseInvalidBBs() { 329 DenseSet<const BinaryBasicBlock *> InvalidBBs; 330 unsigned Count = 0; 331 uint64_t Bytes = 0; 332 for (BinaryBasicBlock *const BB : BasicBlocks) { 333 if (!BB->isValid()) { 334 assert(!isEntryPoint(*BB) && "all entry blocks must be valid"); 335 InvalidBBs.insert(BB); 336 ++Count; 337 Bytes += BC.computeCodeSize(BB->begin(), BB->end()); 338 } 339 } 340 341 Layout.eraseBasicBlocks(InvalidBBs); 342 343 BasicBlockListType NewBasicBlocks; 344 for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) { 345 BinaryBasicBlock *BB = *I; 346 if (InvalidBBs.contains(BB)) { 347 // Make sure the block is removed from the list of predecessors. 348 BB->removeAllSuccessors(); 349 DeletedBasicBlocks.push_back(BB); 350 } else { 351 NewBasicBlocks.push_back(BB); 352 } 353 } 354 BasicBlocks = std::move(NewBasicBlocks); 355 356 assert(BasicBlocks.size() == Layout.block_size()); 357 358 // Update CFG state if needed 359 if (Count > 0) 360 recomputeLandingPads(); 361 362 return std::make_pair(Count, Bytes); 363 } 364 365 bool BinaryFunction::isForwardCall(const MCSymbol *CalleeSymbol) const { 366 // This function should work properly before and after function reordering. 367 // In order to accomplish this, we use the function index (if it is valid). 368 // If the function indices are not valid, we fall back to the original 369 // addresses. This should be ok because the functions without valid indices 370 // should have been ordered with a stable sort. 371 const BinaryFunction *CalleeBF = BC.getFunctionForSymbol(CalleeSymbol); 372 if (CalleeBF) { 373 if (CalleeBF->isInjected()) 374 return true; 375 376 if (hasValidIndex() && CalleeBF->hasValidIndex()) { 377 return getIndex() < CalleeBF->getIndex(); 378 } else if (hasValidIndex() && !CalleeBF->hasValidIndex()) { 379 return true; 380 } else if (!hasValidIndex() && CalleeBF->hasValidIndex()) { 381 return false; 382 } else { 383 return getAddress() < CalleeBF->getAddress(); 384 } 385 } else { 386 // Absolute symbol. 387 ErrorOr<uint64_t> CalleeAddressOrError = BC.getSymbolValue(*CalleeSymbol); 388 assert(CalleeAddressOrError && "unregistered symbol found"); 389 return *CalleeAddressOrError > getAddress(); 390 } 391 } 392 393 void BinaryFunction::dump() const { 394 // getDynoStats calls FunctionLayout::updateLayoutIndices and 395 // BasicBlock::analyzeBranch. The former cannot be const, but should be 396 // removed, the latter should be made const, but seems to require refactoring. 397 // Forcing all callers to have a non-const reference to BinaryFunction to call 398 // dump non-const however is not ideal either. Adding this const_cast is right 399 // now the best solution. It is safe, because BinaryFunction itself is not 400 // modified. Only BinaryBasicBlocks are actually modified (if it all) and we 401 // have mutable pointers to those regardless whether this function is 402 // const-qualified or not. 403 const_cast<BinaryFunction &>(*this).print(dbgs(), ""); 404 } 405 406 void BinaryFunction::print(raw_ostream &OS, std::string Annotation) { 407 if (!opts::shouldPrint(*this)) 408 return; 409 410 StringRef SectionName = 411 OriginSection ? OriginSection->getName() : "<no origin section>"; 412 OS << "Binary Function \"" << *this << "\" " << Annotation << " {"; 413 std::vector<StringRef> AllNames = getNames(); 414 if (AllNames.size() > 1) { 415 OS << "\n All names : "; 416 const char *Sep = ""; 417 for (const StringRef &Name : AllNames) { 418 OS << Sep << Name; 419 Sep = "\n "; 420 } 421 } 422 OS << "\n Number : " << FunctionNumber; 423 OS << "\n State : " << CurrentState; 424 OS << "\n Address : 0x" << Twine::utohexstr(Address); 425 OS << "\n Size : 0x" << Twine::utohexstr(Size); 426 OS << "\n MaxSize : 0x" << Twine::utohexstr(MaxSize); 427 OS << "\n Offset : 0x" << Twine::utohexstr(getFileOffset()); 428 OS << "\n Section : " << SectionName; 429 OS << "\n Orc Section : " << getCodeSectionName(); 430 OS << "\n LSDA : 0x" << Twine::utohexstr(getLSDAAddress()); 431 OS << "\n IsSimple : " << IsSimple; 432 OS << "\n IsMultiEntry: " << isMultiEntry(); 433 OS << "\n IsSplit : " << isSplit(); 434 OS << "\n BB Count : " << size(); 435 436 if (HasFixedIndirectBranch) 437 OS << "\n HasFixedIndirectBranch : true"; 438 if (HasUnknownControlFlow) 439 OS << "\n Unknown CF : true"; 440 if (getPersonalityFunction()) 441 OS << "\n Personality : " << getPersonalityFunction()->getName(); 442 if (IsFragment) 443 OS << "\n IsFragment : true"; 444 if (isFolded()) 445 OS << "\n FoldedInto : " << *getFoldedIntoFunction(); 446 for (BinaryFunction *ParentFragment : ParentFragments) 447 OS << "\n Parent : " << *ParentFragment; 448 if (!Fragments.empty()) { 449 OS << "\n Fragments : "; 450 ListSeparator LS; 451 for (BinaryFunction *Frag : Fragments) 452 OS << LS << *Frag; 453 } 454 if (hasCFG()) 455 OS << "\n Hash : " << Twine::utohexstr(computeHash()); 456 if (isMultiEntry()) { 457 OS << "\n Secondary Entry Points : "; 458 ListSeparator LS; 459 for (const auto &KV : SecondaryEntryPoints) 460 OS << LS << KV.second->getName(); 461 } 462 if (FrameInstructions.size()) 463 OS << "\n CFI Instrs : " << FrameInstructions.size(); 464 if (!Layout.block_empty()) { 465 OS << "\n BB Layout : "; 466 ListSeparator LS; 467 for (const BinaryBasicBlock *BB : Layout.blocks()) 468 OS << LS << BB->getName(); 469 } 470 if (getImageAddress()) 471 OS << "\n Image : 0x" << Twine::utohexstr(getImageAddress()); 472 if (ExecutionCount != COUNT_NO_PROFILE) { 473 OS << "\n Exec Count : " << ExecutionCount; 474 OS << "\n Branch Count: " << RawBranchCount; 475 OS << "\n Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f); 476 } 477 478 if (opts::PrintDynoStats && !getLayout().block_empty()) { 479 OS << '\n'; 480 DynoStats dynoStats = getDynoStats(*this); 481 OS << dynoStats; 482 } 483 484 OS << "\n}\n"; 485 486 if (opts::PrintDynoStatsOnly || !BC.InstPrinter) 487 return; 488 489 // Offset of the instruction in function. 490 uint64_t Offset = 0; 491 492 if (BasicBlocks.empty() && !Instructions.empty()) { 493 // Print before CFG was built. 494 for (const std::pair<const uint32_t, MCInst> &II : Instructions) { 495 Offset = II.first; 496 497 // Print label if exists at this offset. 498 auto LI = Labels.find(Offset); 499 if (LI != Labels.end()) { 500 if (const MCSymbol *EntrySymbol = 501 getSecondaryEntryPointSymbol(LI->second)) 502 OS << EntrySymbol->getName() << " (Entry Point):\n"; 503 OS << LI->second->getName() << ":\n"; 504 } 505 506 BC.printInstruction(OS, II.second, Offset, this); 507 } 508 } 509 510 StringRef SplitPointMsg = ""; 511 for (const FunctionFragment &FF : Layout.fragments()) { 512 OS << SplitPointMsg; 513 SplitPointMsg = "------- HOT-COLD SPLIT POINT -------\n\n"; 514 for (const BinaryBasicBlock *BB : FF) { 515 OS << BB->getName() << " (" << BB->size() 516 << " instructions, align : " << BB->getAlignment() << ")\n"; 517 518 if (isEntryPoint(*BB)) { 519 if (MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB)) 520 OS << " Secondary Entry Point: " << EntrySymbol->getName() << '\n'; 521 else 522 OS << " Entry Point\n"; 523 } 524 525 if (BB->isLandingPad()) 526 OS << " Landing Pad\n"; 527 528 uint64_t BBExecCount = BB->getExecutionCount(); 529 if (hasValidProfile()) { 530 OS << " Exec Count : "; 531 if (BB->getExecutionCount() != BinaryBasicBlock::COUNT_NO_PROFILE) 532 OS << BBExecCount << '\n'; 533 else 534 OS << "<unknown>\n"; 535 } 536 if (BB->getCFIState() >= 0) 537 OS << " CFI State : " << BB->getCFIState() << '\n'; 538 if (opts::EnableBAT) { 539 OS << " Input offset: " << Twine::utohexstr(BB->getInputOffset()) 540 << "\n"; 541 } 542 if (!BB->pred_empty()) { 543 OS << " Predecessors: "; 544 ListSeparator LS; 545 for (BinaryBasicBlock *Pred : BB->predecessors()) 546 OS << LS << Pred->getName(); 547 OS << '\n'; 548 } 549 if (!BB->throw_empty()) { 550 OS << " Throwers: "; 551 ListSeparator LS; 552 for (BinaryBasicBlock *Throw : BB->throwers()) 553 OS << LS << Throw->getName(); 554 OS << '\n'; 555 } 556 557 Offset = alignTo(Offset, BB->getAlignment()); 558 559 // Note: offsets are imprecise since this is happening prior to 560 // relaxation. 561 Offset = BC.printInstructions(OS, BB->begin(), BB->end(), Offset, this); 562 563 if (!BB->succ_empty()) { 564 OS << " Successors: "; 565 // For more than 2 successors, sort them based on frequency. 566 std::vector<uint64_t> Indices(BB->succ_size()); 567 std::iota(Indices.begin(), Indices.end(), 0); 568 if (BB->succ_size() > 2 && BB->getKnownExecutionCount()) { 569 llvm::stable_sort(Indices, [&](const uint64_t A, const uint64_t B) { 570 return BB->BranchInfo[B] < BB->BranchInfo[A]; 571 }); 572 } 573 ListSeparator LS; 574 for (unsigned I = 0; I < Indices.size(); ++I) { 575 BinaryBasicBlock *Succ = BB->Successors[Indices[I]]; 576 const BinaryBasicBlock::BinaryBranchInfo &BI = 577 BB->BranchInfo[Indices[I]]; 578 OS << LS << Succ->getName(); 579 if (ExecutionCount != COUNT_NO_PROFILE && 580 BI.MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) { 581 OS << " (mispreds: " << BI.MispredictedCount 582 << ", count: " << BI.Count << ")"; 583 } else if (ExecutionCount != COUNT_NO_PROFILE && 584 BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE) { 585 OS << " (inferred count: " << BI.Count << ")"; 586 } 587 } 588 OS << '\n'; 589 } 590 591 if (!BB->lp_empty()) { 592 OS << " Landing Pads: "; 593 ListSeparator LS; 594 for (BinaryBasicBlock *LP : BB->landing_pads()) { 595 OS << LS << LP->getName(); 596 if (ExecutionCount != COUNT_NO_PROFILE) { 597 OS << " (count: " << LP->getExecutionCount() << ")"; 598 } 599 } 600 OS << '\n'; 601 } 602 603 // In CFG_Finalized state we can miscalculate CFI state at exit. 604 if (CurrentState == State::CFG) { 605 const int32_t CFIStateAtExit = BB->getCFIStateAtExit(); 606 if (CFIStateAtExit >= 0) 607 OS << " CFI State: " << CFIStateAtExit << '\n'; 608 } 609 610 OS << '\n'; 611 } 612 } 613 614 // Dump new exception ranges for the function. 615 if (!CallSites.empty()) { 616 OS << "EH table:\n"; 617 for (const FunctionFragment &FF : getLayout().fragments()) { 618 for (const auto &FCSI : getCallSites(FF.getFragmentNum())) { 619 const CallSite &CSI = FCSI.second; 620 OS << " [" << *CSI.Start << ", " << *CSI.End << ") landing pad : "; 621 if (CSI.LP) 622 OS << *CSI.LP; 623 else 624 OS << "0"; 625 OS << ", action : " << CSI.Action << '\n'; 626 } 627 } 628 OS << '\n'; 629 } 630 631 // Print all jump tables. 632 for (const std::pair<const uint64_t, JumpTable *> &JTI : JumpTables) 633 JTI.second->print(OS); 634 635 OS << "DWARF CFI Instructions:\n"; 636 if (OffsetToCFI.size()) { 637 // Pre-buildCFG information 638 for (const std::pair<const uint32_t, uint32_t> &Elmt : OffsetToCFI) { 639 OS << format(" %08x:\t", Elmt.first); 640 assert(Elmt.second < FrameInstructions.size() && "Incorrect CFI offset"); 641 BinaryContext::printCFI(OS, FrameInstructions[Elmt.second]); 642 OS << "\n"; 643 } 644 } else { 645 // Post-buildCFG information 646 for (uint32_t I = 0, E = FrameInstructions.size(); I != E; ++I) { 647 const MCCFIInstruction &CFI = FrameInstructions[I]; 648 OS << format(" %d:\t", I); 649 BinaryContext::printCFI(OS, CFI); 650 OS << "\n"; 651 } 652 } 653 if (FrameInstructions.empty()) 654 OS << " <empty>\n"; 655 656 OS << "End of Function \"" << *this << "\"\n\n"; 657 } 658 659 void BinaryFunction::printRelocations(raw_ostream &OS, uint64_t Offset, 660 uint64_t Size) const { 661 const char *Sep = " # Relocs: "; 662 663 auto RI = Relocations.lower_bound(Offset); 664 while (RI != Relocations.end() && RI->first < Offset + Size) { 665 OS << Sep << "(R: " << RI->second << ")"; 666 Sep = ", "; 667 ++RI; 668 } 669 } 670 671 static std::string mutateDWARFExpressionTargetReg(const MCCFIInstruction &Instr, 672 MCPhysReg NewReg) { 673 StringRef ExprBytes = Instr.getValues(); 674 assert(ExprBytes.size() > 1 && "DWARF expression CFI is too short"); 675 uint8_t Opcode = ExprBytes[0]; 676 assert((Opcode == dwarf::DW_CFA_expression || 677 Opcode == dwarf::DW_CFA_val_expression) && 678 "invalid DWARF expression CFI"); 679 (void)Opcode; 680 const uint8_t *const Start = 681 reinterpret_cast<const uint8_t *>(ExprBytes.drop_front(1).data()); 682 const uint8_t *const End = 683 reinterpret_cast<const uint8_t *>(Start + ExprBytes.size() - 1); 684 unsigned Size = 0; 685 decodeULEB128(Start, &Size, End); 686 assert(Size > 0 && "Invalid reg encoding for DWARF expression CFI"); 687 SmallString<8> Tmp; 688 raw_svector_ostream OSE(Tmp); 689 encodeULEB128(NewReg, OSE); 690 return Twine(ExprBytes.slice(0, 1)) 691 .concat(OSE.str()) 692 .concat(ExprBytes.drop_front(1 + Size)) 693 .str(); 694 } 695 696 void BinaryFunction::mutateCFIRegisterFor(const MCInst &Instr, 697 MCPhysReg NewReg) { 698 const MCCFIInstruction *OldCFI = getCFIFor(Instr); 699 assert(OldCFI && "invalid CFI instr"); 700 switch (OldCFI->getOperation()) { 701 default: 702 llvm_unreachable("Unexpected instruction"); 703 case MCCFIInstruction::OpDefCfa: 704 setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, NewReg, 705 OldCFI->getOffset())); 706 break; 707 case MCCFIInstruction::OpDefCfaRegister: 708 setCFIFor(Instr, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg)); 709 break; 710 case MCCFIInstruction::OpOffset: 711 setCFIFor(Instr, MCCFIInstruction::createOffset(nullptr, NewReg, 712 OldCFI->getOffset())); 713 break; 714 case MCCFIInstruction::OpRegister: 715 setCFIFor(Instr, MCCFIInstruction::createRegister(nullptr, NewReg, 716 OldCFI->getRegister2())); 717 break; 718 case MCCFIInstruction::OpSameValue: 719 setCFIFor(Instr, MCCFIInstruction::createSameValue(nullptr, NewReg)); 720 break; 721 case MCCFIInstruction::OpEscape: 722 setCFIFor(Instr, 723 MCCFIInstruction::createEscape( 724 nullptr, 725 StringRef(mutateDWARFExpressionTargetReg(*OldCFI, NewReg)))); 726 break; 727 case MCCFIInstruction::OpRestore: 728 setCFIFor(Instr, MCCFIInstruction::createRestore(nullptr, NewReg)); 729 break; 730 case MCCFIInstruction::OpUndefined: 731 setCFIFor(Instr, MCCFIInstruction::createUndefined(nullptr, NewReg)); 732 break; 733 } 734 } 735 736 const MCCFIInstruction *BinaryFunction::mutateCFIOffsetFor(const MCInst &Instr, 737 int64_t NewOffset) { 738 const MCCFIInstruction *OldCFI = getCFIFor(Instr); 739 assert(OldCFI && "invalid CFI instr"); 740 switch (OldCFI->getOperation()) { 741 default: 742 llvm_unreachable("Unexpected instruction"); 743 case MCCFIInstruction::OpDefCfaOffset: 744 setCFIFor(Instr, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset)); 745 break; 746 case MCCFIInstruction::OpAdjustCfaOffset: 747 setCFIFor(Instr, 748 MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset)); 749 break; 750 case MCCFIInstruction::OpDefCfa: 751 setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI->getRegister(), 752 NewOffset)); 753 break; 754 case MCCFIInstruction::OpOffset: 755 setCFIFor(Instr, MCCFIInstruction::createOffset( 756 nullptr, OldCFI->getRegister(), NewOffset)); 757 break; 758 } 759 return getCFIFor(Instr); 760 } 761 762 IndirectBranchType 763 BinaryFunction::processIndirectBranch(MCInst &Instruction, unsigned Size, 764 uint64_t Offset, 765 uint64_t &TargetAddress) { 766 const unsigned PtrSize = BC.AsmInfo->getCodePointerSize(); 767 768 // The instruction referencing memory used by the branch instruction. 769 // It could be the branch instruction itself or one of the instructions 770 // setting the value of the register used by the branch. 771 MCInst *MemLocInstr; 772 773 // Address of the table referenced by MemLocInstr. Could be either an 774 // array of function pointers, or a jump table. 775 uint64_t ArrayStart = 0; 776 777 unsigned BaseRegNum, IndexRegNum; 778 int64_t DispValue; 779 const MCExpr *DispExpr; 780 781 // In AArch, identify the instruction adding the PC-relative offset to 782 // jump table entries to correctly decode it. 783 MCInst *PCRelBaseInstr; 784 uint64_t PCRelAddr = 0; 785 786 auto Begin = Instructions.begin(); 787 if (BC.isAArch64()) { 788 PreserveNops = BC.HasRelocations; 789 // Start at the last label as an approximation of the current basic block. 790 // This is a heuristic, since the full set of labels have yet to be 791 // determined 792 for (const uint32_t Offset : 793 llvm::make_first_range(llvm::reverse(Labels))) { 794 auto II = Instructions.find(Offset); 795 if (II != Instructions.end()) { 796 Begin = II; 797 break; 798 } 799 } 800 } 801 802 IndirectBranchType BranchType = BC.MIB->analyzeIndirectBranch( 803 Instruction, Begin, Instructions.end(), PtrSize, MemLocInstr, BaseRegNum, 804 IndexRegNum, DispValue, DispExpr, PCRelBaseInstr); 805 806 if (BranchType == IndirectBranchType::UNKNOWN && !MemLocInstr) 807 return BranchType; 808 809 if (MemLocInstr != &Instruction) 810 IndexRegNum = BC.MIB->getNoRegister(); 811 812 if (BC.isAArch64()) { 813 const MCSymbol *Sym = BC.MIB->getTargetSymbol(*PCRelBaseInstr, 1); 814 assert(Sym && "Symbol extraction failed"); 815 ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*Sym); 816 if (SymValueOrError) { 817 PCRelAddr = *SymValueOrError; 818 } else { 819 for (std::pair<const uint32_t, MCSymbol *> &Elmt : Labels) { 820 if (Elmt.second == Sym) { 821 PCRelAddr = Elmt.first + getAddress(); 822 break; 823 } 824 } 825 } 826 uint64_t InstrAddr = 0; 827 for (auto II = Instructions.rbegin(); II != Instructions.rend(); ++II) { 828 if (&II->second == PCRelBaseInstr) { 829 InstrAddr = II->first + getAddress(); 830 break; 831 } 832 } 833 assert(InstrAddr != 0 && "instruction not found"); 834 // We do this to avoid spurious references to code locations outside this 835 // function (for example, if the indirect jump lives in the last basic 836 // block of the function, it will create a reference to the next function). 837 // This replaces a symbol reference with an immediate. 838 BC.MIB->replaceMemOperandDisp(*PCRelBaseInstr, 839 MCOperand::createImm(PCRelAddr - InstrAddr)); 840 // FIXME: Disable full jump table processing for AArch64 until we have a 841 // proper way of determining the jump table limits. 842 return IndirectBranchType::UNKNOWN; 843 } 844 845 // RIP-relative addressing should be converted to symbol form by now 846 // in processed instructions (but not in jump). 847 if (DispExpr) { 848 const MCSymbol *TargetSym; 849 uint64_t TargetOffset; 850 std::tie(TargetSym, TargetOffset) = BC.MIB->getTargetSymbolInfo(DispExpr); 851 ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*TargetSym); 852 assert(SymValueOrError && "global symbol needs a value"); 853 ArrayStart = *SymValueOrError + TargetOffset; 854 BaseRegNum = BC.MIB->getNoRegister(); 855 if (BC.isAArch64()) { 856 ArrayStart &= ~0xFFFULL; 857 ArrayStart += DispValue & 0xFFFULL; 858 } 859 } else { 860 ArrayStart = static_cast<uint64_t>(DispValue); 861 } 862 863 if (BaseRegNum == BC.MRI->getProgramCounter()) 864 ArrayStart += getAddress() + Offset + Size; 865 866 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addressed memory is 0x" 867 << Twine::utohexstr(ArrayStart) << '\n'); 868 869 ErrorOr<BinarySection &> Section = BC.getSectionForAddress(ArrayStart); 870 if (!Section) { 871 // No section - possibly an absolute address. Since we don't allow 872 // internal function addresses to escape the function scope - we 873 // consider it a tail call. 874 if (opts::Verbosity >= 1) { 875 errs() << "BOLT-WARNING: no section for address 0x" 876 << Twine::utohexstr(ArrayStart) << " referenced from function " 877 << *this << '\n'; 878 } 879 return IndirectBranchType::POSSIBLE_TAIL_CALL; 880 } 881 if (Section->isVirtual()) { 882 // The contents are filled at runtime. 883 return IndirectBranchType::POSSIBLE_TAIL_CALL; 884 } 885 886 if (BranchType == IndirectBranchType::POSSIBLE_FIXED_BRANCH) { 887 ErrorOr<uint64_t> Value = BC.getPointerAtAddress(ArrayStart); 888 if (!Value) 889 return IndirectBranchType::UNKNOWN; 890 891 if (BC.getSectionForAddress(ArrayStart)->isWritable()) 892 return IndirectBranchType::UNKNOWN; 893 894 outs() << "BOLT-INFO: fixed indirect branch detected in " << *this 895 << " at 0x" << Twine::utohexstr(getAddress() + Offset) 896 << " referencing data at 0x" << Twine::utohexstr(ArrayStart) 897 << " the destination value is 0x" << Twine::utohexstr(*Value) 898 << '\n'; 899 900 TargetAddress = *Value; 901 return BranchType; 902 } 903 904 // Check if there's already a jump table registered at this address. 905 MemoryContentsType MemType; 906 if (JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart)) { 907 switch (JT->Type) { 908 case JumpTable::JTT_NORMAL: 909 MemType = MemoryContentsType::POSSIBLE_JUMP_TABLE; 910 break; 911 case JumpTable::JTT_PIC: 912 MemType = MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE; 913 break; 914 } 915 } else { 916 MemType = BC.analyzeMemoryAt(ArrayStart, *this); 917 } 918 919 // Check that jump table type in instruction pattern matches memory contents. 920 JumpTable::JumpTableType JTType; 921 if (BranchType == IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE) { 922 if (MemType != MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE) 923 return IndirectBranchType::UNKNOWN; 924 JTType = JumpTable::JTT_PIC; 925 } else { 926 if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE) 927 return IndirectBranchType::UNKNOWN; 928 929 if (MemType == MemoryContentsType::UNKNOWN) 930 return IndirectBranchType::POSSIBLE_TAIL_CALL; 931 932 BranchType = IndirectBranchType::POSSIBLE_JUMP_TABLE; 933 JTType = JumpTable::JTT_NORMAL; 934 } 935 936 // Convert the instruction into jump table branch. 937 const MCSymbol *JTLabel = BC.getOrCreateJumpTable(*this, ArrayStart, JTType); 938 BC.MIB->replaceMemOperandDisp(*MemLocInstr, JTLabel, BC.Ctx.get()); 939 BC.MIB->setJumpTable(Instruction, ArrayStart, IndexRegNum); 940 941 JTSites.emplace_back(Offset, ArrayStart); 942 943 return BranchType; 944 } 945 946 MCSymbol *BinaryFunction::getOrCreateLocalLabel(uint64_t Address, 947 bool CreatePastEnd) { 948 const uint64_t Offset = Address - getAddress(); 949 950 if ((Offset == getSize()) && CreatePastEnd) 951 return getFunctionEndLabel(); 952 953 auto LI = Labels.find(Offset); 954 if (LI != Labels.end()) 955 return LI->second; 956 957 // For AArch64, check if this address is part of a constant island. 958 if (BC.isAArch64()) { 959 if (MCSymbol *IslandSym = getOrCreateIslandAccess(Address)) 960 return IslandSym; 961 } 962 963 MCSymbol *Label = BC.Ctx->createNamedTempSymbol(); 964 Labels[Offset] = Label; 965 966 return Label; 967 } 968 969 ErrorOr<ArrayRef<uint8_t>> BinaryFunction::getData() const { 970 BinarySection &Section = *getOriginSection(); 971 assert(Section.containsRange(getAddress(), getMaxSize()) && 972 "wrong section for function"); 973 974 if (!Section.isText() || Section.isVirtual() || !Section.getSize()) 975 return std::make_error_code(std::errc::bad_address); 976 977 StringRef SectionContents = Section.getContents(); 978 979 assert(SectionContents.size() == Section.getSize() && 980 "section size mismatch"); 981 982 // Function offset from the section start. 983 uint64_t Offset = getAddress() - Section.getAddress(); 984 auto *Bytes = reinterpret_cast<const uint8_t *>(SectionContents.data()); 985 return ArrayRef<uint8_t>(Bytes + Offset, getMaxSize()); 986 } 987 988 size_t BinaryFunction::getSizeOfDataInCodeAt(uint64_t Offset) const { 989 if (!Islands) 990 return 0; 991 992 if (!llvm::is_contained(Islands->DataOffsets, Offset)) 993 return 0; 994 995 auto Iter = Islands->CodeOffsets.upper_bound(Offset); 996 if (Iter != Islands->CodeOffsets.end()) 997 return *Iter - Offset; 998 return getSize() - Offset; 999 } 1000 1001 bool BinaryFunction::isZeroPaddingAt(uint64_t Offset) const { 1002 ArrayRef<uint8_t> FunctionData = *getData(); 1003 uint64_t EndOfCode = getSize(); 1004 if (Islands) { 1005 auto Iter = Islands->DataOffsets.upper_bound(Offset); 1006 if (Iter != Islands->DataOffsets.end()) 1007 EndOfCode = *Iter; 1008 } 1009 for (uint64_t I = Offset; I < EndOfCode; ++I) 1010 if (FunctionData[I] != 0) 1011 return false; 1012 1013 return true; 1014 } 1015 1016 void BinaryFunction::handlePCRelOperand(MCInst &Instruction, uint64_t Address, 1017 uint64_t Size) { 1018 auto &MIB = BC.MIB; 1019 uint64_t TargetAddress = 0; 1020 if (!MIB->evaluateMemOperandTarget(Instruction, TargetAddress, Address, 1021 Size)) { 1022 errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n"; 1023 BC.InstPrinter->printInst(&Instruction, 0, "", *BC.STI, errs()); 1024 errs() << '\n'; 1025 Instruction.dump_pretty(errs(), BC.InstPrinter.get()); 1026 errs() << '\n'; 1027 errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x" 1028 << Twine::utohexstr(Address) << ". Skipping function " << *this 1029 << ".\n"; 1030 if (BC.HasRelocations) 1031 exit(1); 1032 IsSimple = false; 1033 return; 1034 } 1035 if (TargetAddress == 0 && opts::Verbosity >= 1) { 1036 outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this 1037 << '\n'; 1038 } 1039 1040 const MCSymbol *TargetSymbol; 1041 uint64_t TargetOffset; 1042 std::tie(TargetSymbol, TargetOffset) = 1043 BC.handleAddressRef(TargetAddress, *this, /*IsPCRel*/ true); 1044 1045 bool ReplaceSuccess = MIB->replaceMemOperandDisp( 1046 Instruction, TargetSymbol, static_cast<int64_t>(TargetOffset), &*BC.Ctx); 1047 (void)ReplaceSuccess; 1048 assert(ReplaceSuccess && "Failed to replace mem operand with symbol+off."); 1049 } 1050 1051 MCSymbol *BinaryFunction::handleExternalReference(MCInst &Instruction, 1052 uint64_t Size, 1053 uint64_t Offset, 1054 uint64_t TargetAddress, 1055 bool &IsCall) { 1056 auto &MIB = BC.MIB; 1057 1058 const uint64_t AbsoluteInstrAddr = getAddress() + Offset; 1059 BC.addInterproceduralReference(this, TargetAddress); 1060 if (opts::Verbosity >= 2 && !IsCall && Size == 2 && !BC.HasRelocations) { 1061 errs() << "BOLT-WARNING: relaxed tail call detected at 0x" 1062 << Twine::utohexstr(AbsoluteInstrAddr) << " in function " << *this 1063 << ". Code size will be increased.\n"; 1064 } 1065 1066 assert(!MIB->isTailCall(Instruction) && 1067 "synthetic tail call instruction found"); 1068 1069 // This is a call regardless of the opcode. 1070 // Assign proper opcode for tail calls, so that they could be 1071 // treated as calls. 1072 if (!IsCall) { 1073 if (!MIB->convertJmpToTailCall(Instruction)) { 1074 assert(MIB->isConditionalBranch(Instruction) && 1075 "unknown tail call instruction"); 1076 if (opts::Verbosity >= 2) { 1077 errs() << "BOLT-WARNING: conditional tail call detected in " 1078 << "function " << *this << " at 0x" 1079 << Twine::utohexstr(AbsoluteInstrAddr) << ".\n"; 1080 } 1081 } 1082 IsCall = true; 1083 } 1084 1085 if (opts::Verbosity >= 2 && TargetAddress == 0) { 1086 // We actually see calls to address 0 in presence of weak 1087 // symbols originating from libraries. This code is never meant 1088 // to be executed. 1089 outs() << "BOLT-INFO: Function " << *this 1090 << " has a call to address zero.\n"; 1091 } 1092 1093 return BC.getOrCreateGlobalSymbol(TargetAddress, "FUNCat"); 1094 } 1095 1096 void BinaryFunction::handleIndirectBranch(MCInst &Instruction, uint64_t Size, 1097 uint64_t Offset) { 1098 auto &MIB = BC.MIB; 1099 uint64_t IndirectTarget = 0; 1100 IndirectBranchType Result = 1101 processIndirectBranch(Instruction, Size, Offset, IndirectTarget); 1102 switch (Result) { 1103 default: 1104 llvm_unreachable("unexpected result"); 1105 case IndirectBranchType::POSSIBLE_TAIL_CALL: { 1106 bool Result = MIB->convertJmpToTailCall(Instruction); 1107 (void)Result; 1108 assert(Result); 1109 break; 1110 } 1111 case IndirectBranchType::POSSIBLE_JUMP_TABLE: 1112 case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE: 1113 if (opts::JumpTables == JTS_NONE) 1114 IsSimple = false; 1115 break; 1116 case IndirectBranchType::POSSIBLE_FIXED_BRANCH: { 1117 if (containsAddress(IndirectTarget)) { 1118 const MCSymbol *TargetSymbol = getOrCreateLocalLabel(IndirectTarget); 1119 Instruction.clear(); 1120 MIB->createUncondBranch(Instruction, TargetSymbol, BC.Ctx.get()); 1121 TakenBranches.emplace_back(Offset, IndirectTarget - getAddress()); 1122 HasFixedIndirectBranch = true; 1123 } else { 1124 MIB->convertJmpToTailCall(Instruction); 1125 BC.addInterproceduralReference(this, IndirectTarget); 1126 } 1127 break; 1128 } 1129 case IndirectBranchType::UNKNOWN: 1130 // Keep processing. We'll do more checks and fixes in 1131 // postProcessIndirectBranches(). 1132 UnknownIndirectBranchOffsets.emplace(Offset); 1133 break; 1134 } 1135 } 1136 1137 void BinaryFunction::handleAArch64IndirectCall(MCInst &Instruction, 1138 const uint64_t Offset) { 1139 auto &MIB = BC.MIB; 1140 const uint64_t AbsoluteInstrAddr = getAddress() + Offset; 1141 MCInst *TargetHiBits, *TargetLowBits; 1142 uint64_t TargetAddress, Count; 1143 Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(), 1144 AbsoluteInstrAddr, Instruction, TargetHiBits, 1145 TargetLowBits, TargetAddress); 1146 if (Count) { 1147 MIB->addAnnotation(Instruction, "AArch64Veneer", true); 1148 --Count; 1149 for (auto It = std::prev(Instructions.end()); Count != 0; 1150 It = std::prev(It), --Count) { 1151 MIB->addAnnotation(It->second, "AArch64Veneer", true); 1152 } 1153 1154 BC.addAdrpAddRelocAArch64(*this, *TargetLowBits, *TargetHiBits, 1155 TargetAddress); 1156 } 1157 } 1158 1159 bool BinaryFunction::disassemble() { 1160 NamedRegionTimer T("disassemble", "Disassemble function", "buildfuncs", 1161 "Build Binary Functions", opts::TimeBuild); 1162 ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData(); 1163 assert(ErrorOrFunctionData && "function data is not available"); 1164 ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData; 1165 assert(FunctionData.size() == getMaxSize() && 1166 "function size does not match raw data size"); 1167 1168 auto &Ctx = BC.Ctx; 1169 auto &MIB = BC.MIB; 1170 1171 BC.SymbolicDisAsm->setSymbolizer(MIB->createTargetSymbolizer(*this)); 1172 1173 // Insert a label at the beginning of the function. This will be our first 1174 // basic block. 1175 Labels[0] = Ctx->createNamedTempSymbol("BB0"); 1176 1177 uint64_t Size = 0; // instruction size 1178 for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) { 1179 MCInst Instruction; 1180 const uint64_t AbsoluteInstrAddr = getAddress() + Offset; 1181 1182 // Check for data inside code and ignore it 1183 if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) { 1184 Size = DataInCodeSize; 1185 continue; 1186 } 1187 1188 if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size, 1189 FunctionData.slice(Offset), 1190 AbsoluteInstrAddr, nulls())) { 1191 // Functions with "soft" boundaries, e.g. coming from assembly source, 1192 // can have 0-byte padding at the end. 1193 if (isZeroPaddingAt(Offset)) 1194 break; 1195 1196 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x" 1197 << Twine::utohexstr(Offset) << " (address 0x" 1198 << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this 1199 << '\n'; 1200 // Some AVX-512 instructions could not be disassembled at all. 1201 if (BC.HasRelocations && opts::TrapOnAVX512 && BC.isX86()) { 1202 setTrapOnEntry(); 1203 BC.TrappedFunctions.push_back(this); 1204 } else { 1205 setIgnored(); 1206 } 1207 1208 break; 1209 } 1210 1211 // Check integrity of LLVM assembler/disassembler. 1212 if (opts::CheckEncoding && !BC.MIB->isBranch(Instruction) && 1213 !BC.MIB->isCall(Instruction) && !BC.MIB->isNoop(Instruction)) { 1214 if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) { 1215 errs() << "BOLT-WARNING: mismatching LLVM encoding detected in " 1216 << "function " << *this << " for instruction :\n"; 1217 BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr); 1218 errs() << '\n'; 1219 } 1220 } 1221 1222 // Special handling for AVX-512 instructions. 1223 if (MIB->hasEVEXEncoding(Instruction)) { 1224 if (BC.HasRelocations && opts::TrapOnAVX512) { 1225 setTrapOnEntry(); 1226 BC.TrappedFunctions.push_back(this); 1227 break; 1228 } 1229 1230 if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) { 1231 errs() << "BOLT-WARNING: internal assembler/disassembler error " 1232 "detected for AVX512 instruction:\n"; 1233 BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr); 1234 errs() << " in function " << *this << '\n'; 1235 setIgnored(); 1236 break; 1237 } 1238 } 1239 1240 if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) { 1241 uint64_t TargetAddress = 0; 1242 if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size, 1243 TargetAddress)) { 1244 // Check if the target is within the same function. Otherwise it's 1245 // a call, possibly a tail call. 1246 // 1247 // If the target *is* the function address it could be either a branch 1248 // or a recursive call. 1249 bool IsCall = MIB->isCall(Instruction); 1250 const bool IsCondBranch = MIB->isConditionalBranch(Instruction); 1251 MCSymbol *TargetSymbol = nullptr; 1252 1253 if (BC.MIB->isUnsupportedBranch(Instruction)) { 1254 setIgnored(); 1255 if (BinaryFunction *TargetFunc = 1256 BC.getBinaryFunctionContainingAddress(TargetAddress)) 1257 TargetFunc->setIgnored(); 1258 } 1259 1260 if (IsCall && containsAddress(TargetAddress)) { 1261 if (TargetAddress == getAddress()) { 1262 // Recursive call. 1263 TargetSymbol = getSymbol(); 1264 } else { 1265 if (BC.isX86()) { 1266 // Dangerous old-style x86 PIC code. We may need to freeze this 1267 // function, so preserve the function as is for now. 1268 PreserveNops = true; 1269 } else { 1270 errs() << "BOLT-WARNING: internal call detected at 0x" 1271 << Twine::utohexstr(AbsoluteInstrAddr) << " in function " 1272 << *this << ". Skipping.\n"; 1273 IsSimple = false; 1274 } 1275 } 1276 } 1277 1278 if (!TargetSymbol) { 1279 // Create either local label or external symbol. 1280 if (containsAddress(TargetAddress)) { 1281 TargetSymbol = getOrCreateLocalLabel(TargetAddress); 1282 } else { 1283 if (TargetAddress == getAddress() + getSize() && 1284 TargetAddress < getAddress() + getMaxSize() && 1285 !(BC.isAArch64() && 1286 BC.handleAArch64Veneer(TargetAddress, /*MatchOnly*/ true))) { 1287 // Result of __builtin_unreachable(). 1288 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x" 1289 << Twine::utohexstr(AbsoluteInstrAddr) 1290 << " in function " << *this 1291 << " : replacing with nop.\n"); 1292 BC.MIB->createNoop(Instruction); 1293 if (IsCondBranch) { 1294 // Register branch offset for profile validation. 1295 IgnoredBranches.emplace_back(Offset, Offset + Size); 1296 } 1297 goto add_instruction; 1298 } 1299 // May update Instruction and IsCall 1300 TargetSymbol = handleExternalReference(Instruction, Size, Offset, 1301 TargetAddress, IsCall); 1302 } 1303 } 1304 1305 if (!IsCall) { 1306 // Add taken branch info. 1307 TakenBranches.emplace_back(Offset, TargetAddress - getAddress()); 1308 } 1309 BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx); 1310 1311 // Mark CTC. 1312 if (IsCondBranch && IsCall) 1313 MIB->setConditionalTailCall(Instruction, TargetAddress); 1314 } else { 1315 // Could not evaluate branch. Should be an indirect call or an 1316 // indirect branch. Bail out on the latter case. 1317 if (MIB->isIndirectBranch(Instruction)) 1318 handleIndirectBranch(Instruction, Size, Offset); 1319 // Indirect call. We only need to fix it if the operand is RIP-relative. 1320 if (IsSimple && MIB->hasPCRelOperand(Instruction)) 1321 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size); 1322 1323 if (BC.isAArch64()) 1324 handleAArch64IndirectCall(Instruction, Offset); 1325 } 1326 } else if (BC.isAArch64() || BC.isRISCV()) { 1327 // Check if there's a relocation associated with this instruction. 1328 bool UsedReloc = false; 1329 for (auto Itr = Relocations.lower_bound(Offset), 1330 ItrE = Relocations.lower_bound(Offset + Size); 1331 Itr != ItrE; ++Itr) { 1332 const Relocation &Relocation = Itr->second; 1333 int64_t Value = Relocation.Value; 1334 const bool Result = BC.MIB->replaceImmWithSymbolRef( 1335 Instruction, Relocation.Symbol, Relocation.Addend, Ctx.get(), Value, 1336 Relocation.Type); 1337 (void)Result; 1338 assert(Result && "cannot replace immediate with relocation"); 1339 1340 // For aarch64, if we replaced an immediate with a symbol from a 1341 // relocation, we mark it so we do not try to further process a 1342 // pc-relative operand. All we need is the symbol. 1343 UsedReloc = true; 1344 } 1345 1346 if (!BC.isRISCV() && MIB->hasPCRelOperand(Instruction) && !UsedReloc) 1347 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size); 1348 } 1349 1350 add_instruction: 1351 if (getDWARFLineTable()) { 1352 Instruction.setLoc(findDebugLineInformationForInstructionAt( 1353 AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable())); 1354 } 1355 1356 // Record offset of the instruction for profile matching. 1357 if (BC.keepOffsetForInstruction(Instruction)) 1358 MIB->setOffset(Instruction, static_cast<uint32_t>(Offset)); 1359 1360 if (BC.MIB->isNoop(Instruction)) { 1361 // NOTE: disassembly loses the correct size information for noops. 1362 // E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only 1363 // 5 bytes. Preserve the size info using annotations. 1364 MIB->addAnnotation(Instruction, "Size", static_cast<uint32_t>(Size)); 1365 } 1366 1367 addInstruction(Offset, std::move(Instruction)); 1368 } 1369 1370 // Reset symbolizer for the disassembler. 1371 BC.SymbolicDisAsm->setSymbolizer(nullptr); 1372 1373 if (uint64_t Offset = getFirstInstructionOffset()) 1374 Labels[Offset] = BC.Ctx->createNamedTempSymbol(); 1375 1376 clearList(Relocations); 1377 1378 if (!IsSimple) { 1379 clearList(Instructions); 1380 return false; 1381 } 1382 1383 updateState(State::Disassembled); 1384 1385 return true; 1386 } 1387 1388 bool BinaryFunction::scanExternalRefs() { 1389 bool Success = true; 1390 bool DisassemblyFailed = false; 1391 1392 // Ignore pseudo functions. 1393 if (isPseudo()) 1394 return Success; 1395 1396 if (opts::NoScan) { 1397 clearList(Relocations); 1398 clearList(ExternallyReferencedOffsets); 1399 1400 return false; 1401 } 1402 1403 // List of external references for this function. 1404 std::vector<Relocation> FunctionRelocations; 1405 1406 static BinaryContext::IndependentCodeEmitter Emitter = 1407 BC.createIndependentMCCodeEmitter(); 1408 1409 ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData(); 1410 assert(ErrorOrFunctionData && "function data is not available"); 1411 ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData; 1412 assert(FunctionData.size() == getMaxSize() && 1413 "function size does not match raw data size"); 1414 1415 BC.SymbolicDisAsm->setSymbolizer( 1416 BC.MIB->createTargetSymbolizer(*this, /*CreateSymbols*/ false)); 1417 1418 // Disassemble contents of the function. Detect code entry points and create 1419 // relocations for references to code that will be moved. 1420 uint64_t Size = 0; // instruction size 1421 for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) { 1422 // Check for data inside code and ignore it 1423 if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) { 1424 Size = DataInCodeSize; 1425 continue; 1426 } 1427 1428 const uint64_t AbsoluteInstrAddr = getAddress() + Offset; 1429 MCInst Instruction; 1430 if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size, 1431 FunctionData.slice(Offset), 1432 AbsoluteInstrAddr, nulls())) { 1433 if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) { 1434 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x" 1435 << Twine::utohexstr(Offset) << " (address 0x" 1436 << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " 1437 << *this << '\n'; 1438 } 1439 Success = false; 1440 DisassemblyFailed = true; 1441 break; 1442 } 1443 1444 // Return true if we can skip handling the Target function reference. 1445 auto ignoreFunctionRef = [&](const BinaryFunction &Target) { 1446 if (&Target == this) 1447 return true; 1448 1449 // Note that later we may decide not to emit Target function. In that 1450 // case, we conservatively create references that will be ignored or 1451 // resolved to the same function. 1452 if (!BC.shouldEmit(Target)) 1453 return true; 1454 1455 return false; 1456 }; 1457 1458 // Return true if we can ignore reference to the symbol. 1459 auto ignoreReference = [&](const MCSymbol *TargetSymbol) { 1460 if (!TargetSymbol) 1461 return true; 1462 1463 if (BC.forceSymbolRelocations(TargetSymbol->getName())) 1464 return false; 1465 1466 BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol); 1467 if (!TargetFunction) 1468 return true; 1469 1470 return ignoreFunctionRef(*TargetFunction); 1471 }; 1472 1473 // Handle calls and branches separately as symbolization doesn't work for 1474 // them yet. 1475 MCSymbol *BranchTargetSymbol = nullptr; 1476 if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) { 1477 uint64_t TargetAddress = 0; 1478 BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size, 1479 TargetAddress); 1480 1481 // Create an entry point at reference address if needed. 1482 BinaryFunction *TargetFunction = 1483 BC.getBinaryFunctionContainingAddress(TargetAddress); 1484 1485 if (!TargetFunction || ignoreFunctionRef(*TargetFunction)) 1486 continue; 1487 1488 const uint64_t FunctionOffset = 1489 TargetAddress - TargetFunction->getAddress(); 1490 BranchTargetSymbol = 1491 FunctionOffset ? TargetFunction->addEntryPointAtOffset(FunctionOffset) 1492 : TargetFunction->getSymbol(); 1493 } 1494 1495 // Can't find more references. Not creating relocations since we are not 1496 // moving code. 1497 if (!BC.HasRelocations) 1498 continue; 1499 1500 if (BranchTargetSymbol) { 1501 BC.MIB->replaceBranchTarget(Instruction, BranchTargetSymbol, 1502 Emitter.LocalCtx.get()); 1503 } else if (!llvm::any_of(Instruction, 1504 [](const MCOperand &Op) { return Op.isExpr(); })) { 1505 // Skip assembly if the instruction may not have any symbolic operands. 1506 continue; 1507 } 1508 1509 // Emit the instruction using temp emitter and generate relocations. 1510 SmallString<256> Code; 1511 SmallVector<MCFixup, 4> Fixups; 1512 Emitter.MCE->encodeInstruction(Instruction, Code, Fixups, *BC.STI); 1513 1514 // Create relocation for every fixup. 1515 for (const MCFixup &Fixup : Fixups) { 1516 std::optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB); 1517 if (!Rel) { 1518 Success = false; 1519 continue; 1520 } 1521 1522 if (ignoreReference(Rel->Symbol)) 1523 continue; 1524 1525 if (Relocation::getSizeForType(Rel->Type) < 4) { 1526 // If the instruction uses a short form, then we might not be able 1527 // to handle the rewrite without relaxation, and hence cannot reliably 1528 // create an external reference relocation. 1529 Success = false; 1530 continue; 1531 } 1532 Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset; 1533 FunctionRelocations.push_back(*Rel); 1534 } 1535 1536 if (!Success) 1537 break; 1538 } 1539 1540 // Reset symbolizer for the disassembler. 1541 BC.SymbolicDisAsm->setSymbolizer(nullptr); 1542 1543 // Add relocations unless disassembly failed for this function. 1544 if (!DisassemblyFailed) 1545 for (Relocation &Rel : FunctionRelocations) 1546 getOriginSection()->addPendingRelocation(Rel); 1547 1548 // Inform BinaryContext that this function symbols will not be defined and 1549 // relocations should not be created against them. 1550 if (BC.HasRelocations) { 1551 for (std::pair<const uint32_t, MCSymbol *> &LI : Labels) 1552 BC.UndefinedSymbols.insert(LI.second); 1553 for (MCSymbol *const EndLabel : FunctionEndLabels) 1554 if (EndLabel) 1555 BC.UndefinedSymbols.insert(EndLabel); 1556 } 1557 1558 clearList(Relocations); 1559 clearList(ExternallyReferencedOffsets); 1560 1561 if (Success && BC.HasRelocations) 1562 HasExternalRefRelocations = true; 1563 1564 if (opts::Verbosity >= 1 && !Success) 1565 outs() << "BOLT-INFO: failed to scan refs for " << *this << '\n'; 1566 1567 return Success; 1568 } 1569 1570 void BinaryFunction::postProcessEntryPoints() { 1571 if (!isSimple()) 1572 return; 1573 1574 for (auto &KV : Labels) { 1575 MCSymbol *Label = KV.second; 1576 if (!getSecondaryEntryPointSymbol(Label)) 1577 continue; 1578 1579 // In non-relocation mode there's potentially an external undetectable 1580 // reference to the entry point and hence we cannot move this entry 1581 // point. Optimizing without moving could be difficult. 1582 if (!BC.HasRelocations) 1583 setSimple(false); 1584 1585 const uint32_t Offset = KV.first; 1586 1587 // If we are at Offset 0 and there is no instruction associated with it, 1588 // this means this is an empty function. Just ignore. If we find an 1589 // instruction at this offset, this entry point is valid. 1590 if (!Offset || getInstructionAtOffset(Offset)) 1591 continue; 1592 1593 // On AArch64 there are legitimate reasons to have references past the 1594 // end of the function, e.g. jump tables. 1595 if (BC.isAArch64() && Offset == getSize()) 1596 continue; 1597 1598 errs() << "BOLT-WARNING: reference in the middle of instruction " 1599 "detected in function " 1600 << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n'; 1601 if (BC.HasRelocations) 1602 setIgnored(); 1603 setSimple(false); 1604 return; 1605 } 1606 } 1607 1608 void BinaryFunction::postProcessJumpTables() { 1609 // Create labels for all entries. 1610 for (auto &JTI : JumpTables) { 1611 JumpTable &JT = *JTI.second; 1612 if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) { 1613 opts::JumpTables = JTS_MOVE; 1614 outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was " 1615 "detected in function " 1616 << *this << '\n'; 1617 } 1618 const uint64_t BDSize = 1619 BC.getBinaryDataAtAddress(JT.getAddress())->getSize(); 1620 if (!BDSize) { 1621 BC.setBinaryDataSize(JT.getAddress(), JT.getSize()); 1622 } else { 1623 assert(BDSize >= JT.getSize() && 1624 "jump table cannot be larger than the containing object"); 1625 } 1626 if (!JT.Entries.empty()) 1627 continue; 1628 1629 bool HasOneParent = (JT.Parents.size() == 1); 1630 for (uint64_t EntryAddress : JT.EntriesAsAddress) { 1631 // builtin_unreachable does not belong to any function 1632 // Need to handle separately 1633 bool IsBuiltinUnreachable = 1634 llvm::any_of(JT.Parents, [&](const BinaryFunction *Parent) { 1635 return EntryAddress == Parent->getAddress() + Parent->getSize(); 1636 }); 1637 if (IsBuiltinUnreachable) { 1638 MCSymbol *Label = getOrCreateLocalLabel(EntryAddress, true); 1639 JT.Entries.push_back(Label); 1640 continue; 1641 } 1642 // Create local label for targets cannot be reached by other fragments 1643 // Otherwise, secondary entry point to target function 1644 BinaryFunction *TargetBF = 1645 BC.getBinaryFunctionContainingAddress(EntryAddress); 1646 if (uint64_t Offset = EntryAddress - TargetBF->getAddress()) { 1647 MCSymbol *Label = (HasOneParent && TargetBF == this) 1648 ? getOrCreateLocalLabel(EntryAddress, true) 1649 : TargetBF->addEntryPointAtOffset(Offset); 1650 JT.Entries.push_back(Label); 1651 } 1652 } 1653 } 1654 1655 // Add TakenBranches from JumpTables. 1656 // 1657 // We want to do it after initial processing since we don't know jump tables' 1658 // boundaries until we process them all. 1659 for (auto &JTSite : JTSites) { 1660 const uint64_t JTSiteOffset = JTSite.first; 1661 const uint64_t JTAddress = JTSite.second; 1662 const JumpTable *JT = getJumpTableContainingAddress(JTAddress); 1663 assert(JT && "cannot find jump table for address"); 1664 1665 uint64_t EntryOffset = JTAddress - JT->getAddress(); 1666 while (EntryOffset < JT->getSize()) { 1667 uint64_t EntryAddress = JT->EntriesAsAddress[EntryOffset / JT->EntrySize]; 1668 uint64_t TargetOffset = EntryAddress - getAddress(); 1669 if (TargetOffset < getSize()) { 1670 TakenBranches.emplace_back(JTSiteOffset, TargetOffset); 1671 1672 if (opts::StrictMode) 1673 registerReferencedOffset(TargetOffset); 1674 } 1675 1676 EntryOffset += JT->EntrySize; 1677 1678 // A label at the next entry means the end of this jump table. 1679 if (JT->Labels.count(EntryOffset)) 1680 break; 1681 } 1682 } 1683 clearList(JTSites); 1684 1685 // Conservatively populate all possible destinations for unknown indirect 1686 // branches. 1687 if (opts::StrictMode && hasInternalReference()) { 1688 for (uint64_t Offset : UnknownIndirectBranchOffsets) { 1689 for (uint64_t PossibleDestination : ExternallyReferencedOffsets) { 1690 // Ignore __builtin_unreachable(). 1691 if (PossibleDestination == getSize()) 1692 continue; 1693 TakenBranches.emplace_back(Offset, PossibleDestination); 1694 } 1695 } 1696 } 1697 1698 // Remove duplicates branches. We can get a bunch of them from jump tables. 1699 // Without doing jump table value profiling we don't have use for extra 1700 // (duplicate) branches. 1701 llvm::sort(TakenBranches); 1702 auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end()); 1703 TakenBranches.erase(NewEnd, TakenBranches.end()); 1704 } 1705 1706 bool BinaryFunction::validateExternallyReferencedOffsets() { 1707 SmallPtrSet<MCSymbol *, 4> JTTargets; 1708 for (const JumpTable *JT : llvm::make_second_range(JumpTables)) 1709 JTTargets.insert(JT->Entries.begin(), JT->Entries.end()); 1710 1711 bool HasUnclaimedReference = false; 1712 for (uint64_t Destination : ExternallyReferencedOffsets) { 1713 // Ignore __builtin_unreachable(). 1714 if (Destination == getSize()) 1715 continue; 1716 // Ignore constant islands 1717 if (isInConstantIsland(Destination + getAddress())) 1718 continue; 1719 1720 if (BinaryBasicBlock *BB = getBasicBlockAtOffset(Destination)) { 1721 // Check if the externally referenced offset is a recognized jump table 1722 // target. 1723 if (JTTargets.contains(BB->getLabel())) 1724 continue; 1725 1726 if (opts::Verbosity >= 1) { 1727 errs() << "BOLT-WARNING: unclaimed data to code reference (possibly " 1728 << "an unrecognized jump table entry) to " << BB->getName() 1729 << " in " << *this << "\n"; 1730 } 1731 auto L = BC.scopeLock(); 1732 addEntryPoint(*BB); 1733 } else { 1734 errs() << "BOLT-WARNING: unknown data to code reference to offset " 1735 << Twine::utohexstr(Destination) << " in " << *this << "\n"; 1736 setIgnored(); 1737 } 1738 HasUnclaimedReference = true; 1739 } 1740 return !HasUnclaimedReference; 1741 } 1742 1743 bool BinaryFunction::postProcessIndirectBranches( 1744 MCPlusBuilder::AllocatorIdTy AllocId) { 1745 auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) { 1746 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding unknown control flow in " << *this 1747 << " for " << BB.getName() << "\n"); 1748 HasUnknownControlFlow = true; 1749 BB.removeAllSuccessors(); 1750 for (uint64_t PossibleDestination : ExternallyReferencedOffsets) 1751 if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination)) 1752 BB.addSuccessor(SuccBB); 1753 }; 1754 1755 uint64_t NumIndirectJumps = 0; 1756 MCInst *LastIndirectJump = nullptr; 1757 BinaryBasicBlock *LastIndirectJumpBB = nullptr; 1758 uint64_t LastJT = 0; 1759 uint16_t LastJTIndexReg = BC.MIB->getNoRegister(); 1760 for (BinaryBasicBlock &BB : blocks()) { 1761 for (MCInst &Instr : BB) { 1762 if (!BC.MIB->isIndirectBranch(Instr)) 1763 continue; 1764 1765 // If there's an indirect branch in a single-block function - 1766 // it must be a tail call. 1767 if (BasicBlocks.size() == 1) { 1768 BC.MIB->convertJmpToTailCall(Instr); 1769 return true; 1770 } 1771 1772 ++NumIndirectJumps; 1773 1774 if (opts::StrictMode && !hasInternalReference()) { 1775 BC.MIB->convertJmpToTailCall(Instr); 1776 break; 1777 } 1778 1779 // Validate the tail call or jump table assumptions now that we know 1780 // basic block boundaries. 1781 if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) { 1782 const unsigned PtrSize = BC.AsmInfo->getCodePointerSize(); 1783 MCInst *MemLocInstr; 1784 unsigned BaseRegNum, IndexRegNum; 1785 int64_t DispValue; 1786 const MCExpr *DispExpr; 1787 MCInst *PCRelBaseInstr; 1788 IndirectBranchType Type = BC.MIB->analyzeIndirectBranch( 1789 Instr, BB.begin(), BB.end(), PtrSize, MemLocInstr, BaseRegNum, 1790 IndexRegNum, DispValue, DispExpr, PCRelBaseInstr); 1791 if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr) 1792 continue; 1793 1794 if (!opts::StrictMode) 1795 return false; 1796 1797 if (BC.MIB->isTailCall(Instr)) { 1798 BC.MIB->convertTailCallToJmp(Instr); 1799 } else { 1800 LastIndirectJump = &Instr; 1801 LastIndirectJumpBB = &BB; 1802 LastJT = BC.MIB->getJumpTable(Instr); 1803 LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr); 1804 BC.MIB->unsetJumpTable(Instr); 1805 1806 JumpTable *JT = BC.getJumpTableContainingAddress(LastJT); 1807 if (JT->Type == JumpTable::JTT_NORMAL) { 1808 // Invalidating the jump table may also invalidate other jump table 1809 // boundaries. Until we have/need a support for this, mark the 1810 // function as non-simple. 1811 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference" 1812 << JT->getName() << " in " << *this << '\n'); 1813 return false; 1814 } 1815 } 1816 1817 addUnknownControlFlow(BB); 1818 continue; 1819 } 1820 1821 // If this block contains an epilogue code and has an indirect branch, 1822 // then most likely it's a tail call. Otherwise, we cannot tell for sure 1823 // what it is and conservatively reject the function's CFG. 1824 bool IsEpilogue = llvm::any_of(BB, [&](const MCInst &Instr) { 1825 return BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr); 1826 }); 1827 if (IsEpilogue) { 1828 BC.MIB->convertJmpToTailCall(Instr); 1829 BB.removeAllSuccessors(); 1830 continue; 1831 } 1832 1833 if (opts::Verbosity >= 2) { 1834 outs() << "BOLT-INFO: rejected potential indirect tail call in " 1835 << "function " << *this << " in basic block " << BB.getName() 1836 << ".\n"; 1837 LLVM_DEBUG(BC.printInstructions(dbgs(), BB.begin(), BB.end(), 1838 BB.getOffset(), this, true)); 1839 } 1840 1841 if (!opts::StrictMode) 1842 return false; 1843 1844 addUnknownControlFlow(BB); 1845 } 1846 } 1847 1848 if (HasInternalLabelReference) 1849 return false; 1850 1851 // If there's only one jump table, and one indirect jump, and no other 1852 // references, then we should be able to derive the jump table even if we 1853 // fail to match the pattern. 1854 if (HasUnknownControlFlow && NumIndirectJumps == 1 && 1855 JumpTables.size() == 1 && LastIndirectJump && 1856 !BC.getJumpTableContainingAddress(LastJT)->IsSplit) { 1857 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: unsetting unknown control flow in " 1858 << *this << '\n'); 1859 BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId); 1860 HasUnknownControlFlow = false; 1861 1862 LastIndirectJumpBB->updateJumpTableSuccessors(); 1863 } 1864 1865 if (HasFixedIndirectBranch) 1866 return false; 1867 1868 // Validate that all data references to function offsets are claimed by 1869 // recognized jump tables. Register externally referenced blocks as entry 1870 // points. 1871 if (!opts::StrictMode && hasInternalReference()) { 1872 if (!validateExternallyReferencedOffsets()) 1873 return false; 1874 } 1875 1876 if (HasUnknownControlFlow && !BC.HasRelocations) 1877 return false; 1878 1879 return true; 1880 } 1881 1882 void BinaryFunction::recomputeLandingPads() { 1883 updateBBIndices(0); 1884 1885 for (BinaryBasicBlock *BB : BasicBlocks) { 1886 BB->LandingPads.clear(); 1887 BB->Throwers.clear(); 1888 } 1889 1890 for (BinaryBasicBlock *BB : BasicBlocks) { 1891 std::unordered_set<const BinaryBasicBlock *> BBLandingPads; 1892 for (MCInst &Instr : *BB) { 1893 if (!BC.MIB->isInvoke(Instr)) 1894 continue; 1895 1896 const std::optional<MCPlus::MCLandingPad> EHInfo = 1897 BC.MIB->getEHInfo(Instr); 1898 if (!EHInfo || !EHInfo->first) 1899 continue; 1900 1901 BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first); 1902 if (!BBLandingPads.count(LPBlock)) { 1903 BBLandingPads.insert(LPBlock); 1904 BB->LandingPads.emplace_back(LPBlock); 1905 LPBlock->Throwers.emplace_back(BB); 1906 } 1907 } 1908 } 1909 } 1910 1911 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) { 1912 auto &MIB = BC.MIB; 1913 1914 if (!isSimple()) { 1915 assert(!BC.HasRelocations && 1916 "cannot process file with non-simple function in relocs mode"); 1917 return false; 1918 } 1919 1920 if (CurrentState != State::Disassembled) 1921 return false; 1922 1923 assert(BasicBlocks.empty() && "basic block list should be empty"); 1924 assert((Labels.find(getFirstInstructionOffset()) != Labels.end()) && 1925 "first instruction should always have a label"); 1926 1927 // Create basic blocks in the original layout order: 1928 // 1929 // * Every instruction with associated label marks 1930 // the beginning of a basic block. 1931 // * Conditional instruction marks the end of a basic block, 1932 // except when the following instruction is an 1933 // unconditional branch, and the unconditional branch is not 1934 // a destination of another branch. In the latter case, the 1935 // basic block will consist of a single unconditional branch 1936 // (missed "double-jump" optimization). 1937 // 1938 // Created basic blocks are sorted in layout order since they are 1939 // created in the same order as instructions, and instructions are 1940 // sorted by offsets. 1941 BinaryBasicBlock *InsertBB = nullptr; 1942 BinaryBasicBlock *PrevBB = nullptr; 1943 bool IsLastInstrNop = false; 1944 // Offset of the last non-nop instruction. 1945 uint64_t LastInstrOffset = 0; 1946 1947 auto addCFIPlaceholders = [this](uint64_t CFIOffset, 1948 BinaryBasicBlock *InsertBB) { 1949 for (auto FI = OffsetToCFI.lower_bound(CFIOffset), 1950 FE = OffsetToCFI.upper_bound(CFIOffset); 1951 FI != FE; ++FI) { 1952 addCFIPseudo(InsertBB, InsertBB->end(), FI->second); 1953 } 1954 }; 1955 1956 // For profiling purposes we need to save the offset of the last instruction 1957 // in the basic block. 1958 // NOTE: nops always have an Offset annotation. Annotate the last non-nop as 1959 // older profiles ignored nops. 1960 auto updateOffset = [&](uint64_t Offset) { 1961 assert(PrevBB && PrevBB != InsertBB && "invalid previous block"); 1962 MCInst *LastNonNop = nullptr; 1963 for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(), 1964 E = PrevBB->rend(); 1965 RII != E; ++RII) { 1966 if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) { 1967 LastNonNop = &*RII; 1968 break; 1969 } 1970 } 1971 if (LastNonNop && !MIB->getOffset(*LastNonNop)) 1972 MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId); 1973 }; 1974 1975 for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) { 1976 const uint32_t Offset = I->first; 1977 MCInst &Instr = I->second; 1978 1979 auto LI = Labels.find(Offset); 1980 if (LI != Labels.end()) { 1981 // Always create new BB at branch destination. 1982 PrevBB = InsertBB ? InsertBB : PrevBB; 1983 InsertBB = addBasicBlockAt(LI->first, LI->second); 1984 if (opts::PreserveBlocksAlignment && IsLastInstrNop) 1985 InsertBB->setDerivedAlignment(); 1986 1987 if (PrevBB) 1988 updateOffset(LastInstrOffset); 1989 } 1990 1991 bool IsLKMarker = BC.LKMarkers.count(I->first + Address); 1992 // Mark all nops with Offset for profile tracking purposes. 1993 if (MIB->isNoop(Instr) || IsLKMarker) { 1994 // If "Offset" annotation is not present, set it and mark the nop for 1995 // deletion. 1996 if (!MIB->getOffset(Instr)) { 1997 MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId); 1998 // Annotate ordinary nops, so we can safely delete them if required. 1999 if (!IsLKMarker) 2000 MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), 2001 AllocatorId); 2002 } 2003 if (IsLKMarker) 2004 HasSDTMarker = true; 2005 } 2006 2007 if (!InsertBB) { 2008 // It must be a fallthrough or unreachable code. Create a new block unless 2009 // we see an unconditional branch following a conditional one. The latter 2010 // should not be a conditional tail call. 2011 assert(PrevBB && "no previous basic block for a fall through"); 2012 MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr(); 2013 assert(PrevInstr && "no previous instruction for a fall through"); 2014 if (MIB->isUnconditionalBranch(Instr) && 2015 !MIB->isIndirectBranch(*PrevInstr) && 2016 !MIB->isUnconditionalBranch(*PrevInstr) && 2017 !MIB->getConditionalTailCall(*PrevInstr) && 2018 !MIB->isReturn(*PrevInstr)) { 2019 // Temporarily restore inserter basic block. 2020 InsertBB = PrevBB; 2021 } else { 2022 MCSymbol *Label; 2023 { 2024 auto L = BC.scopeLock(); 2025 Label = BC.Ctx->createNamedTempSymbol("FT"); 2026 } 2027 InsertBB = addBasicBlockAt(Offset, Label); 2028 if (opts::PreserveBlocksAlignment && IsLastInstrNop) 2029 InsertBB->setDerivedAlignment(); 2030 updateOffset(LastInstrOffset); 2031 } 2032 } 2033 if (Offset == getFirstInstructionOffset()) { 2034 // Add associated CFI pseudos in the first offset 2035 addCFIPlaceholders(Offset, InsertBB); 2036 } 2037 2038 const bool IsBlockEnd = MIB->isTerminator(Instr); 2039 IsLastInstrNop = MIB->isNoop(Instr); 2040 if (!IsLastInstrNop) 2041 LastInstrOffset = Offset; 2042 InsertBB->addInstruction(std::move(Instr)); 2043 2044 // Add associated CFI instrs. We always add the CFI instruction that is 2045 // located immediately after this instruction, since the next CFI 2046 // instruction reflects the change in state caused by this instruction. 2047 auto NextInstr = std::next(I); 2048 uint64_t CFIOffset; 2049 if (NextInstr != E) 2050 CFIOffset = NextInstr->first; 2051 else 2052 CFIOffset = getSize(); 2053 2054 // Note: this potentially invalidates instruction pointers/iterators. 2055 addCFIPlaceholders(CFIOffset, InsertBB); 2056 2057 if (IsBlockEnd) { 2058 PrevBB = InsertBB; 2059 InsertBB = nullptr; 2060 } 2061 } 2062 2063 if (BasicBlocks.empty()) { 2064 setSimple(false); 2065 return false; 2066 } 2067 2068 // Intermediate dump. 2069 LLVM_DEBUG(print(dbgs(), "after creating basic blocks")); 2070 2071 // TODO: handle properly calls to no-return functions, 2072 // e.g. exit(3), etc. Otherwise we'll see a false fall-through 2073 // blocks. 2074 2075 for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) { 2076 LLVM_DEBUG(dbgs() << "registering branch [0x" 2077 << Twine::utohexstr(Branch.first) << "] -> [0x" 2078 << Twine::utohexstr(Branch.second) << "]\n"); 2079 BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first); 2080 BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second); 2081 if (!FromBB || !ToBB) { 2082 if (!FromBB) 2083 errs() << "BOLT-ERROR: cannot find BB containing the branch.\n"; 2084 if (!ToBB) 2085 errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n"; 2086 BC.exitWithBugReport("disassembly failed - inconsistent branch found.", 2087 *this); 2088 } 2089 2090 FromBB->addSuccessor(ToBB); 2091 } 2092 2093 // Add fall-through branches. 2094 PrevBB = nullptr; 2095 bool IsPrevFT = false; // Is previous block a fall-through. 2096 for (BinaryBasicBlock *BB : BasicBlocks) { 2097 if (IsPrevFT) 2098 PrevBB->addSuccessor(BB); 2099 2100 if (BB->empty()) { 2101 IsPrevFT = true; 2102 PrevBB = BB; 2103 continue; 2104 } 2105 2106 MCInst *LastInstr = BB->getLastNonPseudoInstr(); 2107 assert(LastInstr && 2108 "should have non-pseudo instruction in non-empty block"); 2109 2110 if (BB->succ_size() == 0) { 2111 // Since there's no existing successors, we know the last instruction is 2112 // not a conditional branch. Thus if it's a terminator, it shouldn't be a 2113 // fall-through. 2114 // 2115 // Conditional tail call is a special case since we don't add a taken 2116 // branch successor for it. 2117 IsPrevFT = !MIB->isTerminator(*LastInstr) || 2118 MIB->getConditionalTailCall(*LastInstr); 2119 } else if (BB->succ_size() == 1) { 2120 IsPrevFT = MIB->isConditionalBranch(*LastInstr); 2121 } else { 2122 IsPrevFT = false; 2123 } 2124 2125 PrevBB = BB; 2126 } 2127 2128 // Assign landing pads and throwers info. 2129 recomputeLandingPads(); 2130 2131 // Assign CFI information to each BB entry. 2132 annotateCFIState(); 2133 2134 // Annotate invoke instructions with GNU_args_size data. 2135 propagateGnuArgsSizeInfo(AllocatorId); 2136 2137 // Set the basic block layout to the original order and set end offsets. 2138 PrevBB = nullptr; 2139 for (BinaryBasicBlock *BB : BasicBlocks) { 2140 Layout.addBasicBlock(BB); 2141 if (PrevBB) 2142 PrevBB->setEndOffset(BB->getOffset()); 2143 PrevBB = BB; 2144 } 2145 PrevBB->setEndOffset(getSize()); 2146 2147 Layout.updateLayoutIndices(); 2148 2149 normalizeCFIState(); 2150 2151 // Clean-up memory taken by intermediate structures. 2152 // 2153 // NB: don't clear Labels list as we may need them if we mark the function 2154 // as non-simple later in the process of discovering extra entry points. 2155 clearList(Instructions); 2156 clearList(OffsetToCFI); 2157 clearList(TakenBranches); 2158 2159 // Update the state. 2160 CurrentState = State::CFG; 2161 2162 // Make any necessary adjustments for indirect branches. 2163 if (!postProcessIndirectBranches(AllocatorId)) { 2164 if (opts::Verbosity) { 2165 errs() << "BOLT-WARNING: failed to post-process indirect branches for " 2166 << *this << '\n'; 2167 } 2168 // In relocation mode we want to keep processing the function but avoid 2169 // optimizing it. 2170 setSimple(false); 2171 } 2172 2173 clearList(ExternallyReferencedOffsets); 2174 clearList(UnknownIndirectBranchOffsets); 2175 2176 return true; 2177 } 2178 2179 void BinaryFunction::postProcessCFG() { 2180 if (isSimple() && !BasicBlocks.empty()) { 2181 // Convert conditional tail call branches to conditional branches that jump 2182 // to a tail call. 2183 removeConditionalTailCalls(); 2184 2185 postProcessProfile(); 2186 2187 // Eliminate inconsistencies between branch instructions and CFG. 2188 postProcessBranches(); 2189 } 2190 2191 calculateMacroOpFusionStats(); 2192 2193 // The final cleanup of intermediate structures. 2194 clearList(IgnoredBranches); 2195 2196 // Remove "Offset" annotations, unless we need an address-translation table 2197 // later. This has no cost, since annotations are allocated by a bumpptr 2198 // allocator and won't be released anyway until late in the pipeline. 2199 if (!requiresAddressTranslation() && !opts::Instrument) { 2200 for (BinaryBasicBlock &BB : blocks()) 2201 for (MCInst &Inst : BB) 2202 BC.MIB->clearOffset(Inst); 2203 } 2204 2205 assert((!isSimple() || validateCFG()) && 2206 "invalid CFG detected after post-processing"); 2207 } 2208 2209 void BinaryFunction::calculateMacroOpFusionStats() { 2210 if (!getBinaryContext().isX86()) 2211 return; 2212 for (const BinaryBasicBlock &BB : blocks()) { 2213 auto II = BB.getMacroOpFusionPair(); 2214 if (II == BB.end()) 2215 continue; 2216 2217 // Check offset of the second instruction. 2218 // FIXME: arch-specific. 2219 const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0); 2220 if (!Offset || (getAddress() + Offset) % 64) 2221 continue; 2222 2223 LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x" 2224 << Twine::utohexstr(getAddress() + Offset) 2225 << " in function " << *this << "; executed " 2226 << BB.getKnownExecutionCount() << " times.\n"); 2227 ++BC.MissedMacroFusionPairs; 2228 BC.MissedMacroFusionExecCount += BB.getKnownExecutionCount(); 2229 } 2230 } 2231 2232 void BinaryFunction::removeTagsFromProfile() { 2233 for (BinaryBasicBlock *BB : BasicBlocks) { 2234 if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE) 2235 BB->ExecutionCount = 0; 2236 for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) { 2237 if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE && 2238 BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE) 2239 continue; 2240 BI.Count = 0; 2241 BI.MispredictedCount = 0; 2242 } 2243 } 2244 } 2245 2246 void BinaryFunction::removeConditionalTailCalls() { 2247 // Blocks to be appended at the end. 2248 std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks; 2249 2250 for (auto BBI = begin(); BBI != end(); ++BBI) { 2251 BinaryBasicBlock &BB = *BBI; 2252 MCInst *CTCInstr = BB.getLastNonPseudoInstr(); 2253 if (!CTCInstr) 2254 continue; 2255 2256 std::optional<uint64_t> TargetAddressOrNone = 2257 BC.MIB->getConditionalTailCall(*CTCInstr); 2258 if (!TargetAddressOrNone) 2259 continue; 2260 2261 // Gather all necessary information about CTC instruction before 2262 // annotations are destroyed. 2263 const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr); 2264 uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE; 2265 uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE; 2266 if (hasValidProfile()) { 2267 CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>( 2268 *CTCInstr, "CTCTakenCount"); 2269 CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>( 2270 *CTCInstr, "CTCMispredCount"); 2271 } 2272 2273 // Assert that the tail call does not throw. 2274 assert(!BC.MIB->getEHInfo(*CTCInstr) && 2275 "found tail call with associated landing pad"); 2276 2277 // Create a basic block with an unconditional tail call instruction using 2278 // the same destination. 2279 const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr); 2280 assert(CTCTargetLabel && "symbol expected for conditional tail call"); 2281 MCInst TailCallInstr; 2282 BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get()); 2283 // Link new BBs to the original input offset of the BB where the CTC 2284 // is, so we can map samples recorded in new BBs back to the original BB 2285 // seem in the input binary (if using BAT) 2286 std::unique_ptr<BinaryBasicBlock> TailCallBB = 2287 createBasicBlock(BC.Ctx->createNamedTempSymbol("TC")); 2288 TailCallBB->setOffset(BB.getInputOffset()); 2289 TailCallBB->addInstruction(TailCallInstr); 2290 TailCallBB->setCFIState(CFIStateBeforeCTC); 2291 2292 // Add CFG edge with profile info from BB to TailCallBB. 2293 BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount); 2294 2295 // Add execution count for the block. 2296 TailCallBB->setExecutionCount(CTCTakenCount); 2297 2298 BC.MIB->convertTailCallToJmp(*CTCInstr); 2299 2300 BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(), 2301 BC.Ctx.get()); 2302 2303 // Add basic block to the list that will be added to the end. 2304 NewBlocks.emplace_back(std::move(TailCallBB)); 2305 2306 // Swap edges as the TailCallBB corresponds to the taken branch. 2307 BB.swapConditionalSuccessors(); 2308 2309 // This branch is no longer a conditional tail call. 2310 BC.MIB->unsetConditionalTailCall(*CTCInstr); 2311 } 2312 2313 insertBasicBlocks(std::prev(end()), std::move(NewBlocks), 2314 /* UpdateLayout */ true, 2315 /* UpdateCFIState */ false); 2316 } 2317 2318 uint64_t BinaryFunction::getFunctionScore() const { 2319 if (FunctionScore != -1) 2320 return FunctionScore; 2321 2322 if (!isSimple() || !hasValidProfile()) { 2323 FunctionScore = 0; 2324 return FunctionScore; 2325 } 2326 2327 uint64_t TotalScore = 0ULL; 2328 for (const BinaryBasicBlock &BB : blocks()) { 2329 uint64_t BBExecCount = BB.getExecutionCount(); 2330 if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE) 2331 continue; 2332 TotalScore += BBExecCount * BB.getNumNonPseudos(); 2333 } 2334 FunctionScore = TotalScore; 2335 return FunctionScore; 2336 } 2337 2338 void BinaryFunction::annotateCFIState() { 2339 assert(CurrentState == State::Disassembled && "unexpected function state"); 2340 assert(!BasicBlocks.empty() && "basic block list should not be empty"); 2341 2342 // This is an index of the last processed CFI in FDE CFI program. 2343 uint32_t State = 0; 2344 2345 // This is an index of RememberState CFI reflecting effective state right 2346 // after execution of RestoreState CFI. 2347 // 2348 // It differs from State iff the CFI at (State-1) 2349 // was RestoreState (modulo GNU_args_size CFIs, which are ignored). 2350 // 2351 // This allows us to generate shorter replay sequences when producing new 2352 // CFI programs. 2353 uint32_t EffectiveState = 0; 2354 2355 // For tracking RememberState/RestoreState sequences. 2356 std::stack<uint32_t> StateStack; 2357 2358 for (BinaryBasicBlock *BB : BasicBlocks) { 2359 BB->setCFIState(EffectiveState); 2360 2361 for (const MCInst &Instr : *BB) { 2362 const MCCFIInstruction *CFI = getCFIFor(Instr); 2363 if (!CFI) 2364 continue; 2365 2366 ++State; 2367 2368 switch (CFI->getOperation()) { 2369 case MCCFIInstruction::OpRememberState: 2370 StateStack.push(EffectiveState); 2371 EffectiveState = State; 2372 break; 2373 case MCCFIInstruction::OpRestoreState: 2374 assert(!StateStack.empty() && "corrupt CFI stack"); 2375 EffectiveState = StateStack.top(); 2376 StateStack.pop(); 2377 break; 2378 case MCCFIInstruction::OpGnuArgsSize: 2379 // OpGnuArgsSize CFIs do not affect the CFI state. 2380 break; 2381 default: 2382 // Any other CFI updates the state. 2383 EffectiveState = State; 2384 break; 2385 } 2386 } 2387 } 2388 2389 assert(StateStack.empty() && "corrupt CFI stack"); 2390 } 2391 2392 namespace { 2393 2394 /// Our full interpretation of a DWARF CFI machine state at a given point 2395 struct CFISnapshot { 2396 /// CFA register number and offset defining the canonical frame at this 2397 /// point, or the number of a rule (CFI state) that computes it with a 2398 /// DWARF expression. This number will be negative if it refers to a CFI 2399 /// located in the CIE instead of the FDE. 2400 uint32_t CFAReg; 2401 int32_t CFAOffset; 2402 int32_t CFARule; 2403 /// Mapping of rules (CFI states) that define the location of each 2404 /// register. If absent, no rule defining the location of such register 2405 /// was ever read. This number will be negative if it refers to a CFI 2406 /// located in the CIE instead of the FDE. 2407 DenseMap<int32_t, int32_t> RegRule; 2408 2409 /// References to CIE, FDE and expanded instructions after a restore state 2410 const BinaryFunction::CFIInstrMapType &CIE; 2411 const BinaryFunction::CFIInstrMapType &FDE; 2412 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents; 2413 2414 /// Current FDE CFI number representing the state where the snapshot is at 2415 int32_t CurState; 2416 2417 /// Used when we don't have information about which state/rule to apply 2418 /// to recover the location of either the CFA or a specific register 2419 constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min(); 2420 2421 private: 2422 /// Update our snapshot by executing a single CFI 2423 void update(const MCCFIInstruction &Instr, int32_t RuleNumber) { 2424 switch (Instr.getOperation()) { 2425 case MCCFIInstruction::OpSameValue: 2426 case MCCFIInstruction::OpRelOffset: 2427 case MCCFIInstruction::OpOffset: 2428 case MCCFIInstruction::OpRestore: 2429 case MCCFIInstruction::OpUndefined: 2430 case MCCFIInstruction::OpRegister: 2431 RegRule[Instr.getRegister()] = RuleNumber; 2432 break; 2433 case MCCFIInstruction::OpDefCfaRegister: 2434 CFAReg = Instr.getRegister(); 2435 CFARule = UNKNOWN; 2436 break; 2437 case MCCFIInstruction::OpDefCfaOffset: 2438 CFAOffset = Instr.getOffset(); 2439 CFARule = UNKNOWN; 2440 break; 2441 case MCCFIInstruction::OpDefCfa: 2442 CFAReg = Instr.getRegister(); 2443 CFAOffset = Instr.getOffset(); 2444 CFARule = UNKNOWN; 2445 break; 2446 case MCCFIInstruction::OpEscape: { 2447 std::optional<uint8_t> Reg = 2448 readDWARFExpressionTargetReg(Instr.getValues()); 2449 // Handle DW_CFA_def_cfa_expression 2450 if (!Reg) { 2451 CFARule = RuleNumber; 2452 break; 2453 } 2454 RegRule[*Reg] = RuleNumber; 2455 break; 2456 } 2457 case MCCFIInstruction::OpAdjustCfaOffset: 2458 case MCCFIInstruction::OpWindowSave: 2459 case MCCFIInstruction::OpNegateRAState: 2460 case MCCFIInstruction::OpLLVMDefAspaceCfa: 2461 llvm_unreachable("unsupported CFI opcode"); 2462 break; 2463 case MCCFIInstruction::OpRememberState: 2464 case MCCFIInstruction::OpRestoreState: 2465 case MCCFIInstruction::OpGnuArgsSize: 2466 // do not affect CFI state 2467 break; 2468 } 2469 } 2470 2471 public: 2472 /// Advance state reading FDE CFI instructions up to State number 2473 void advanceTo(int32_t State) { 2474 for (int32_t I = CurState, E = State; I != E; ++I) { 2475 const MCCFIInstruction &Instr = FDE[I]; 2476 if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) { 2477 update(Instr, I); 2478 continue; 2479 } 2480 // If restore state instruction, fetch the equivalent CFIs that have 2481 // the same effect of this restore. This is used to ensure remember- 2482 // restore pairs are completely removed. 2483 auto Iter = FrameRestoreEquivalents.find(I); 2484 if (Iter == FrameRestoreEquivalents.end()) 2485 continue; 2486 for (int32_t RuleNumber : Iter->second) 2487 update(FDE[RuleNumber], RuleNumber); 2488 } 2489 2490 assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) || 2491 CFARule != UNKNOWN) && 2492 "CIE did not define default CFA?"); 2493 2494 CurState = State; 2495 } 2496 2497 /// Interpret all CIE and FDE instructions up until CFI State number and 2498 /// populate this snapshot 2499 CFISnapshot( 2500 const BinaryFunction::CFIInstrMapType &CIE, 2501 const BinaryFunction::CFIInstrMapType &FDE, 2502 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents, 2503 int32_t State) 2504 : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) { 2505 CFAReg = UNKNOWN; 2506 CFAOffset = UNKNOWN; 2507 CFARule = UNKNOWN; 2508 CurState = 0; 2509 2510 for (int32_t I = 0, E = CIE.size(); I != E; ++I) { 2511 const MCCFIInstruction &Instr = CIE[I]; 2512 update(Instr, -I); 2513 } 2514 2515 advanceTo(State); 2516 } 2517 }; 2518 2519 /// A CFI snapshot with the capability of checking if incremental additions to 2520 /// it are redundant. This is used to ensure we do not emit two CFI instructions 2521 /// back-to-back that are doing the same state change, or to avoid emitting a 2522 /// CFI at all when the state at that point would not be modified after that CFI 2523 struct CFISnapshotDiff : public CFISnapshot { 2524 bool RestoredCFAReg{false}; 2525 bool RestoredCFAOffset{false}; 2526 DenseMap<int32_t, bool> RestoredRegs; 2527 2528 CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {} 2529 2530 CFISnapshotDiff( 2531 const BinaryFunction::CFIInstrMapType &CIE, 2532 const BinaryFunction::CFIInstrMapType &FDE, 2533 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents, 2534 int32_t State) 2535 : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {} 2536 2537 /// Return true if applying Instr to this state is redundant and can be 2538 /// dismissed. 2539 bool isRedundant(const MCCFIInstruction &Instr) { 2540 switch (Instr.getOperation()) { 2541 case MCCFIInstruction::OpSameValue: 2542 case MCCFIInstruction::OpRelOffset: 2543 case MCCFIInstruction::OpOffset: 2544 case MCCFIInstruction::OpRestore: 2545 case MCCFIInstruction::OpUndefined: 2546 case MCCFIInstruction::OpRegister: 2547 case MCCFIInstruction::OpEscape: { 2548 uint32_t Reg; 2549 if (Instr.getOperation() != MCCFIInstruction::OpEscape) { 2550 Reg = Instr.getRegister(); 2551 } else { 2552 std::optional<uint8_t> R = 2553 readDWARFExpressionTargetReg(Instr.getValues()); 2554 // Handle DW_CFA_def_cfa_expression 2555 if (!R) { 2556 if (RestoredCFAReg && RestoredCFAOffset) 2557 return true; 2558 RestoredCFAReg = true; 2559 RestoredCFAOffset = true; 2560 return false; 2561 } 2562 Reg = *R; 2563 } 2564 if (RestoredRegs[Reg]) 2565 return true; 2566 RestoredRegs[Reg] = true; 2567 const int32_t CurRegRule = RegRule.contains(Reg) ? RegRule[Reg] : UNKNOWN; 2568 if (CurRegRule == UNKNOWN) { 2569 if (Instr.getOperation() == MCCFIInstruction::OpRestore || 2570 Instr.getOperation() == MCCFIInstruction::OpSameValue) 2571 return true; 2572 return false; 2573 } 2574 const MCCFIInstruction &LastDef = 2575 CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule]; 2576 return LastDef == Instr; 2577 } 2578 case MCCFIInstruction::OpDefCfaRegister: 2579 if (RestoredCFAReg) 2580 return true; 2581 RestoredCFAReg = true; 2582 return CFAReg == Instr.getRegister(); 2583 case MCCFIInstruction::OpDefCfaOffset: 2584 if (RestoredCFAOffset) 2585 return true; 2586 RestoredCFAOffset = true; 2587 return CFAOffset == Instr.getOffset(); 2588 case MCCFIInstruction::OpDefCfa: 2589 if (RestoredCFAReg && RestoredCFAOffset) 2590 return true; 2591 RestoredCFAReg = true; 2592 RestoredCFAOffset = true; 2593 return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset(); 2594 case MCCFIInstruction::OpAdjustCfaOffset: 2595 case MCCFIInstruction::OpWindowSave: 2596 case MCCFIInstruction::OpNegateRAState: 2597 case MCCFIInstruction::OpLLVMDefAspaceCfa: 2598 llvm_unreachable("unsupported CFI opcode"); 2599 return false; 2600 case MCCFIInstruction::OpRememberState: 2601 case MCCFIInstruction::OpRestoreState: 2602 case MCCFIInstruction::OpGnuArgsSize: 2603 // do not affect CFI state 2604 return true; 2605 } 2606 return false; 2607 } 2608 }; 2609 2610 } // end anonymous namespace 2611 2612 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState, 2613 BinaryBasicBlock *InBB, 2614 BinaryBasicBlock::iterator InsertIt) { 2615 if (FromState == ToState) 2616 return true; 2617 assert(FromState < ToState && "can only replay CFIs forward"); 2618 2619 CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions, 2620 FrameRestoreEquivalents, FromState); 2621 2622 std::vector<uint32_t> NewCFIs; 2623 for (int32_t CurState = FromState; CurState < ToState; ++CurState) { 2624 MCCFIInstruction *Instr = &FrameInstructions[CurState]; 2625 if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) { 2626 auto Iter = FrameRestoreEquivalents.find(CurState); 2627 assert(Iter != FrameRestoreEquivalents.end()); 2628 NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end()); 2629 // RestoreState / Remember will be filtered out later by CFISnapshotDiff, 2630 // so we might as well fall-through here. 2631 } 2632 NewCFIs.push_back(CurState); 2633 } 2634 2635 // Replay instructions while avoiding duplicates 2636 for (int32_t State : llvm::reverse(NewCFIs)) { 2637 if (CFIDiff.isRedundant(FrameInstructions[State])) 2638 continue; 2639 InsertIt = addCFIPseudo(InBB, InsertIt, State); 2640 } 2641 2642 return true; 2643 } 2644 2645 SmallVector<int32_t, 4> 2646 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState, 2647 BinaryBasicBlock *InBB, 2648 BinaryBasicBlock::iterator &InsertIt) { 2649 SmallVector<int32_t, 4> NewStates; 2650 2651 CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions, 2652 FrameRestoreEquivalents, ToState); 2653 CFISnapshotDiff FromCFITable(ToCFITable); 2654 FromCFITable.advanceTo(FromState); 2655 2656 auto undoStateDefCfa = [&]() { 2657 if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) { 2658 FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa( 2659 nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset)); 2660 if (FromCFITable.isRedundant(FrameInstructions.back())) { 2661 FrameInstructions.pop_back(); 2662 return; 2663 } 2664 NewStates.push_back(FrameInstructions.size() - 1); 2665 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1); 2666 ++InsertIt; 2667 } else if (ToCFITable.CFARule < 0) { 2668 if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule])) 2669 return; 2670 NewStates.push_back(FrameInstructions.size()); 2671 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size()); 2672 ++InsertIt; 2673 FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]); 2674 } else if (!FromCFITable.isRedundant( 2675 FrameInstructions[ToCFITable.CFARule])) { 2676 NewStates.push_back(ToCFITable.CFARule); 2677 InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule); 2678 ++InsertIt; 2679 } 2680 }; 2681 2682 auto undoState = [&](const MCCFIInstruction &Instr) { 2683 switch (Instr.getOperation()) { 2684 case MCCFIInstruction::OpRememberState: 2685 case MCCFIInstruction::OpRestoreState: 2686 break; 2687 case MCCFIInstruction::OpSameValue: 2688 case MCCFIInstruction::OpRelOffset: 2689 case MCCFIInstruction::OpOffset: 2690 case MCCFIInstruction::OpRestore: 2691 case MCCFIInstruction::OpUndefined: 2692 case MCCFIInstruction::OpEscape: 2693 case MCCFIInstruction::OpRegister: { 2694 uint32_t Reg; 2695 if (Instr.getOperation() != MCCFIInstruction::OpEscape) { 2696 Reg = Instr.getRegister(); 2697 } else { 2698 std::optional<uint8_t> R = 2699 readDWARFExpressionTargetReg(Instr.getValues()); 2700 // Handle DW_CFA_def_cfa_expression 2701 if (!R) { 2702 undoStateDefCfa(); 2703 return; 2704 } 2705 Reg = *R; 2706 } 2707 2708 if (!ToCFITable.RegRule.contains(Reg)) { 2709 FrameInstructions.emplace_back( 2710 MCCFIInstruction::createRestore(nullptr, Reg)); 2711 if (FromCFITable.isRedundant(FrameInstructions.back())) { 2712 FrameInstructions.pop_back(); 2713 break; 2714 } 2715 NewStates.push_back(FrameInstructions.size() - 1); 2716 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1); 2717 ++InsertIt; 2718 break; 2719 } 2720 const int32_t Rule = ToCFITable.RegRule[Reg]; 2721 if (Rule < 0) { 2722 if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule])) 2723 break; 2724 NewStates.push_back(FrameInstructions.size()); 2725 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size()); 2726 ++InsertIt; 2727 FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]); 2728 break; 2729 } 2730 if (FromCFITable.isRedundant(FrameInstructions[Rule])) 2731 break; 2732 NewStates.push_back(Rule); 2733 InsertIt = addCFIPseudo(InBB, InsertIt, Rule); 2734 ++InsertIt; 2735 break; 2736 } 2737 case MCCFIInstruction::OpDefCfaRegister: 2738 case MCCFIInstruction::OpDefCfaOffset: 2739 case MCCFIInstruction::OpDefCfa: 2740 undoStateDefCfa(); 2741 break; 2742 case MCCFIInstruction::OpAdjustCfaOffset: 2743 case MCCFIInstruction::OpWindowSave: 2744 case MCCFIInstruction::OpNegateRAState: 2745 case MCCFIInstruction::OpLLVMDefAspaceCfa: 2746 llvm_unreachable("unsupported CFI opcode"); 2747 break; 2748 case MCCFIInstruction::OpGnuArgsSize: 2749 // do not affect CFI state 2750 break; 2751 } 2752 }; 2753 2754 // Undo all modifications from ToState to FromState 2755 for (int32_t I = ToState, E = FromState; I != E; ++I) { 2756 const MCCFIInstruction &Instr = FrameInstructions[I]; 2757 if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) { 2758 undoState(Instr); 2759 continue; 2760 } 2761 auto Iter = FrameRestoreEquivalents.find(I); 2762 if (Iter == FrameRestoreEquivalents.end()) 2763 continue; 2764 for (int32_t State : Iter->second) 2765 undoState(FrameInstructions[State]); 2766 } 2767 2768 return NewStates; 2769 } 2770 2771 void BinaryFunction::normalizeCFIState() { 2772 // Reordering blocks with remember-restore state instructions can be specially 2773 // tricky. When rewriting the CFI, we omit remember-restore state instructions 2774 // entirely. For restore state, we build a map expanding each restore to the 2775 // equivalent unwindCFIState sequence required at that point to achieve the 2776 // same effect of the restore. All remember state are then just ignored. 2777 std::stack<int32_t> Stack; 2778 for (BinaryBasicBlock *CurBB : Layout.blocks()) { 2779 for (auto II = CurBB->begin(); II != CurBB->end(); ++II) { 2780 if (const MCCFIInstruction *CFI = getCFIFor(*II)) { 2781 if (CFI->getOperation() == MCCFIInstruction::OpRememberState) { 2782 Stack.push(II->getOperand(0).getImm()); 2783 continue; 2784 } 2785 if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) { 2786 const int32_t RememberState = Stack.top(); 2787 const int32_t CurState = II->getOperand(0).getImm(); 2788 FrameRestoreEquivalents[CurState] = 2789 unwindCFIState(CurState, RememberState, CurBB, II); 2790 Stack.pop(); 2791 } 2792 } 2793 } 2794 } 2795 } 2796 2797 bool BinaryFunction::finalizeCFIState() { 2798 LLVM_DEBUG( 2799 dbgs() << "Trying to fix CFI states for each BB after reordering.\n"); 2800 LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this 2801 << ": "); 2802 2803 const char *Sep = ""; 2804 (void)Sep; 2805 for (FunctionFragment &FF : Layout.fragments()) { 2806 // Hot-cold border: at start of each region (with a different FDE) we need 2807 // to reset the CFI state. 2808 int32_t State = 0; 2809 2810 for (BinaryBasicBlock *BB : FF) { 2811 const int32_t CFIStateAtExit = BB->getCFIStateAtExit(); 2812 2813 // We need to recover the correct state if it doesn't match expected 2814 // state at BB entry point. 2815 if (BB->getCFIState() < State) { 2816 // In this case, State is currently higher than what this BB expect it 2817 // to be. To solve this, we need to insert CFI instructions to undo 2818 // the effect of all CFI from BB's state to current State. 2819 auto InsertIt = BB->begin(); 2820 unwindCFIState(State, BB->getCFIState(), BB, InsertIt); 2821 } else if (BB->getCFIState() > State) { 2822 // If BB's CFI state is greater than State, it means we are behind in 2823 // the state. Just emit all instructions to reach this state at the 2824 // beginning of this BB. If this sequence of instructions involve 2825 // remember state or restore state, bail out. 2826 if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin())) 2827 return false; 2828 } 2829 2830 State = CFIStateAtExit; 2831 LLVM_DEBUG(dbgs() << Sep << State; Sep = ", "); 2832 } 2833 } 2834 LLVM_DEBUG(dbgs() << "\n"); 2835 2836 for (BinaryBasicBlock &BB : blocks()) { 2837 for (auto II = BB.begin(); II != BB.end();) { 2838 const MCCFIInstruction *CFI = getCFIFor(*II); 2839 if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState || 2840 CFI->getOperation() == MCCFIInstruction::OpRestoreState)) { 2841 II = BB.eraseInstruction(II); 2842 } else { 2843 ++II; 2844 } 2845 } 2846 } 2847 2848 return true; 2849 } 2850 2851 bool BinaryFunction::requiresAddressTranslation() const { 2852 return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe(); 2853 } 2854 2855 uint64_t BinaryFunction::getInstructionCount() const { 2856 uint64_t Count = 0; 2857 for (const BinaryBasicBlock &BB : blocks()) 2858 Count += BB.getNumNonPseudos(); 2859 return Count; 2860 } 2861 2862 void BinaryFunction::clearDisasmState() { 2863 clearList(Instructions); 2864 clearList(IgnoredBranches); 2865 clearList(TakenBranches); 2866 2867 if (BC.HasRelocations) { 2868 for (std::pair<const uint32_t, MCSymbol *> &LI : Labels) 2869 BC.UndefinedSymbols.insert(LI.second); 2870 for (MCSymbol *const EndLabel : FunctionEndLabels) 2871 if (EndLabel) 2872 BC.UndefinedSymbols.insert(EndLabel); 2873 } 2874 } 2875 2876 void BinaryFunction::setTrapOnEntry() { 2877 clearDisasmState(); 2878 2879 forEachEntryPoint([&](uint64_t Offset, const MCSymbol *Label) -> bool { 2880 MCInst TrapInstr; 2881 BC.MIB->createTrap(TrapInstr); 2882 addInstruction(Offset, std::move(TrapInstr)); 2883 return true; 2884 }); 2885 2886 TrapsOnEntry = true; 2887 } 2888 2889 void BinaryFunction::setIgnored() { 2890 if (opts::processAllFunctions()) { 2891 // We can accept ignored functions before they've been disassembled. 2892 // In that case, they would still get disassembled and emited, but not 2893 // optimized. 2894 assert(CurrentState == State::Empty && 2895 "cannot ignore non-empty functions in current mode"); 2896 IsIgnored = true; 2897 return; 2898 } 2899 2900 clearDisasmState(); 2901 2902 // Clear CFG state too. 2903 if (hasCFG()) { 2904 releaseCFG(); 2905 2906 for (BinaryBasicBlock *BB : BasicBlocks) 2907 delete BB; 2908 clearList(BasicBlocks); 2909 2910 for (BinaryBasicBlock *BB : DeletedBasicBlocks) 2911 delete BB; 2912 clearList(DeletedBasicBlocks); 2913 2914 Layout.clear(); 2915 } 2916 2917 CurrentState = State::Empty; 2918 2919 IsIgnored = true; 2920 IsSimple = false; 2921 LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n'); 2922 } 2923 2924 void BinaryFunction::duplicateConstantIslands() { 2925 assert(Islands && "function expected to have constant islands"); 2926 2927 for (BinaryBasicBlock *BB : getLayout().blocks()) { 2928 if (!BB->isCold()) 2929 continue; 2930 2931 for (MCInst &Inst : *BB) { 2932 int OpNum = 0; 2933 for (MCOperand &Operand : Inst) { 2934 if (!Operand.isExpr()) { 2935 ++OpNum; 2936 continue; 2937 } 2938 const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum); 2939 // Check if this is an island symbol 2940 if (!Islands->Symbols.count(Symbol) && 2941 !Islands->ProxySymbols.count(Symbol)) 2942 continue; 2943 2944 // Create cold symbol, if missing 2945 auto ISym = Islands->ColdSymbols.find(Symbol); 2946 MCSymbol *ColdSymbol; 2947 if (ISym != Islands->ColdSymbols.end()) { 2948 ColdSymbol = ISym->second; 2949 } else { 2950 ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold"); 2951 Islands->ColdSymbols[Symbol] = ColdSymbol; 2952 // Check if this is a proxy island symbol and update owner proxy map 2953 if (Islands->ProxySymbols.count(Symbol)) { 2954 BinaryFunction *Owner = Islands->ProxySymbols[Symbol]; 2955 auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol); 2956 Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol; 2957 } 2958 } 2959 2960 // Update instruction reference 2961 Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor( 2962 Inst, 2963 MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None, 2964 *BC.Ctx), 2965 *BC.Ctx, 0)); 2966 ++OpNum; 2967 } 2968 } 2969 } 2970 } 2971 2972 #ifndef MAX_PATH 2973 #define MAX_PATH 255 2974 #endif 2975 2976 static std::string constructFilename(std::string Filename, 2977 std::string Annotation, 2978 std::string Suffix) { 2979 std::replace(Filename.begin(), Filename.end(), '/', '-'); 2980 if (!Annotation.empty()) 2981 Annotation.insert(0, "-"); 2982 if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) { 2983 assert(Suffix.size() + Annotation.size() <= MAX_PATH); 2984 if (opts::Verbosity >= 1) { 2985 errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix 2986 << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n"; 2987 } 2988 Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size())); 2989 } 2990 Filename += Annotation; 2991 Filename += Suffix; 2992 return Filename; 2993 } 2994 2995 static std::string formatEscapes(const std::string &Str) { 2996 std::string Result; 2997 for (unsigned I = 0; I < Str.size(); ++I) { 2998 char C = Str[I]; 2999 switch (C) { 3000 case '\n': 3001 Result += " "; 3002 break; 3003 case '"': 3004 break; 3005 default: 3006 Result += C; 3007 break; 3008 } 3009 } 3010 return Result; 3011 } 3012 3013 void BinaryFunction::dumpGraph(raw_ostream &OS) const { 3014 OS << "digraph \"" << getPrintName() << "\" {\n" 3015 << "node [fontname=courier, shape=box, style=filled, colorscheme=brbg9]\n"; 3016 uint64_t Offset = Address; 3017 for (BinaryBasicBlock *BB : BasicBlocks) { 3018 auto LayoutPos = find(Layout.blocks(), BB); 3019 unsigned LayoutIndex = LayoutPos - Layout.block_begin(); 3020 const char *ColdStr = BB->isCold() ? " (cold)" : ""; 3021 std::vector<std::string> Attrs; 3022 // Bold box for entry points 3023 if (isEntryPoint(*BB)) 3024 Attrs.push_back("penwidth=2"); 3025 if (BLI && BLI->getLoopFor(BB)) { 3026 // Distinguish innermost loops 3027 const BinaryLoop *Loop = BLI->getLoopFor(BB); 3028 if (Loop->isInnermost()) 3029 Attrs.push_back("fillcolor=6"); 3030 else // some outer loop 3031 Attrs.push_back("fillcolor=4"); 3032 } else { // non-loopy code 3033 Attrs.push_back("fillcolor=5"); 3034 } 3035 ListSeparator LS; 3036 OS << "\"" << BB->getName() << "\" ["; 3037 for (StringRef Attr : Attrs) 3038 OS << LS << Attr; 3039 OS << "]\n"; 3040 OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u,CFI:%u)\\n", 3041 BB->getName().data(), BB->getName().data(), ColdStr, 3042 BB->getKnownExecutionCount(), BB->getOffset(), getIndex(BB), 3043 LayoutIndex, BB->getCFIState()); 3044 3045 if (opts::DotToolTipCode) { 3046 std::string Str; 3047 raw_string_ostream CS(Str); 3048 Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this, 3049 /* PrintMCInst = */ false, 3050 /* PrintMemData = */ false, 3051 /* PrintRelocations = */ false, 3052 /* Endl = */ R"(\\l)"); 3053 OS << formatEscapes(CS.str()) << '\n'; 3054 } 3055 OS << "\"]\n"; 3056 3057 // analyzeBranch is just used to get the names of the branch 3058 // opcodes. 3059 const MCSymbol *TBB = nullptr; 3060 const MCSymbol *FBB = nullptr; 3061 MCInst *CondBranch = nullptr; 3062 MCInst *UncondBranch = nullptr; 3063 const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch); 3064 3065 const MCInst *LastInstr = BB->getLastNonPseudoInstr(); 3066 const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr); 3067 3068 auto BI = BB->branch_info_begin(); 3069 for (BinaryBasicBlock *Succ : BB->successors()) { 3070 std::string Branch; 3071 if (Success) { 3072 if (Succ == BB->getConditionalSuccessor(true)) { 3073 Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName( 3074 CondBranch->getOpcode())) 3075 : "TB"; 3076 } else if (Succ == BB->getConditionalSuccessor(false)) { 3077 Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName( 3078 UncondBranch->getOpcode())) 3079 : "FB"; 3080 } else { 3081 Branch = "FT"; 3082 } 3083 } 3084 if (IsJumpTable) 3085 Branch = "JT"; 3086 OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(), 3087 Succ->getName().data(), Branch.c_str()); 3088 3089 if (BB->getExecutionCount() != COUNT_NO_PROFILE && 3090 BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) { 3091 OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")"; 3092 } else if (ExecutionCount != COUNT_NO_PROFILE && 3093 BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) { 3094 OS << "\\n(IC:" << BI->Count << ")"; 3095 } 3096 OS << "\"]\n"; 3097 3098 ++BI; 3099 } 3100 for (BinaryBasicBlock *LP : BB->landing_pads()) { 3101 OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n", 3102 BB->getName().data(), LP->getName().data()); 3103 } 3104 } 3105 OS << "}\n"; 3106 } 3107 3108 void BinaryFunction::viewGraph() const { 3109 SmallString<MAX_PATH> Filename; 3110 if (std::error_code EC = 3111 sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) { 3112 errs() << "BOLT-ERROR: " << EC.message() << ", unable to create " 3113 << " bolt-cfg-XXXXX.dot temporary file.\n"; 3114 return; 3115 } 3116 dumpGraphToFile(std::string(Filename)); 3117 if (DisplayGraph(Filename)) 3118 errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n"; 3119 if (std::error_code EC = sys::fs::remove(Filename)) { 3120 errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove " 3121 << Filename << "\n"; 3122 } 3123 } 3124 3125 void BinaryFunction::dumpGraphForPass(std::string Annotation) const { 3126 if (!opts::shouldPrint(*this)) 3127 return; 3128 3129 std::string Filename = constructFilename(getPrintName(), Annotation, ".dot"); 3130 if (opts::Verbosity >= 1) 3131 outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n"; 3132 dumpGraphToFile(Filename); 3133 } 3134 3135 void BinaryFunction::dumpGraphToFile(std::string Filename) const { 3136 std::error_code EC; 3137 raw_fd_ostream of(Filename, EC, sys::fs::OF_None); 3138 if (EC) { 3139 if (opts::Verbosity >= 1) { 3140 errs() << "BOLT-WARNING: " << EC.message() << ", unable to open " 3141 << Filename << " for output.\n"; 3142 } 3143 return; 3144 } 3145 dumpGraph(of); 3146 } 3147 3148 bool BinaryFunction::validateCFG() const { 3149 bool Valid = true; 3150 for (BinaryBasicBlock *BB : BasicBlocks) 3151 Valid &= BB->validateSuccessorInvariants(); 3152 3153 if (!Valid) 3154 return Valid; 3155 3156 // Make sure all blocks in CFG are valid. 3157 auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) { 3158 if (!BB->isValid()) { 3159 errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName() 3160 << " detected in:\n"; 3161 this->dump(); 3162 return false; 3163 } 3164 return true; 3165 }; 3166 for (const BinaryBasicBlock *BB : BasicBlocks) { 3167 if (!validateBlock(BB, "block")) 3168 return false; 3169 for (const BinaryBasicBlock *PredBB : BB->predecessors()) 3170 if (!validateBlock(PredBB, "predecessor")) 3171 return false; 3172 for (const BinaryBasicBlock *SuccBB : BB->successors()) 3173 if (!validateBlock(SuccBB, "successor")) 3174 return false; 3175 for (const BinaryBasicBlock *LP : BB->landing_pads()) 3176 if (!validateBlock(LP, "landing pad")) 3177 return false; 3178 for (const BinaryBasicBlock *Thrower : BB->throwers()) 3179 if (!validateBlock(Thrower, "thrower")) 3180 return false; 3181 } 3182 3183 for (const BinaryBasicBlock *BB : BasicBlocks) { 3184 std::unordered_set<const BinaryBasicBlock *> BBLandingPads; 3185 for (const BinaryBasicBlock *LP : BB->landing_pads()) { 3186 if (BBLandingPads.count(LP)) { 3187 errs() << "BOLT-ERROR: duplicate landing pad detected in" 3188 << BB->getName() << " in function " << *this << '\n'; 3189 return false; 3190 } 3191 BBLandingPads.insert(LP); 3192 } 3193 3194 std::unordered_set<const BinaryBasicBlock *> BBThrowers; 3195 for (const BinaryBasicBlock *Thrower : BB->throwers()) { 3196 if (BBThrowers.count(Thrower)) { 3197 errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName() 3198 << " in function " << *this << '\n'; 3199 return false; 3200 } 3201 BBThrowers.insert(Thrower); 3202 } 3203 3204 for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) { 3205 if (!llvm::is_contained(LPBlock->throwers(), BB)) { 3206 errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this 3207 << ": " << BB->getName() << " is in LandingPads but not in " 3208 << LPBlock->getName() << " Throwers\n"; 3209 return false; 3210 } 3211 } 3212 for (const BinaryBasicBlock *Thrower : BB->throwers()) { 3213 if (!llvm::is_contained(Thrower->landing_pads(), BB)) { 3214 errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this 3215 << ": " << BB->getName() << " is in Throwers list but not in " 3216 << Thrower->getName() << " LandingPads\n"; 3217 return false; 3218 } 3219 } 3220 } 3221 3222 return Valid; 3223 } 3224 3225 void BinaryFunction::fixBranches() { 3226 auto &MIB = BC.MIB; 3227 MCContext *Ctx = BC.Ctx.get(); 3228 3229 for (BinaryBasicBlock *BB : BasicBlocks) { 3230 const MCSymbol *TBB = nullptr; 3231 const MCSymbol *FBB = nullptr; 3232 MCInst *CondBranch = nullptr; 3233 MCInst *UncondBranch = nullptr; 3234 if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch)) 3235 continue; 3236 3237 // We will create unconditional branch with correct destination if needed. 3238 if (UncondBranch) 3239 BB->eraseInstruction(BB->findInstruction(UncondBranch)); 3240 3241 // Basic block that follows the current one in the final layout. 3242 const BinaryBasicBlock *NextBB = 3243 Layout.getBasicBlockAfter(BB, /*IgnoreSplits=*/false); 3244 3245 if (BB->succ_size() == 1) { 3246 // __builtin_unreachable() could create a conditional branch that 3247 // falls-through into the next function - hence the block will have only 3248 // one valid successor. Since behaviour is undefined - we replace 3249 // the conditional branch with an unconditional if required. 3250 if (CondBranch) 3251 BB->eraseInstruction(BB->findInstruction(CondBranch)); 3252 if (BB->getSuccessor() == NextBB) 3253 continue; 3254 BB->addBranchInstruction(BB->getSuccessor()); 3255 } else if (BB->succ_size() == 2) { 3256 assert(CondBranch && "conditional branch expected"); 3257 const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true); 3258 const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false); 3259 // Check whether we support reversing this branch direction 3260 const bool IsSupported = !MIB->isUnsupportedBranch(*CondBranch); 3261 if (NextBB && NextBB == TSuccessor && IsSupported) { 3262 std::swap(TSuccessor, FSuccessor); 3263 { 3264 auto L = BC.scopeLock(); 3265 MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx); 3266 } 3267 BB->swapConditionalSuccessors(); 3268 } else { 3269 auto L = BC.scopeLock(); 3270 MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx); 3271 } 3272 if (TSuccessor == FSuccessor) 3273 BB->removeDuplicateConditionalSuccessor(CondBranch); 3274 if (!NextBB || 3275 ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) { 3276 // If one of the branches is guaranteed to be "long" while the other 3277 // could be "short", then prioritize short for "taken". This will 3278 // generate a sequence 1 byte shorter on x86. 3279 if (IsSupported && BC.isX86() && 3280 TSuccessor->getFragmentNum() != FSuccessor->getFragmentNum() && 3281 BB->getFragmentNum() != TSuccessor->getFragmentNum()) { 3282 std::swap(TSuccessor, FSuccessor); 3283 { 3284 auto L = BC.scopeLock(); 3285 MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), 3286 Ctx); 3287 } 3288 BB->swapConditionalSuccessors(); 3289 } 3290 BB->addBranchInstruction(FSuccessor); 3291 } 3292 } 3293 // Cases where the number of successors is 0 (block ends with a 3294 // terminator) or more than 2 (switch table) don't require branch 3295 // instruction adjustments. 3296 } 3297 assert((!isSimple() || validateCFG()) && 3298 "Invalid CFG detected after fixing branches"); 3299 } 3300 3301 void BinaryFunction::propagateGnuArgsSizeInfo( 3302 MCPlusBuilder::AllocatorIdTy AllocId) { 3303 assert(CurrentState == State::Disassembled && "unexpected function state"); 3304 3305 if (!hasEHRanges() || !usesGnuArgsSize()) 3306 return; 3307 3308 // The current value of DW_CFA_GNU_args_size affects all following 3309 // invoke instructions until the next CFI overrides it. 3310 // It is important to iterate basic blocks in the original order when 3311 // assigning the value. 3312 uint64_t CurrentGnuArgsSize = 0; 3313 for (BinaryBasicBlock *BB : BasicBlocks) { 3314 for (auto II = BB->begin(); II != BB->end();) { 3315 MCInst &Instr = *II; 3316 if (BC.MIB->isCFI(Instr)) { 3317 const MCCFIInstruction *CFI = getCFIFor(Instr); 3318 if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) { 3319 CurrentGnuArgsSize = CFI->getOffset(); 3320 // Delete DW_CFA_GNU_args_size instructions and only regenerate 3321 // during the final code emission. The information is embedded 3322 // inside call instructions. 3323 II = BB->erasePseudoInstruction(II); 3324 continue; 3325 } 3326 } else if (BC.MIB->isInvoke(Instr)) { 3327 // Add the value of GNU_args_size as an extra operand to invokes. 3328 BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId); 3329 } 3330 ++II; 3331 } 3332 } 3333 } 3334 3335 void BinaryFunction::postProcessBranches() { 3336 if (!isSimple()) 3337 return; 3338 for (BinaryBasicBlock &BB : blocks()) { 3339 auto LastInstrRI = BB.getLastNonPseudo(); 3340 if (BB.succ_size() == 1) { 3341 if (LastInstrRI != BB.rend() && 3342 BC.MIB->isConditionalBranch(*LastInstrRI)) { 3343 // __builtin_unreachable() could create a conditional branch that 3344 // falls-through into the next function - hence the block will have only 3345 // one valid successor. Such behaviour is undefined and thus we remove 3346 // the conditional branch while leaving a valid successor. 3347 BB.eraseInstruction(std::prev(LastInstrRI.base())); 3348 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in " 3349 << BB.getName() << " in function " << *this << '\n'); 3350 } 3351 } else if (BB.succ_size() == 0) { 3352 // Ignore unreachable basic blocks. 3353 if (BB.pred_size() == 0 || BB.isLandingPad()) 3354 continue; 3355 3356 // If it's the basic block that does not end up with a terminator - we 3357 // insert a return instruction unless it's a call instruction. 3358 if (LastInstrRI == BB.rend()) { 3359 LLVM_DEBUG( 3360 dbgs() << "BOLT-DEBUG: at least one instruction expected in BB " 3361 << BB.getName() << " in function " << *this << '\n'); 3362 continue; 3363 } 3364 if (!BC.MIB->isTerminator(*LastInstrRI) && 3365 !BC.MIB->isCall(*LastInstrRI)) { 3366 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block " 3367 << BB.getName() << " in function " << *this << '\n'); 3368 MCInst ReturnInstr; 3369 BC.MIB->createReturn(ReturnInstr); 3370 BB.addInstruction(ReturnInstr); 3371 } 3372 } 3373 } 3374 assert(validateCFG() && "invalid CFG"); 3375 } 3376 3377 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) { 3378 assert(Offset && "cannot add primary entry point"); 3379 assert(CurrentState == State::Empty || CurrentState == State::Disassembled); 3380 3381 const uint64_t EntryPointAddress = getAddress() + Offset; 3382 MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress); 3383 3384 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol); 3385 if (EntrySymbol) 3386 return EntrySymbol; 3387 3388 if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) { 3389 EntrySymbol = EntryBD->getSymbol(); 3390 } else { 3391 EntrySymbol = BC.getOrCreateGlobalSymbol( 3392 EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@"); 3393 } 3394 SecondaryEntryPoints[LocalSymbol] = EntrySymbol; 3395 3396 BC.setSymbolToFunctionMap(EntrySymbol, this); 3397 3398 return EntrySymbol; 3399 } 3400 3401 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) { 3402 assert(CurrentState == State::CFG && 3403 "basic block can be added as an entry only in a function with CFG"); 3404 3405 if (&BB == BasicBlocks.front()) 3406 return getSymbol(); 3407 3408 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB); 3409 if (EntrySymbol) 3410 return EntrySymbol; 3411 3412 EntrySymbol = 3413 BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName()); 3414 3415 SecondaryEntryPoints[BB.getLabel()] = EntrySymbol; 3416 3417 BC.setSymbolToFunctionMap(EntrySymbol, this); 3418 3419 return EntrySymbol; 3420 } 3421 3422 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) { 3423 if (EntryID == 0) 3424 return getSymbol(); 3425 3426 if (!isMultiEntry()) 3427 return nullptr; 3428 3429 uint64_t NumEntries = 0; 3430 if (hasCFG()) { 3431 for (BinaryBasicBlock *BB : BasicBlocks) { 3432 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB); 3433 if (!EntrySymbol) 3434 continue; 3435 if (NumEntries == EntryID) 3436 return EntrySymbol; 3437 ++NumEntries; 3438 } 3439 } else { 3440 for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) { 3441 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second); 3442 if (!EntrySymbol) 3443 continue; 3444 if (NumEntries == EntryID) 3445 return EntrySymbol; 3446 ++NumEntries; 3447 } 3448 } 3449 3450 return nullptr; 3451 } 3452 3453 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const { 3454 if (!isMultiEntry()) 3455 return 0; 3456 3457 for (const MCSymbol *FunctionSymbol : getSymbols()) 3458 if (FunctionSymbol == Symbol) 3459 return 0; 3460 3461 // Check all secondary entries available as either basic blocks or lables. 3462 uint64_t NumEntries = 0; 3463 for (const BinaryBasicBlock *BB : BasicBlocks) { 3464 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB); 3465 if (!EntrySymbol) 3466 continue; 3467 if (EntrySymbol == Symbol) 3468 return NumEntries; 3469 ++NumEntries; 3470 } 3471 NumEntries = 0; 3472 for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) { 3473 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second); 3474 if (!EntrySymbol) 3475 continue; 3476 if (EntrySymbol == Symbol) 3477 return NumEntries; 3478 ++NumEntries; 3479 } 3480 3481 llvm_unreachable("symbol not found"); 3482 } 3483 3484 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const { 3485 bool Status = Callback(0, getSymbol()); 3486 if (!isMultiEntry()) 3487 return Status; 3488 3489 for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) { 3490 if (!Status) 3491 break; 3492 3493 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second); 3494 if (!EntrySymbol) 3495 continue; 3496 3497 Status = Callback(KV.first, EntrySymbol); 3498 } 3499 3500 return Status; 3501 } 3502 3503 BinaryFunction::BasicBlockListType BinaryFunction::dfs() const { 3504 BasicBlockListType DFS; 3505 unsigned Index = 0; 3506 std::stack<BinaryBasicBlock *> Stack; 3507 3508 // Push entry points to the stack in reverse order. 3509 // 3510 // NB: we rely on the original order of entries to match. 3511 SmallVector<BinaryBasicBlock *> EntryPoints; 3512 llvm::copy_if(BasicBlocks, std::back_inserter(EntryPoints), 3513 [&](const BinaryBasicBlock *const BB) { return isEntryPoint(*BB); }); 3514 // Sort entry points by their offset to make sure we got them in the right 3515 // order. 3516 llvm::stable_sort(EntryPoints, [](const BinaryBasicBlock *const A, 3517 const BinaryBasicBlock *const B) { 3518 return A->getOffset() < B->getOffset(); 3519 }); 3520 for (BinaryBasicBlock *const BB : reverse(EntryPoints)) 3521 Stack.push(BB); 3522 3523 for (BinaryBasicBlock &BB : blocks()) 3524 BB.setLayoutIndex(BinaryBasicBlock::InvalidIndex); 3525 3526 while (!Stack.empty()) { 3527 BinaryBasicBlock *BB = Stack.top(); 3528 Stack.pop(); 3529 3530 if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex) 3531 continue; 3532 3533 BB->setLayoutIndex(Index++); 3534 DFS.push_back(BB); 3535 3536 for (BinaryBasicBlock *SuccBB : BB->landing_pads()) { 3537 Stack.push(SuccBB); 3538 } 3539 3540 const MCSymbol *TBB = nullptr; 3541 const MCSymbol *FBB = nullptr; 3542 MCInst *CondBranch = nullptr; 3543 MCInst *UncondBranch = nullptr; 3544 if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch && 3545 BB->succ_size() == 2) { 3546 if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode( 3547 *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) { 3548 Stack.push(BB->getConditionalSuccessor(true)); 3549 Stack.push(BB->getConditionalSuccessor(false)); 3550 } else { 3551 Stack.push(BB->getConditionalSuccessor(false)); 3552 Stack.push(BB->getConditionalSuccessor(true)); 3553 } 3554 } else { 3555 for (BinaryBasicBlock *SuccBB : BB->successors()) { 3556 Stack.push(SuccBB); 3557 } 3558 } 3559 } 3560 3561 return DFS; 3562 } 3563 3564 size_t BinaryFunction::computeHash(bool UseDFS, 3565 OperandHashFuncTy OperandHashFunc) const { 3566 if (size() == 0) 3567 return 0; 3568 3569 assert(hasCFG() && "function is expected to have CFG"); 3570 3571 SmallVector<const BinaryBasicBlock *, 0> Order; 3572 if (UseDFS) 3573 llvm::copy(dfs(), std::back_inserter(Order)); 3574 else 3575 llvm::copy(Layout.blocks(), std::back_inserter(Order)); 3576 3577 // The hash is computed by creating a string of all instruction opcodes and 3578 // possibly their operands and then hashing that string with std::hash. 3579 std::string HashString; 3580 for (const BinaryBasicBlock *BB : Order) 3581 HashString.append(hashBlock(BC, *BB, OperandHashFunc)); 3582 3583 return Hash = std::hash<std::string>{}(HashString); 3584 } 3585 3586 void BinaryFunction::insertBasicBlocks( 3587 BinaryBasicBlock *Start, 3588 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs, 3589 const bool UpdateLayout, const bool UpdateCFIState, 3590 const bool RecomputeLandingPads) { 3591 const int64_t StartIndex = Start ? getIndex(Start) : -1LL; 3592 const size_t NumNewBlocks = NewBBs.size(); 3593 3594 BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks, 3595 nullptr); 3596 3597 int64_t I = StartIndex + 1; 3598 for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) { 3599 assert(!BasicBlocks[I]); 3600 BasicBlocks[I++] = BB.release(); 3601 } 3602 3603 if (RecomputeLandingPads) 3604 recomputeLandingPads(); 3605 else 3606 updateBBIndices(0); 3607 3608 if (UpdateLayout) 3609 updateLayout(Start, NumNewBlocks); 3610 3611 if (UpdateCFIState) 3612 updateCFIState(Start, NumNewBlocks); 3613 } 3614 3615 BinaryFunction::iterator BinaryFunction::insertBasicBlocks( 3616 BinaryFunction::iterator StartBB, 3617 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs, 3618 const bool UpdateLayout, const bool UpdateCFIState, 3619 const bool RecomputeLandingPads) { 3620 const unsigned StartIndex = getIndex(&*StartBB); 3621 const size_t NumNewBlocks = NewBBs.size(); 3622 3623 BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks, 3624 nullptr); 3625 auto RetIter = BasicBlocks.begin() + StartIndex + 1; 3626 3627 unsigned I = StartIndex + 1; 3628 for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) { 3629 assert(!BasicBlocks[I]); 3630 BasicBlocks[I++] = BB.release(); 3631 } 3632 3633 if (RecomputeLandingPads) 3634 recomputeLandingPads(); 3635 else 3636 updateBBIndices(0); 3637 3638 if (UpdateLayout) 3639 updateLayout(*std::prev(RetIter), NumNewBlocks); 3640 3641 if (UpdateCFIState) 3642 updateCFIState(*std::prev(RetIter), NumNewBlocks); 3643 3644 return RetIter; 3645 } 3646 3647 void BinaryFunction::updateBBIndices(const unsigned StartIndex) { 3648 for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I) 3649 BasicBlocks[I]->Index = I; 3650 } 3651 3652 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start, 3653 const unsigned NumNewBlocks) { 3654 const int32_t CFIState = Start->getCFIStateAtExit(); 3655 const unsigned StartIndex = getIndex(Start) + 1; 3656 for (unsigned I = 0; I < NumNewBlocks; ++I) 3657 BasicBlocks[StartIndex + I]->setCFIState(CFIState); 3658 } 3659 3660 void BinaryFunction::updateLayout(BinaryBasicBlock *Start, 3661 const unsigned NumNewBlocks) { 3662 BasicBlockListType::iterator Begin; 3663 BasicBlockListType::iterator End; 3664 3665 // If start not provided copy new blocks from the beginning of BasicBlocks 3666 if (!Start) { 3667 Begin = BasicBlocks.begin(); 3668 End = BasicBlocks.begin() + NumNewBlocks; 3669 } else { 3670 unsigned StartIndex = getIndex(Start); 3671 Begin = std::next(BasicBlocks.begin(), StartIndex + 1); 3672 End = std::next(BasicBlocks.begin(), StartIndex + NumNewBlocks + 1); 3673 } 3674 3675 // Insert new blocks in the layout immediately after Start. 3676 Layout.insertBasicBlocks(Start, {Begin, End}); 3677 Layout.updateLayoutIndices(); 3678 } 3679 3680 bool BinaryFunction::checkForAmbiguousJumpTables() { 3681 SmallSet<uint64_t, 4> JumpTables; 3682 for (BinaryBasicBlock *&BB : BasicBlocks) { 3683 for (MCInst &Inst : *BB) { 3684 if (!BC.MIB->isIndirectBranch(Inst)) 3685 continue; 3686 uint64_t JTAddress = BC.MIB->getJumpTable(Inst); 3687 if (!JTAddress) 3688 continue; 3689 // This address can be inside another jump table, but we only consider 3690 // it ambiguous when the same start address is used, not the same JT 3691 // object. 3692 if (!JumpTables.count(JTAddress)) { 3693 JumpTables.insert(JTAddress); 3694 continue; 3695 } 3696 return true; 3697 } 3698 } 3699 return false; 3700 } 3701 3702 void BinaryFunction::disambiguateJumpTables( 3703 MCPlusBuilder::AllocatorIdTy AllocId) { 3704 assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations); 3705 SmallPtrSet<JumpTable *, 4> JumpTables; 3706 for (BinaryBasicBlock *&BB : BasicBlocks) { 3707 for (MCInst &Inst : *BB) { 3708 if (!BC.MIB->isIndirectBranch(Inst)) 3709 continue; 3710 JumpTable *JT = getJumpTable(Inst); 3711 if (!JT) 3712 continue; 3713 auto Iter = JumpTables.find(JT); 3714 if (Iter == JumpTables.end()) { 3715 JumpTables.insert(JT); 3716 continue; 3717 } 3718 // This instruction is an indirect jump using a jump table, but it is 3719 // using the same jump table of another jump. Try all our tricks to 3720 // extract the jump table symbol and make it point to a new, duplicated JT 3721 MCPhysReg BaseReg1; 3722 uint64_t Scale; 3723 const MCSymbol *Target; 3724 // In case we match if our first matcher, first instruction is the one to 3725 // patch 3726 MCInst *JTLoadInst = &Inst; 3727 // Try a standard indirect jump matcher, scale 8 3728 std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher = 3729 BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1), 3730 BC.MIB->matchImm(Scale), BC.MIB->matchReg(), 3731 /*Offset=*/BC.MIB->matchSymbol(Target)); 3732 if (!IndJmpMatcher->match( 3733 *BC.MRI, *BC.MIB, 3734 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) || 3735 BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) { 3736 MCPhysReg BaseReg2; 3737 uint64_t Offset; 3738 // Standard JT matching failed. Trying now: 3739 // movq "jt.2397/1"(,%rax,8), %rax 3740 // jmpq *%rax 3741 std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner = 3742 BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1), 3743 BC.MIB->matchImm(Scale), BC.MIB->matchReg(), 3744 /*Offset=*/BC.MIB->matchSymbol(Target)); 3745 MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get(); 3746 std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 = 3747 BC.MIB->matchIndJmp(std::move(LoadMatcherOwner)); 3748 if (!IndJmpMatcher2->match( 3749 *BC.MRI, *BC.MIB, 3750 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) || 3751 BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) { 3752 // JT matching failed. Trying now: 3753 // PIC-style matcher, scale 4 3754 // addq %rdx, %rsi 3755 // addq %rdx, %rdi 3756 // leaq DATAat0x402450(%rip), %r11 3757 // movslq (%r11,%rdx,4), %rcx 3758 // addq %r11, %rcx 3759 // jmpq *%rcx # JUMPTABLE @0x402450 3760 std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher = 3761 BC.MIB->matchIndJmp(BC.MIB->matchAdd( 3762 BC.MIB->matchReg(BaseReg1), 3763 BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2), 3764 BC.MIB->matchImm(Scale), BC.MIB->matchReg(), 3765 BC.MIB->matchImm(Offset)))); 3766 std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner = 3767 BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target)); 3768 MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get(); 3769 std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher = 3770 BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner), 3771 BC.MIB->matchAnyOperand())); 3772 if (!PICIndJmpMatcher->match( 3773 *BC.MRI, *BC.MIB, 3774 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) || 3775 Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 || 3776 !PICBaseAddrMatcher->match( 3777 *BC.MRI, *BC.MIB, 3778 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) { 3779 llvm_unreachable("Failed to extract jump table base"); 3780 continue; 3781 } 3782 // Matched PIC, identify the instruction with the reference to the JT 3783 JTLoadInst = LEAMatcher->CurInst; 3784 } else { 3785 // Matched non-PIC 3786 JTLoadInst = LoadMatcher->CurInst; 3787 } 3788 } 3789 3790 uint64_t NewJumpTableID = 0; 3791 const MCSymbol *NewJTLabel; 3792 std::tie(NewJumpTableID, NewJTLabel) = 3793 BC.duplicateJumpTable(*this, JT, Target); 3794 { 3795 auto L = BC.scopeLock(); 3796 BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get()); 3797 } 3798 // We use a unique ID with the high bit set as address for this "injected" 3799 // jump table (not originally in the input binary). 3800 BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId); 3801 } 3802 } 3803 } 3804 3805 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB, 3806 BinaryBasicBlock *OldDest, 3807 BinaryBasicBlock *NewDest) { 3808 MCInst *Instr = BB->getLastNonPseudoInstr(); 3809 if (!Instr || !BC.MIB->isIndirectBranch(*Instr)) 3810 return false; 3811 uint64_t JTAddress = BC.MIB->getJumpTable(*Instr); 3812 assert(JTAddress && "Invalid jump table address"); 3813 JumpTable *JT = getJumpTableContainingAddress(JTAddress); 3814 assert(JT && "No jump table structure for this indirect branch"); 3815 bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(), 3816 NewDest->getLabel()); 3817 (void)Patched; 3818 assert(Patched && "Invalid entry to be replaced in jump table"); 3819 return true; 3820 } 3821 3822 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From, 3823 BinaryBasicBlock *To) { 3824 // Create intermediate BB 3825 MCSymbol *Tmp; 3826 { 3827 auto L = BC.scopeLock(); 3828 Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge"); 3829 } 3830 // Link new BBs to the original input offset of the From BB, so we can map 3831 // samples recorded in new BBs back to the original BB seem in the input 3832 // binary (if using BAT) 3833 std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp); 3834 NewBB->setOffset(From->getInputOffset()); 3835 BinaryBasicBlock *NewBBPtr = NewBB.get(); 3836 3837 // Update "From" BB 3838 auto I = From->succ_begin(); 3839 auto BI = From->branch_info_begin(); 3840 for (; I != From->succ_end(); ++I) { 3841 if (*I == To) 3842 break; 3843 ++BI; 3844 } 3845 assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!"); 3846 uint64_t OrigCount = BI->Count; 3847 uint64_t OrigMispreds = BI->MispredictedCount; 3848 replaceJumpTableEntryIn(From, To, NewBBPtr); 3849 From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds); 3850 3851 NewBB->addSuccessor(To, OrigCount, OrigMispreds); 3852 NewBB->setExecutionCount(OrigCount); 3853 NewBB->setIsCold(From->isCold()); 3854 3855 // Update CFI and BB layout with new intermediate BB 3856 std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs; 3857 NewBBs.emplace_back(std::move(NewBB)); 3858 insertBasicBlocks(From, std::move(NewBBs), true, true, 3859 /*RecomputeLandingPads=*/false); 3860 return NewBBPtr; 3861 } 3862 3863 void BinaryFunction::deleteConservativeEdges() { 3864 // Our goal is to aggressively remove edges from the CFG that we believe are 3865 // wrong. This is used for instrumentation, where it is safe to remove 3866 // fallthrough edges because we won't reorder blocks. 3867 for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) { 3868 BinaryBasicBlock *BB = *I; 3869 if (BB->succ_size() != 1 || BB->size() == 0) 3870 continue; 3871 3872 auto NextBB = std::next(I); 3873 MCInst *Last = BB->getLastNonPseudoInstr(); 3874 // Fallthrough is a landing pad? Delete this edge (as long as we don't 3875 // have a direct jump to it) 3876 if ((*BB->succ_begin())->isLandingPad() && NextBB != E && 3877 *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) { 3878 BB->removeAllSuccessors(); 3879 continue; 3880 } 3881 3882 // Look for suspicious calls at the end of BB where gcc may optimize it and 3883 // remove the jump to the epilogue when it knows the call won't return. 3884 if (!Last || !BC.MIB->isCall(*Last)) 3885 continue; 3886 3887 const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last); 3888 if (!CalleeSymbol) 3889 continue; 3890 3891 StringRef CalleeName = CalleeSymbol->getName(); 3892 if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" && 3893 CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" && 3894 CalleeName != "abort@PLT") 3895 continue; 3896 3897 BB->removeAllSuccessors(); 3898 } 3899 } 3900 3901 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol, 3902 uint64_t SymbolSize) const { 3903 // If this symbol is in a different section from the one where the 3904 // function symbol is, don't consider it as valid. 3905 if (!getOriginSection()->containsAddress( 3906 cantFail(Symbol.getAddress(), "cannot get symbol address"))) 3907 return false; 3908 3909 // Some symbols are tolerated inside function bodies, others are not. 3910 // The real function boundaries may not be known at this point. 3911 if (BC.isMarker(Symbol)) 3912 return true; 3913 3914 // It's okay to have a zero-sized symbol in the middle of non-zero-sized 3915 // function. 3916 if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress()))) 3917 return true; 3918 3919 if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown) 3920 return false; 3921 3922 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global) 3923 return false; 3924 3925 return true; 3926 } 3927 3928 void BinaryFunction::adjustExecutionCount(uint64_t Count) { 3929 if (getKnownExecutionCount() == 0 || Count == 0) 3930 return; 3931 3932 if (ExecutionCount < Count) 3933 Count = ExecutionCount; 3934 3935 double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount; 3936 if (AdjustmentRatio < 0.0) 3937 AdjustmentRatio = 0.0; 3938 3939 for (BinaryBasicBlock &BB : blocks()) 3940 BB.adjustExecutionCount(AdjustmentRatio); 3941 3942 ExecutionCount -= Count; 3943 } 3944 3945 BinaryFunction::~BinaryFunction() { 3946 for (BinaryBasicBlock *BB : BasicBlocks) 3947 delete BB; 3948 for (BinaryBasicBlock *BB : DeletedBasicBlocks) 3949 delete BB; 3950 } 3951 3952 void BinaryFunction::calculateLoopInfo() { 3953 // Discover loops. 3954 BinaryDominatorTree DomTree; 3955 DomTree.recalculate(*this); 3956 BLI.reset(new BinaryLoopInfo()); 3957 BLI->analyze(DomTree); 3958 3959 // Traverse discovered loops and add depth and profile information. 3960 std::stack<BinaryLoop *> St; 3961 for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) { 3962 St.push(*I); 3963 ++BLI->OuterLoops; 3964 } 3965 3966 while (!St.empty()) { 3967 BinaryLoop *L = St.top(); 3968 St.pop(); 3969 ++BLI->TotalLoops; 3970 BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth); 3971 3972 // Add nested loops in the stack. 3973 for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) 3974 St.push(*I); 3975 3976 // Skip if no valid profile is found. 3977 if (!hasValidProfile()) { 3978 L->EntryCount = COUNT_NO_PROFILE; 3979 L->ExitCount = COUNT_NO_PROFILE; 3980 L->TotalBackEdgeCount = COUNT_NO_PROFILE; 3981 continue; 3982 } 3983 3984 // Compute back edge count. 3985 SmallVector<BinaryBasicBlock *, 1> Latches; 3986 L->getLoopLatches(Latches); 3987 3988 for (BinaryBasicBlock *Latch : Latches) { 3989 auto BI = Latch->branch_info_begin(); 3990 for (BinaryBasicBlock *Succ : Latch->successors()) { 3991 if (Succ == L->getHeader()) { 3992 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE && 3993 "profile data not found"); 3994 L->TotalBackEdgeCount += BI->Count; 3995 } 3996 ++BI; 3997 } 3998 } 3999 4000 // Compute entry count. 4001 L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount; 4002 4003 // Compute exit count. 4004 SmallVector<BinaryLoop::Edge, 1> ExitEdges; 4005 L->getExitEdges(ExitEdges); 4006 for (BinaryLoop::Edge &Exit : ExitEdges) { 4007 const BinaryBasicBlock *Exiting = Exit.first; 4008 const BinaryBasicBlock *ExitTarget = Exit.second; 4009 auto BI = Exiting->branch_info_begin(); 4010 for (BinaryBasicBlock *Succ : Exiting->successors()) { 4011 if (Succ == ExitTarget) { 4012 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE && 4013 "profile data not found"); 4014 L->ExitCount += BI->Count; 4015 } 4016 ++BI; 4017 } 4018 } 4019 } 4020 } 4021 4022 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) { 4023 if (!isEmitted()) { 4024 assert(!isInjected() && "injected function should be emitted"); 4025 setOutputAddress(getAddress()); 4026 setOutputSize(getSize()); 4027 return; 4028 } 4029 4030 const uint64_t BaseAddress = getCodeSection()->getOutputAddress(); 4031 if (BC.HasRelocations || isInjected()) { 4032 const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol()); 4033 const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel()); 4034 setOutputAddress(BaseAddress + StartOffset); 4035 setOutputSize(EndOffset - StartOffset); 4036 if (hasConstantIsland()) { 4037 const uint64_t DataOffset = 4038 Layout.getSymbolOffset(*getFunctionConstantIslandLabel()); 4039 setOutputDataAddress(BaseAddress + DataOffset); 4040 for (auto It : Islands->Offsets) { 4041 const uint64_t OldOffset = It.first; 4042 BinaryData *BD = BC.getBinaryDataAtAddress(getAddress() + OldOffset); 4043 if (!BD) 4044 continue; 4045 4046 MCSymbol *Symbol = It.second; 4047 const uint64_t NewOffset = Layout.getSymbolOffset(*Symbol); 4048 BD->setOutputLocation(*getCodeSection(), NewOffset); 4049 } 4050 } 4051 if (isSplit()) { 4052 for (FunctionFragment &FF : getLayout().getSplitFragments()) { 4053 ErrorOr<BinarySection &> ColdSection = 4054 getCodeSection(FF.getFragmentNum()); 4055 // If fragment is empty, cold section might not exist 4056 if (FF.empty() && ColdSection.getError()) 4057 continue; 4058 const uint64_t ColdBaseAddress = ColdSection->getOutputAddress(); 4059 4060 const MCSymbol *ColdStartSymbol = getSymbol(FF.getFragmentNum()); 4061 // If fragment is empty, symbol might have not been emitted 4062 if (FF.empty() && (!ColdStartSymbol || !ColdStartSymbol->isDefined()) && 4063 !hasConstantIsland()) 4064 continue; 4065 assert(ColdStartSymbol && ColdStartSymbol->isDefined() && 4066 "split function should have defined cold symbol"); 4067 const MCSymbol *ColdEndSymbol = 4068 getFunctionEndLabel(FF.getFragmentNum()); 4069 assert(ColdEndSymbol && ColdEndSymbol->isDefined() && 4070 "split function should have defined cold end symbol"); 4071 const uint64_t ColdStartOffset = 4072 Layout.getSymbolOffset(*ColdStartSymbol); 4073 const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol); 4074 FF.setAddress(ColdBaseAddress + ColdStartOffset); 4075 FF.setImageSize(ColdEndOffset - ColdStartOffset); 4076 if (hasConstantIsland()) { 4077 const uint64_t DataOffset = 4078 Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel()); 4079 setOutputColdDataAddress(ColdBaseAddress + DataOffset); 4080 } 4081 } 4082 } 4083 } else { 4084 setOutputAddress(getAddress()); 4085 setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel())); 4086 } 4087 4088 // Update basic block output ranges for the debug info, if we have 4089 // secondary entry points in the symbol table to update or if writing BAT. 4090 if (!opts::UpdateDebugSections && !isMultiEntry() && 4091 !requiresAddressTranslation()) 4092 return; 4093 4094 // Output ranges should match the input if the body hasn't changed. 4095 if (!isSimple() && !BC.HasRelocations) 4096 return; 4097 4098 // AArch64 may have functions that only contains a constant island (no code). 4099 if (getLayout().block_empty()) 4100 return; 4101 4102 for (FunctionFragment &FF : getLayout().fragments()) { 4103 if (FF.empty()) 4104 continue; 4105 4106 const uint64_t FragmentBaseAddress = 4107 getCodeSection(isSimple() ? FF.getFragmentNum() : FragmentNum::main()) 4108 ->getOutputAddress(); 4109 4110 BinaryBasicBlock *PrevBB = nullptr; 4111 for (BinaryBasicBlock *const BB : FF) { 4112 assert(BB->getLabel()->isDefined() && "symbol should be defined"); 4113 if (!BC.HasRelocations) { 4114 if (BB->isSplit()) 4115 assert(FragmentBaseAddress == FF.getAddress()); 4116 else 4117 assert(FragmentBaseAddress == getOutputAddress()); 4118 } 4119 4120 const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel()); 4121 const uint64_t BBAddress = FragmentBaseAddress + BBOffset; 4122 BB->setOutputStartAddress(BBAddress); 4123 4124 if (PrevBB) 4125 PrevBB->setOutputEndAddress(BBAddress); 4126 PrevBB = BB; 4127 4128 BB->updateOutputValues(Layout); 4129 } 4130 4131 PrevBB->setOutputEndAddress(PrevBB->isSplit() 4132 ? FF.getAddress() + FF.getImageSize() 4133 : getOutputAddress() + getOutputSize()); 4134 } 4135 } 4136 4137 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const { 4138 DebugAddressRangesVector OutputRanges; 4139 4140 if (isFolded()) 4141 return OutputRanges; 4142 4143 if (IsFragment) 4144 return OutputRanges; 4145 4146 OutputRanges.emplace_back(getOutputAddress(), 4147 getOutputAddress() + getOutputSize()); 4148 if (isSplit()) { 4149 assert(isEmitted() && "split function should be emitted"); 4150 for (const FunctionFragment &FF : getLayout().getSplitFragments()) 4151 OutputRanges.emplace_back(FF.getAddress(), 4152 FF.getAddress() + FF.getImageSize()); 4153 } 4154 4155 if (isSimple()) 4156 return OutputRanges; 4157 4158 for (BinaryFunction *Frag : Fragments) { 4159 assert(!Frag->isSimple() && 4160 "fragment of non-simple function should also be non-simple"); 4161 OutputRanges.emplace_back(Frag->getOutputAddress(), 4162 Frag->getOutputAddress() + Frag->getOutputSize()); 4163 } 4164 4165 return OutputRanges; 4166 } 4167 4168 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const { 4169 if (isFolded()) 4170 return 0; 4171 4172 // If the function hasn't changed return the same address. 4173 if (!isEmitted()) 4174 return Address; 4175 4176 if (Address < getAddress()) 4177 return 0; 4178 4179 // Check if the address is associated with an instruction that is tracked 4180 // by address translation. 4181 auto KV = InputOffsetToAddressMap.find(Address - getAddress()); 4182 if (KV != InputOffsetToAddressMap.end()) 4183 return KV->second; 4184 4185 // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay 4186 // intact. Instead we can use pseudo instructions and/or annotations. 4187 const uint64_t Offset = Address - getAddress(); 4188 const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset); 4189 if (!BB) { 4190 // Special case for address immediately past the end of the function. 4191 if (Offset == getSize()) 4192 return getOutputAddress() + getOutputSize(); 4193 4194 return 0; 4195 } 4196 4197 return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(), 4198 BB->getOutputAddressRange().second); 4199 } 4200 4201 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges( 4202 const DWARFAddressRangesVector &InputRanges) const { 4203 DebugAddressRangesVector OutputRanges; 4204 4205 if (isFolded()) 4206 return OutputRanges; 4207 4208 // If the function hasn't changed return the same ranges. 4209 if (!isEmitted()) { 4210 OutputRanges.resize(InputRanges.size()); 4211 llvm::transform(InputRanges, OutputRanges.begin(), 4212 [](const DWARFAddressRange &Range) { 4213 return DebugAddressRange(Range.LowPC, Range.HighPC); 4214 }); 4215 return OutputRanges; 4216 } 4217 4218 // Even though we will merge ranges in a post-processing pass, we attempt to 4219 // merge them in a main processing loop as it improves the processing time. 4220 uint64_t PrevEndAddress = 0; 4221 for (const DWARFAddressRange &Range : InputRanges) { 4222 if (!containsAddress(Range.LowPC)) { 4223 LLVM_DEBUG( 4224 dbgs() << "BOLT-DEBUG: invalid debug address range detected for " 4225 << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x" 4226 << Twine::utohexstr(Range.HighPC) << "]\n"); 4227 PrevEndAddress = 0; 4228 continue; 4229 } 4230 uint64_t InputOffset = Range.LowPC - getAddress(); 4231 const uint64_t InputEndOffset = 4232 std::min(Range.HighPC - getAddress(), getSize()); 4233 4234 auto BBI = llvm::upper_bound(BasicBlockOffsets, 4235 BasicBlockOffset(InputOffset, nullptr), 4236 CompareBasicBlockOffsets()); 4237 --BBI; 4238 do { 4239 const BinaryBasicBlock *BB = BBI->second; 4240 if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) { 4241 LLVM_DEBUG( 4242 dbgs() << "BOLT-DEBUG: invalid debug address range detected for " 4243 << *this << " : [0x" << Twine::utohexstr(Range.LowPC) 4244 << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n"); 4245 PrevEndAddress = 0; 4246 break; 4247 } 4248 4249 // Skip the range if the block was deleted. 4250 if (const uint64_t OutputStart = BB->getOutputAddressRange().first) { 4251 const uint64_t StartAddress = 4252 OutputStart + InputOffset - BB->getOffset(); 4253 uint64_t EndAddress = BB->getOutputAddressRange().second; 4254 if (InputEndOffset < BB->getEndOffset()) 4255 EndAddress = StartAddress + InputEndOffset - InputOffset; 4256 4257 if (StartAddress == PrevEndAddress) { 4258 OutputRanges.back().HighPC = 4259 std::max(OutputRanges.back().HighPC, EndAddress); 4260 } else { 4261 OutputRanges.emplace_back(StartAddress, 4262 std::max(StartAddress, EndAddress)); 4263 } 4264 PrevEndAddress = OutputRanges.back().HighPC; 4265 } 4266 4267 InputOffset = BB->getEndOffset(); 4268 ++BBI; 4269 } while (InputOffset < InputEndOffset); 4270 } 4271 4272 // Post-processing pass to sort and merge ranges. 4273 llvm::sort(OutputRanges); 4274 DebugAddressRangesVector MergedRanges; 4275 PrevEndAddress = 0; 4276 for (const DebugAddressRange &Range : OutputRanges) { 4277 if (Range.LowPC <= PrevEndAddress) { 4278 MergedRanges.back().HighPC = 4279 std::max(MergedRanges.back().HighPC, Range.HighPC); 4280 } else { 4281 MergedRanges.emplace_back(Range.LowPC, Range.HighPC); 4282 } 4283 PrevEndAddress = MergedRanges.back().HighPC; 4284 } 4285 4286 return MergedRanges; 4287 } 4288 4289 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) { 4290 if (CurrentState == State::Disassembled) { 4291 auto II = Instructions.find(Offset); 4292 return (II == Instructions.end()) ? nullptr : &II->second; 4293 } else if (CurrentState == State::CFG) { 4294 BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset); 4295 if (!BB) 4296 return nullptr; 4297 4298 for (MCInst &Inst : *BB) { 4299 constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max(); 4300 if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset)) 4301 return &Inst; 4302 } 4303 4304 if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) { 4305 const uint32_t Size = 4306 BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size"); 4307 if (BB->getEndOffset() - Offset == Size) 4308 return LastInstr; 4309 } 4310 4311 return nullptr; 4312 } else { 4313 llvm_unreachable("invalid CFG state to use getInstructionAtOffset()"); 4314 } 4315 } 4316 4317 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList( 4318 const DebugLocationsVector &InputLL) const { 4319 DebugLocationsVector OutputLL; 4320 4321 if (isFolded()) 4322 return OutputLL; 4323 4324 // If the function hasn't changed - there's nothing to update. 4325 if (!isEmitted()) 4326 return InputLL; 4327 4328 uint64_t PrevEndAddress = 0; 4329 SmallVectorImpl<uint8_t> *PrevExpr = nullptr; 4330 for (const DebugLocationEntry &Entry : InputLL) { 4331 const uint64_t Start = Entry.LowPC; 4332 const uint64_t End = Entry.HighPC; 4333 if (!containsAddress(Start)) { 4334 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected " 4335 "for " 4336 << *this << " : [0x" << Twine::utohexstr(Start) 4337 << ", 0x" << Twine::utohexstr(End) << "]\n"); 4338 continue; 4339 } 4340 uint64_t InputOffset = Start - getAddress(); 4341 const uint64_t InputEndOffset = std::min(End - getAddress(), getSize()); 4342 auto BBI = llvm::upper_bound(BasicBlockOffsets, 4343 BasicBlockOffset(InputOffset, nullptr), 4344 CompareBasicBlockOffsets()); 4345 --BBI; 4346 do { 4347 const BinaryBasicBlock *BB = BBI->second; 4348 if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) { 4349 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected " 4350 "for " 4351 << *this << " : [0x" << Twine::utohexstr(Start) 4352 << ", 0x" << Twine::utohexstr(End) << "]\n"); 4353 PrevEndAddress = 0; 4354 break; 4355 } 4356 4357 // Skip the range if the block was deleted. 4358 if (const uint64_t OutputStart = BB->getOutputAddressRange().first) { 4359 const uint64_t StartAddress = 4360 OutputStart + InputOffset - BB->getOffset(); 4361 uint64_t EndAddress = BB->getOutputAddressRange().second; 4362 if (InputEndOffset < BB->getEndOffset()) 4363 EndAddress = StartAddress + InputEndOffset - InputOffset; 4364 4365 if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) { 4366 OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress); 4367 } else { 4368 OutputLL.emplace_back(DebugLocationEntry{ 4369 StartAddress, std::max(StartAddress, EndAddress), Entry.Expr}); 4370 } 4371 PrevEndAddress = OutputLL.back().HighPC; 4372 PrevExpr = &OutputLL.back().Expr; 4373 } 4374 4375 ++BBI; 4376 InputOffset = BB->getEndOffset(); 4377 } while (InputOffset < InputEndOffset); 4378 } 4379 4380 // Sort and merge adjacent entries with identical location. 4381 llvm::stable_sort( 4382 OutputLL, [](const DebugLocationEntry &A, const DebugLocationEntry &B) { 4383 return A.LowPC < B.LowPC; 4384 }); 4385 DebugLocationsVector MergedLL; 4386 PrevEndAddress = 0; 4387 PrevExpr = nullptr; 4388 for (const DebugLocationEntry &Entry : OutputLL) { 4389 if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) { 4390 MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC); 4391 } else { 4392 const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress); 4393 const uint64_t End = std::max(Begin, Entry.HighPC); 4394 MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr}); 4395 } 4396 PrevEndAddress = MergedLL.back().HighPC; 4397 PrevExpr = &MergedLL.back().Expr; 4398 } 4399 4400 return MergedLL; 4401 } 4402 4403 void BinaryFunction::printLoopInfo(raw_ostream &OS) const { 4404 if (!opts::shouldPrint(*this)) 4405 return; 4406 4407 OS << "Loop Info for Function \"" << *this << "\""; 4408 if (hasValidProfile()) 4409 OS << " (count: " << getExecutionCount() << ")"; 4410 OS << "\n"; 4411 4412 std::stack<BinaryLoop *> St; 4413 for (BinaryLoop *L : *BLI) 4414 St.push(L); 4415 while (!St.empty()) { 4416 BinaryLoop *L = St.top(); 4417 St.pop(); 4418 4419 for (BinaryLoop *Inner : *L) 4420 St.push(Inner); 4421 4422 if (!hasValidProfile()) 4423 continue; 4424 4425 OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer") 4426 << " loop header: " << L->getHeader()->getName(); 4427 OS << "\n"; 4428 OS << "Loop basic blocks: "; 4429 ListSeparator LS; 4430 for (BinaryBasicBlock *BB : L->blocks()) 4431 OS << LS << BB->getName(); 4432 OS << "\n"; 4433 if (hasValidProfile()) { 4434 OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n"; 4435 OS << "Loop entry count: " << L->EntryCount << "\n"; 4436 OS << "Loop exit count: " << L->ExitCount << "\n"; 4437 if (L->EntryCount > 0) { 4438 OS << "Average iters per entry: " 4439 << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount) 4440 << "\n"; 4441 } 4442 } 4443 OS << "----\n"; 4444 } 4445 4446 OS << "Total number of loops: " << BLI->TotalLoops << "\n"; 4447 OS << "Number of outer loops: " << BLI->OuterLoops << "\n"; 4448 OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n"; 4449 } 4450 4451 bool BinaryFunction::isAArch64Veneer() const { 4452 if (empty() || hasIslandsInfo()) 4453 return false; 4454 4455 BinaryBasicBlock &BB = **BasicBlocks.begin(); 4456 for (MCInst &Inst : BB) 4457 if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer")) 4458 return false; 4459 4460 for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) { 4461 for (MCInst &Inst : **I) 4462 if (!BC.MIB->isNoop(Inst)) 4463 return false; 4464 } 4465 4466 return true; 4467 } 4468 4469 void BinaryFunction::addRelocation(uint64_t Address, MCSymbol *Symbol, 4470 uint64_t RelType, uint64_t Addend, 4471 uint64_t Value) { 4472 assert(Address >= getAddress() && Address < getAddress() + getMaxSize() && 4473 "address is outside of the function"); 4474 uint64_t Offset = Address - getAddress(); 4475 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addRelocation in " 4476 << formatv("{0}@{1:x} against {2}\n", *this, Offset, 4477 Symbol->getName())); 4478 bool IsCI = BC.isAArch64() && isInConstantIsland(Address); 4479 std::map<uint64_t, Relocation> &Rels = 4480 IsCI ? Islands->Relocations : Relocations; 4481 if (BC.MIB->shouldRecordCodeRelocation(RelType)) 4482 Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value}; 4483 } 4484 4485 } // namespace bolt 4486 } // namespace llvm 4487