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