1 //===- bolt/Core/BinaryFunction.h - Low-level function ----------*- C++ -*-===// 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 contains the declaration of the BinaryFunction class. It represents 10 // a function at the lowest IR level. Typically, a BinaryFunction represents a 11 // function object in a compiled and linked binary file. However, a 12 // BinaryFunction can also be constructed manually, e.g. for injecting into a 13 // binary file. 14 // 15 // A BinaryFunction could be in one of the several states described in 16 // BinaryFunction::State. While in the disassembled state, it will contain a 17 // list of instructions with their offsets. In the CFG state, it will contain a 18 // list of BinaryBasicBlocks that form a control-flow graph. This state is best 19 // suited for binary analysis and optimizations. However, sometimes it's 20 // impossible to build the precise CFG due to the ambiguity of indirect 21 // branches. 22 // 23 //===----------------------------------------------------------------------===// 24 25 #ifndef BOLT_CORE_BINARY_FUNCTION_H 26 #define BOLT_CORE_BINARY_FUNCTION_H 27 28 #include "bolt/Core/BinaryBasicBlock.h" 29 #include "bolt/Core/BinaryContext.h" 30 #include "bolt/Core/BinaryLoop.h" 31 #include "bolt/Core/BinarySection.h" 32 #include "bolt/Core/DebugData.h" 33 #include "bolt/Core/JumpTable.h" 34 #include "bolt/Core/MCPlus.h" 35 #include "bolt/Utils/NameResolver.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/iterator.h" 38 #include "llvm/BinaryFormat/Dwarf.h" 39 #include "llvm/MC/MCContext.h" 40 #include "llvm/MC/MCDwarf.h" 41 #include "llvm/MC/MCInst.h" 42 #include "llvm/MC/MCSymbol.h" 43 #include "llvm/Object/ObjectFile.h" 44 #include "llvm/Support/raw_ostream.h" 45 #include <algorithm> 46 #include <limits> 47 #include <unordered_map> 48 #include <unordered_set> 49 #include <vector> 50 51 using namespace llvm::object; 52 53 namespace llvm { 54 55 class DWARFUnit; 56 57 namespace bolt { 58 59 using InputOffsetToAddressMapTy = std::unordered_multimap<uint64_t, uint64_t>; 60 61 /// Types of macro-fusion alignment corrections. 62 enum MacroFusionType { MFT_NONE, MFT_HOT, MFT_ALL }; 63 64 enum IndirectCallPromotionType : char { 65 ICP_NONE, /// Don't perform ICP. 66 ICP_CALLS, /// Perform ICP on indirect calls. 67 ICP_JUMP_TABLES, /// Perform ICP on jump tables. 68 ICP_ALL /// Perform ICP on calls and jump tables. 69 }; 70 71 /// Information on a single indirect call to a particular callee. 72 struct IndirectCallProfile { 73 MCSymbol *Symbol; 74 uint32_t Offset; 75 uint64_t Count; 76 uint64_t Mispreds; 77 78 IndirectCallProfile(MCSymbol *Symbol, uint64_t Count, uint64_t Mispreds, 79 uint32_t Offset = 0) 80 : Symbol(Symbol), Offset(Offset), Count(Count), Mispreds(Mispreds) {} 81 82 bool operator==(const IndirectCallProfile &Other) const { 83 return Symbol == Other.Symbol && Offset == Other.Offset; 84 } 85 }; 86 87 /// Aggregated information for an indirect call site. 88 using IndirectCallSiteProfile = SmallVector<IndirectCallProfile, 4>; 89 90 inline raw_ostream &operator<<(raw_ostream &OS, 91 const bolt::IndirectCallSiteProfile &ICSP) { 92 std::string TempString; 93 raw_string_ostream SS(TempString); 94 95 const char *Sep = "\n "; 96 uint64_t TotalCount = 0; 97 uint64_t TotalMispreds = 0; 98 for (const IndirectCallProfile &CSP : ICSP) { 99 SS << Sep << "{ " << (CSP.Symbol ? CSP.Symbol->getName() : "<unknown>") 100 << ": " << CSP.Count << " (" << CSP.Mispreds << " misses) }"; 101 Sep = ",\n "; 102 TotalCount += CSP.Count; 103 TotalMispreds += CSP.Mispreds; 104 } 105 SS.flush(); 106 107 OS << TotalCount << " (" << TotalMispreds << " misses) :" << TempString; 108 return OS; 109 } 110 111 /// BinaryFunction is a representation of machine-level function. 112 /// 113 /// In the input binary, an instance of BinaryFunction can represent a fragment 114 /// of a function if the higher-level function was split, e.g. into hot and cold 115 /// parts. The fragment containing the main entry point is called a parent 116 /// or the main fragment. 117 class BinaryFunction { 118 public: 119 enum class State : char { 120 Empty = 0, /// Function body is empty. 121 Disassembled, /// Function have been disassembled. 122 CFG, /// Control flow graph has been built. 123 CFG_Finalized, /// CFG is finalized. No optimizations allowed. 124 EmittedCFG, /// Instructions have been emitted to output. 125 Emitted, /// Same as above plus CFG is destroyed. 126 }; 127 128 /// Types of profile the function can use. Could be a combination. 129 enum { 130 PF_NONE = 0, /// No profile. 131 PF_LBR = 1, /// Profile is based on last branch records. 132 PF_SAMPLE = 2, /// Non-LBR sample-based profile. 133 PF_MEMEVENT = 4, /// Profile has mem events. 134 }; 135 136 /// Struct for tracking exception handling ranges. 137 struct CallSite { 138 const MCSymbol *Start; 139 const MCSymbol *End; 140 const MCSymbol *LP; 141 uint64_t Action; 142 }; 143 144 using CallSitesType = SmallVector<CallSite, 0>; 145 146 using IslandProxiesType = 147 std::map<BinaryFunction *, std::map<const MCSymbol *, MCSymbol *>>; 148 149 struct IslandInfo { 150 /// Temporary holder of offsets that are data markers (used in AArch) 151 /// It is possible to have data in code sections. To ease the identification 152 /// of data in code sections, the ABI requires the symbol table to have 153 /// symbols named "$d" identifying the start of data inside code and "$x" 154 /// identifying the end of a chunk of data inside code. DataOffsets contain 155 /// all offsets of $d symbols and CodeOffsets all offsets of $x symbols. 156 std::set<uint64_t> DataOffsets; 157 std::set<uint64_t> CodeOffsets; 158 159 /// List of relocations associated with data in the constant island 160 std::map<uint64_t, Relocation> Relocations; 161 162 /// Offsets in function that are data values in a constant island identified 163 /// after disassembling 164 std::map<uint64_t, MCSymbol *> Offsets; 165 SmallPtrSet<MCSymbol *, 4> Symbols; 166 DenseMap<const MCSymbol *, BinaryFunction *> ProxySymbols; 167 DenseMap<const MCSymbol *, MCSymbol *> ColdSymbols; 168 /// Keeps track of other functions we depend on because there is a reference 169 /// to the constant islands in them. 170 IslandProxiesType Proxies, ColdProxies; 171 SmallPtrSet<BinaryFunction *, 1> Dependency; // The other way around 172 173 mutable MCSymbol *FunctionConstantIslandLabel{nullptr}; 174 mutable MCSymbol *FunctionColdConstantIslandLabel{nullptr}; 175 176 // Returns constant island alignment 177 uint16_t getAlignment() const { return sizeof(uint64_t); } 178 }; 179 180 static constexpr uint64_t COUNT_NO_PROFILE = 181 BinaryBasicBlock::COUNT_NO_PROFILE; 182 183 /// We have to use at least 2-byte alignment for functions because of C++ ABI. 184 static constexpr unsigned MinAlign = 2; 185 186 static const char TimerGroupName[]; 187 static const char TimerGroupDesc[]; 188 189 using BasicBlockOrderType = SmallVector<BinaryBasicBlock *, 0>; 190 191 /// Mark injected functions 192 bool IsInjected = false; 193 194 using LSDATypeTableTy = SmallVector<uint64_t, 0>; 195 196 /// List of DWARF CFI instructions. Original CFI from the binary must be 197 /// sorted w.r.t. offset that it appears. We rely on this to replay CFIs 198 /// if needed (to fix state after reordering BBs). 199 using CFIInstrMapType = SmallVector<MCCFIInstruction, 0>; 200 using cfi_iterator = CFIInstrMapType::iterator; 201 using const_cfi_iterator = CFIInstrMapType::const_iterator; 202 203 private: 204 /// Current state of the function. 205 State CurrentState{State::Empty}; 206 207 /// A list of symbols associated with the function entry point. 208 /// 209 /// Multiple symbols would typically result from identical code-folding 210 /// optimization. 211 typedef SmallVector<MCSymbol *, 1> SymbolListTy; 212 SymbolListTy Symbols; 213 214 /// The list of names this function is known under. Used for fuzzy-matching 215 /// the function to its name in a profile, command line, etc. 216 SmallVector<std::string, 0> Aliases; 217 218 /// Containing section in the input file. 219 BinarySection *OriginSection = nullptr; 220 221 /// Address of the function in memory. Also could be an offset from 222 /// base address for position independent binaries. 223 uint64_t Address; 224 225 /// Original size of the function. 226 uint64_t Size; 227 228 /// Address of the function in output. 229 uint64_t OutputAddress{0}; 230 231 /// Size of the function in the output file. 232 uint64_t OutputSize{0}; 233 234 /// Offset in the file. 235 uint64_t FileOffset{0}; 236 237 /// Maximum size this function is allowed to have. 238 uint64_t MaxSize{std::numeric_limits<uint64_t>::max()}; 239 240 /// Alignment requirements for the function. 241 uint16_t Alignment{2}; 242 243 /// Maximum number of bytes used for alignment of hot part of the function. 244 uint16_t MaxAlignmentBytes{0}; 245 246 /// Maximum number of bytes used for alignment of cold part of the function. 247 uint16_t MaxColdAlignmentBytes{0}; 248 249 const MCSymbol *PersonalityFunction{nullptr}; 250 uint8_t PersonalityEncoding{dwarf::DW_EH_PE_sdata4 | dwarf::DW_EH_PE_pcrel}; 251 252 BinaryContext &BC; 253 254 std::unique_ptr<BinaryLoopInfo> BLI; 255 256 /// All labels in the function that are referenced via relocations from 257 /// data objects. Typically these are jump table destinations and computed 258 /// goto labels. 259 std::set<uint64_t> ExternallyReferencedOffsets; 260 261 /// Offsets of indirect branches with unknown destinations. 262 std::set<uint64_t> UnknownIndirectBranchOffsets; 263 264 /// A set of local and global symbols corresponding to secondary entry points. 265 /// Each additional function entry point has a corresponding entry in the map. 266 /// The key is a local symbol corresponding to a basic block and the value 267 /// is a global symbol corresponding to an external entry point. 268 DenseMap<const MCSymbol *, MCSymbol *> SecondaryEntryPoints; 269 270 /// False if the function is too complex to reconstruct its control 271 /// flow graph. 272 /// In relocation mode we still disassemble and re-assemble such functions. 273 bool IsSimple{true}; 274 275 /// Indication that the function should be ignored for optimization purposes. 276 /// If we can skip emission of some functions, then ignored functions could 277 /// be not fully disassembled and will not be emitted. 278 bool IsIgnored{false}; 279 280 /// Pseudo functions should not be disassembled or emitted. 281 bool IsPseudo{false}; 282 283 /// True if the original function code has all necessary relocations to track 284 /// addresses of functions emitted to new locations. Typically set for 285 /// functions that we are not going to emit. 286 bool HasExternalRefRelocations{false}; 287 288 /// True if the function has an indirect branch with unknown destination. 289 bool HasUnknownControlFlow{false}; 290 291 /// The code from inside the function references one of the code locations 292 /// from the same function as a data, i.e. it's possible the label is used 293 /// inside an address calculation or could be referenced from outside. 294 bool HasInternalLabelReference{false}; 295 296 /// In AArch64, preserve nops to maintain code equal to input (assuming no 297 /// optimizations are done). 298 bool PreserveNops{false}; 299 300 /// Indicate if this function has associated exception handling metadata. 301 bool HasEHRanges{false}; 302 303 /// True if the function uses DW_CFA_GNU_args_size CFIs. 304 bool UsesGnuArgsSize{false}; 305 306 /// True if the function might have a profile available externally. 307 /// Used to check if processing of the function is required under certain 308 /// conditions. 309 bool HasProfileAvailable{false}; 310 311 bool HasMemoryProfile{false}; 312 313 /// Execution halts whenever this function is entered. 314 bool TrapsOnEntry{false}; 315 316 /// True if the function had an indirect branch with a fixed internal 317 /// destination. 318 bool HasFixedIndirectBranch{false}; 319 320 /// True if the function is a fragment of another function. This means that 321 /// this function could only be entered via its parent or one of its sibling 322 /// fragments. It could be entered at any basic block. It can also return 323 /// the control to any basic block of its parent or its sibling. 324 bool IsFragment{false}; 325 326 /// Indicate that the function body has SDT marker 327 bool HasSDTMarker{false}; 328 329 /// Indicate that the function body has Pseudo Probe 330 bool HasPseudoProbe{BC.getUniqueSectionByName(".pseudo_probe_desc") && 331 BC.getUniqueSectionByName(".pseudo_probe")}; 332 333 /// True if the original entry point was patched. 334 bool IsPatched{false}; 335 336 /// True if the function contains jump table with entries pointing to 337 /// locations in fragments. 338 bool HasSplitJumpTable{false}; 339 340 /// True if there are no control-flow edges with successors in other functions 341 /// (i.e. if tail calls have edges to function-local basic blocks). 342 /// Set to false by SCTC. Dynostats can't be reliably computed for 343 /// functions with non-canonical CFG. 344 /// This attribute is only valid when hasCFG() == true. 345 bool HasCanonicalCFG{true}; 346 347 /// The address for the code for this function in codegen memory. 348 /// Used for functions that are emitted in a dedicated section with a fixed 349 /// address. E.g. for functions that are overwritten in-place. 350 uint64_t ImageAddress{0}; 351 352 /// The size of the code in memory. 353 uint64_t ImageSize{0}; 354 355 /// Name for the section this function code should reside in. 356 std::string CodeSectionName; 357 358 /// Name for the corresponding cold code section. 359 std::string ColdCodeSectionName; 360 361 /// Parent function fragment for split function fragments. 362 SmallPtrSet<BinaryFunction *, 1> ParentFragments; 363 364 /// Indicate if the function body was folded into another function. 365 /// Used by ICF optimization. 366 BinaryFunction *FoldedIntoFunction{nullptr}; 367 368 /// All fragments for a parent function. 369 SmallPtrSet<BinaryFunction *, 1> Fragments; 370 371 /// The profile data for the number of times the function was executed. 372 uint64_t ExecutionCount{COUNT_NO_PROFILE}; 373 374 /// Profile match ratio. 375 float ProfileMatchRatio{0.0f}; 376 377 /// Raw branch count for this function in the profile 378 uint64_t RawBranchCount{0}; 379 380 /// Indicates the type of profile the function is using. 381 uint16_t ProfileFlags{PF_NONE}; 382 383 /// For functions with mismatched profile we store all call profile 384 /// information at a function level (as opposed to tying it to 385 /// specific call sites). 386 IndirectCallSiteProfile AllCallSites; 387 388 /// Score of the function (estimated number of instructions executed, 389 /// according to profile data). -1 if the score has not been calculated yet. 390 mutable int64_t FunctionScore{-1}; 391 392 /// Original LSDA address for the function. 393 uint64_t LSDAAddress{0}; 394 395 /// Containing compilation unit for the function. 396 DWARFUnit *DwarfUnit{nullptr}; 397 398 /// Last computed hash value. Note that the value could be recomputed using 399 /// different parameters by every pass. 400 mutable uint64_t Hash{0}; 401 402 /// For PLT functions it contains a symbol associated with a function 403 /// reference. It is nullptr for non-PLT functions. 404 const MCSymbol *PLTSymbol{nullptr}; 405 406 /// Function order for streaming into the destination binary. 407 uint32_t Index{-1U}; 408 409 /// Get basic block index assuming it belongs to this function. 410 unsigned getIndex(const BinaryBasicBlock *BB) const { 411 assert(BB->getIndex() < BasicBlocks.size()); 412 return BB->getIndex(); 413 } 414 415 /// Return basic block that originally contained offset \p Offset 416 /// from the function start. 417 BinaryBasicBlock *getBasicBlockContainingOffset(uint64_t Offset); 418 419 const BinaryBasicBlock *getBasicBlockContainingOffset(uint64_t Offset) const { 420 return const_cast<BinaryFunction *>(this)->getBasicBlockContainingOffset( 421 Offset); 422 } 423 424 /// Return basic block that started at offset \p Offset. 425 BinaryBasicBlock *getBasicBlockAtOffset(uint64_t Offset) { 426 BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset); 427 return BB && BB->getOffset() == Offset ? BB : nullptr; 428 } 429 430 /// Release memory taken by the list. 431 template <typename T> BinaryFunction &clearList(T &List) { 432 T TempList; 433 TempList.swap(List); 434 return *this; 435 } 436 437 /// Update the indices of all the basic blocks starting at StartIndex. 438 void updateBBIndices(const unsigned StartIndex); 439 440 /// Annotate each basic block entry with its current CFI state. This is 441 /// run right after the construction of CFG while basic blocks are in their 442 /// original order. 443 void annotateCFIState(); 444 445 /// Associate DW_CFA_GNU_args_size info with invoke instructions 446 /// (call instructions with non-empty landing pad). 447 void propagateGnuArgsSizeInfo(MCPlusBuilder::AllocatorIdTy AllocId); 448 449 /// Synchronize branch instructions with CFG. 450 void postProcessBranches(); 451 452 /// The address offset where we emitted the constant island, that is, the 453 /// chunk of data in the function code area (AArch only) 454 int64_t OutputDataOffset{0}; 455 int64_t OutputColdDataOffset{0}; 456 457 /// Map labels to corresponding basic blocks. 458 DenseMap<const MCSymbol *, BinaryBasicBlock *> LabelToBB; 459 460 using BranchListType = SmallVector<std::pair<uint32_t, uint32_t>, 0>; 461 BranchListType TakenBranches; /// All local taken branches. 462 BranchListType IgnoredBranches; /// Branches ignored by CFG purposes. 463 464 /// Map offset in the function to a label. 465 /// Labels are used for building CFG for simple functions. For non-simple 466 /// function in relocation mode we need to emit them for relocations 467 /// referencing function internals to work (e.g. jump tables). 468 using LabelsMapType = std::map<uint32_t, MCSymbol *>; 469 LabelsMapType Labels; 470 471 /// Temporary holder of instructions before CFG is constructed. 472 /// Map offset in the function to MCInst. 473 using InstrMapType = std::map<uint32_t, MCInst>; 474 InstrMapType Instructions; 475 476 /// We don't decode Call Frame Info encoded in DWARF program state 477 /// machine. Instead we define a "CFI State" - a frame information that 478 /// is a result of executing FDE CFI program up to a given point. The 479 /// program consists of opaque Call Frame Instructions: 480 /// 481 /// CFI #0 482 /// CFI #1 483 /// .... 484 /// CFI #N 485 /// 486 /// When we refer to "CFI State K" - it corresponds to a row in an abstract 487 /// Call Frame Info table. This row is reached right before executing CFI #K. 488 /// 489 /// At any point of execution in a function we are in any one of (N + 2) 490 /// states described in the original FDE program. We can't have more states 491 /// without intelligent processing of CFIs. 492 /// 493 /// When the final layout of basic blocks is known, and we finalize CFG, 494 /// we modify the original program to make sure the same state could be 495 /// reached even when basic blocks containing CFI instructions are executed 496 /// in a different order. 497 CFIInstrMapType FrameInstructions; 498 499 /// A map of restore state CFI instructions to their equivalent CFI 500 /// instructions that produce the same state, in order to eliminate 501 /// remember-restore CFI instructions when rewriting CFI. 502 DenseMap<int32_t, SmallVector<int32_t, 4>> FrameRestoreEquivalents; 503 504 // For tracking exception handling ranges. 505 CallSitesType CallSites; 506 CallSitesType ColdCallSites; 507 508 /// Binary blobs representing action, type, and type index tables for this 509 /// function' LSDA (exception handling). 510 ArrayRef<uint8_t> LSDAActionTable; 511 ArrayRef<uint8_t> LSDATypeIndexTable; 512 513 /// Vector of addresses of types referenced by LSDA. 514 LSDATypeTableTy LSDATypeTable; 515 516 /// Vector of addresses of entries in LSDATypeTable used for indirect 517 /// addressing. 518 LSDATypeTableTy LSDATypeAddressTable; 519 520 /// Marking for the beginning of language-specific data area for the function. 521 MCSymbol *LSDASymbol{nullptr}; 522 MCSymbol *ColdLSDASymbol{nullptr}; 523 524 /// Map to discover which CFIs are attached to a given instruction offset. 525 /// Maps an instruction offset into a FrameInstructions offset. 526 /// This is only relevant to the buildCFG phase and is discarded afterwards. 527 std::multimap<uint32_t, uint32_t> OffsetToCFI; 528 529 /// List of CFI instructions associated with the CIE (common to more than one 530 /// function and that apply before the entry basic block). 531 CFIInstrMapType CIEFrameInstructions; 532 533 /// All compound jump tables for this function. This duplicates what's stored 534 /// in the BinaryContext, but additionally it gives quick access for all 535 /// jump tables used by this function. 536 /// 537 /// <OriginalAddress> -> <JumpTable *> 538 std::map<uint64_t, JumpTable *> JumpTables; 539 540 /// All jump table sites in the function before CFG is built. 541 SmallVector<std::pair<uint64_t, uint64_t>, 0> JTSites; 542 543 /// List of relocations in this function. 544 std::map<uint64_t, Relocation> Relocations; 545 546 /// Information on function constant islands. 547 std::unique_ptr<IslandInfo> Islands; 548 549 // Blocks are kept sorted in the layout order. If we need to change the 550 // layout (if BasicBlocksLayout stores a different order than BasicBlocks), 551 // the terminating instructions need to be modified. 552 using BasicBlockListType = SmallVector<BinaryBasicBlock *, 0>; 553 BasicBlockListType BasicBlocks; 554 BasicBlockListType DeletedBasicBlocks; 555 BasicBlockOrderType BasicBlocksLayout; 556 /// Previous layout replaced by modifyLayout 557 BasicBlockOrderType BasicBlocksPreviousLayout; 558 bool ModifiedLayout{false}; 559 560 /// BasicBlockOffsets are used during CFG construction to map from code 561 /// offsets to BinaryBasicBlocks. Any modifications made to the CFG 562 /// after initial construction are not reflected in this data structure. 563 using BasicBlockOffset = std::pair<uint64_t, BinaryBasicBlock *>; 564 struct CompareBasicBlockOffsets { 565 bool operator()(const BasicBlockOffset &A, 566 const BasicBlockOffset &B) const { 567 return A.first < B.first; 568 } 569 }; 570 SmallVector<BasicBlockOffset, 0> BasicBlockOffsets; 571 572 MCSymbol *ColdSymbol{nullptr}; 573 574 /// Symbol at the end of the function. 575 mutable MCSymbol *FunctionEndLabel{nullptr}; 576 577 /// Symbol at the end of the cold part of split function. 578 mutable MCSymbol *FunctionColdEndLabel{nullptr}; 579 580 /// Unique number associated with the function. 581 uint64_t FunctionNumber; 582 583 /// Count the number of functions created. 584 static uint64_t Count; 585 586 /// Map offsets of special instructions to addresses in the output. 587 InputOffsetToAddressMapTy InputOffsetToAddressMap; 588 589 /// Register alternative function name. 590 void addAlternativeName(std::string NewName) { 591 Aliases.push_back(std::move(NewName)); 592 } 593 594 /// Return a label at a given \p Address in the function. If the label does 595 /// not exist - create it. Assert if the \p Address does not belong to 596 /// the function. If \p CreatePastEnd is true, then return the function 597 /// end label when the \p Address points immediately past the last byte 598 /// of the function. 599 /// NOTE: the function always returns a local (temp) symbol, even if there's 600 /// a global symbol that corresponds to an entry at this address. 601 MCSymbol *getOrCreateLocalLabel(uint64_t Address, bool CreatePastEnd = false); 602 603 /// Register an data entry at a given \p Offset into the function. 604 void markDataAtOffset(uint64_t Offset) { 605 if (!Islands) 606 Islands = std::make_unique<IslandInfo>(); 607 Islands->DataOffsets.emplace(Offset); 608 } 609 610 /// Register an entry point at a given \p Offset into the function. 611 void markCodeAtOffset(uint64_t Offset) { 612 if (!Islands) 613 Islands = std::make_unique<IslandInfo>(); 614 Islands->CodeOffsets.emplace(Offset); 615 } 616 617 /// Register secondary entry point at a given \p Offset into the function. 618 /// Return global symbol for use by extern function references. 619 MCSymbol *addEntryPointAtOffset(uint64_t Offset); 620 621 /// Register an internal offset in a function referenced from outside. 622 void registerReferencedOffset(uint64_t Offset) { 623 ExternallyReferencedOffsets.emplace(Offset); 624 } 625 626 /// True if there are references to internals of this function from data, 627 /// e.g. from jump tables. 628 bool hasInternalReference() const { 629 return !ExternallyReferencedOffsets.empty(); 630 } 631 632 /// Return an entry ID corresponding to a symbol known to belong to 633 /// the function. 634 /// 635 /// Prefer to use BinaryContext::getFunctionForSymbol(EntrySymbol, &ID) 636 /// instead of calling this function directly. 637 uint64_t getEntryIDForSymbol(const MCSymbol *EntrySymbol) const; 638 639 /// If the function represents a secondary split function fragment, set its 640 /// parent fragment to \p BF. 641 void addParentFragment(BinaryFunction &BF) { 642 assert(this != &BF); 643 assert(IsFragment && "function must be a fragment to have a parent"); 644 ParentFragments.insert(&BF); 645 } 646 647 /// Register a child fragment for the main fragment of a split function. 648 void addFragment(BinaryFunction &BF) { 649 assert(this != &BF); 650 Fragments.insert(&BF); 651 } 652 653 void addInstruction(uint64_t Offset, MCInst &&Instruction) { 654 Instructions.emplace(Offset, std::forward<MCInst>(Instruction)); 655 } 656 657 /// Convert CFI instructions to a standard form (remove remember/restore). 658 void normalizeCFIState(); 659 660 /// Analyze and process indirect branch \p Instruction before it is 661 /// added to Instructions list. 662 IndirectBranchType processIndirectBranch(MCInst &Instruction, unsigned Size, 663 uint64_t Offset, 664 uint64_t &TargetAddress); 665 666 BinaryFunction &operator=(const BinaryFunction &) = delete; 667 BinaryFunction(const BinaryFunction &) = delete; 668 669 friend class MachORewriteInstance; 670 friend class RewriteInstance; 671 friend class BinaryContext; 672 friend class DataReader; 673 friend class DataAggregator; 674 675 static std::string buildCodeSectionName(StringRef Name, 676 const BinaryContext &BC); 677 static std::string buildColdCodeSectionName(StringRef Name, 678 const BinaryContext &BC); 679 680 /// Creation should be handled by RewriteInstance or BinaryContext 681 BinaryFunction(const std::string &Name, BinarySection &Section, 682 uint64_t Address, uint64_t Size, BinaryContext &BC) 683 : OriginSection(&Section), Address(Address), Size(Size), BC(BC), 684 CodeSectionName(buildCodeSectionName(Name, BC)), 685 ColdCodeSectionName(buildColdCodeSectionName(Name, BC)), 686 FunctionNumber(++Count) { 687 Symbols.push_back(BC.Ctx->getOrCreateSymbol(Name)); 688 } 689 690 /// This constructor is used to create an injected function 691 BinaryFunction(const std::string &Name, BinaryContext &BC, bool IsSimple) 692 : Address(0), Size(0), BC(BC), IsSimple(IsSimple), 693 CodeSectionName(buildCodeSectionName(Name, BC)), 694 ColdCodeSectionName(buildColdCodeSectionName(Name, BC)), 695 FunctionNumber(++Count) { 696 Symbols.push_back(BC.Ctx->getOrCreateSymbol(Name)); 697 IsInjected = true; 698 } 699 700 /// Create a basic block at a given \p Offset in the function and append it 701 /// to the end of list of blocks. Used during CFG construction only. 702 BinaryBasicBlock *addBasicBlockAt(uint64_t Offset, MCSymbol *Label) { 703 assert(CurrentState == State::Disassembled && 704 "Cannot add block with an offset in non-disassembled state."); 705 assert(!getBasicBlockAtOffset(Offset) && 706 "Basic block already exists at the offset."); 707 708 BasicBlocks.emplace_back(createBasicBlock(Label).release()); 709 BinaryBasicBlock *BB = BasicBlocks.back(); 710 711 BB->setIndex(BasicBlocks.size() - 1); 712 BB->setOffset(Offset); 713 714 BasicBlockOffsets.emplace_back(Offset, BB); 715 assert(llvm::is_sorted(BasicBlockOffsets, CompareBasicBlockOffsets()) && 716 llvm::is_sorted(blocks())); 717 718 return BB; 719 } 720 721 /// Clear state of the function that could not be disassembled or if its 722 /// disassembled state was later invalidated. 723 void clearDisasmState(); 724 725 /// Release memory allocated for CFG and instructions. 726 /// We still keep basic blocks for address translation/mapping purposes. 727 void releaseCFG() { 728 for (BinaryBasicBlock *BB : BasicBlocks) 729 BB->releaseCFG(); 730 for (BinaryBasicBlock *BB : DeletedBasicBlocks) 731 BB->releaseCFG(); 732 733 clearList(CallSites); 734 clearList(ColdCallSites); 735 clearList(LSDATypeTable); 736 clearList(LSDATypeAddressTable); 737 738 clearList(LabelToBB); 739 740 if (!isMultiEntry()) 741 clearList(Labels); 742 743 clearList(FrameInstructions); 744 clearList(FrameRestoreEquivalents); 745 } 746 747 public: 748 BinaryFunction(BinaryFunction &&) = default; 749 750 using iterator = pointee_iterator<BasicBlockListType::iterator>; 751 using const_iterator = pointee_iterator<BasicBlockListType::const_iterator>; 752 using reverse_iterator = 753 pointee_iterator<BasicBlockListType::reverse_iterator>; 754 using const_reverse_iterator = 755 pointee_iterator<BasicBlockListType::const_reverse_iterator>; 756 757 typedef BasicBlockOrderType::iterator order_iterator; 758 typedef BasicBlockOrderType::const_iterator const_order_iterator; 759 typedef BasicBlockOrderType::reverse_iterator reverse_order_iterator; 760 typedef BasicBlockOrderType::const_reverse_iterator 761 const_reverse_order_iterator; 762 763 // CFG iterators. 764 iterator begin() { return BasicBlocks.begin(); } 765 const_iterator begin() const { return BasicBlocks.begin(); } 766 iterator end () { return BasicBlocks.end(); } 767 const_iterator end () const { return BasicBlocks.end(); } 768 769 reverse_iterator rbegin() { return BasicBlocks.rbegin(); } 770 const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); } 771 reverse_iterator rend () { return BasicBlocks.rend(); } 772 const_reverse_iterator rend () const { return BasicBlocks.rend(); } 773 774 size_t size() const { return BasicBlocks.size();} 775 bool empty() const { return BasicBlocks.empty(); } 776 const BinaryBasicBlock &front() const { return *BasicBlocks.front(); } 777 BinaryBasicBlock &front() { return *BasicBlocks.front(); } 778 const BinaryBasicBlock & back() const { return *BasicBlocks.back(); } 779 BinaryBasicBlock & back() { return *BasicBlocks.back(); } 780 inline iterator_range<iterator> blocks() { 781 return iterator_range<iterator>(begin(), end()); 782 } 783 inline iterator_range<const_iterator> blocks() const { 784 return iterator_range<const_iterator>(begin(), end()); 785 } 786 787 // Iterators by pointer. 788 BasicBlockListType::iterator pbegin() { return BasicBlocks.begin(); } 789 BasicBlockListType::iterator pend() { return BasicBlocks.end(); } 790 791 order_iterator layout_begin() { return BasicBlocksLayout.begin(); } 792 const_order_iterator layout_begin() const 793 { return BasicBlocksLayout.begin(); } 794 order_iterator layout_end() { return BasicBlocksLayout.end(); } 795 const_order_iterator layout_end() const 796 { return BasicBlocksLayout.end(); } 797 reverse_order_iterator layout_rbegin() 798 { return BasicBlocksLayout.rbegin(); } 799 const_reverse_order_iterator layout_rbegin() const 800 { return BasicBlocksLayout.rbegin(); } 801 reverse_order_iterator layout_rend() 802 { return BasicBlocksLayout.rend(); } 803 const_reverse_order_iterator layout_rend() const 804 { return BasicBlocksLayout.rend(); } 805 size_t layout_size() const { return BasicBlocksLayout.size(); } 806 bool layout_empty() const { return BasicBlocksLayout.empty(); } 807 const BinaryBasicBlock *layout_front() const 808 { return BasicBlocksLayout.front(); } 809 BinaryBasicBlock *layout_front() { return BasicBlocksLayout.front(); } 810 const BinaryBasicBlock *layout_back() const 811 { return BasicBlocksLayout.back(); } 812 BinaryBasicBlock *layout_back() { return BasicBlocksLayout.back(); } 813 814 inline iterator_range<order_iterator> layout() { 815 return iterator_range<order_iterator>(BasicBlocksLayout.begin(), 816 BasicBlocksLayout.end()); 817 } 818 819 inline iterator_range<const_order_iterator> layout() const { 820 return iterator_range<const_order_iterator>(BasicBlocksLayout.begin(), 821 BasicBlocksLayout.end()); 822 } 823 824 inline iterator_range<reverse_order_iterator> rlayout() { 825 return iterator_range<reverse_order_iterator>(BasicBlocksLayout.rbegin(), 826 BasicBlocksLayout.rend()); 827 } 828 829 inline iterator_range<const_reverse_order_iterator> rlayout() const { 830 return iterator_range<const_reverse_order_iterator>( 831 BasicBlocksLayout.rbegin(), BasicBlocksLayout.rend()); 832 } 833 834 cfi_iterator cie_begin() { return CIEFrameInstructions.begin(); } 835 const_cfi_iterator cie_begin() const { return CIEFrameInstructions.begin(); } 836 cfi_iterator cie_end() { return CIEFrameInstructions.end(); } 837 const_cfi_iterator cie_end() const { return CIEFrameInstructions.end(); } 838 bool cie_empty() const { return CIEFrameInstructions.empty(); } 839 840 inline iterator_range<cfi_iterator> cie() { 841 return iterator_range<cfi_iterator>(cie_begin(), cie_end()); 842 } 843 inline iterator_range<const_cfi_iterator> cie() const { 844 return iterator_range<const_cfi_iterator>(cie_begin(), cie_end()); 845 } 846 847 /// Iterate over all jump tables associated with this function. 848 iterator_range<std::map<uint64_t, JumpTable *>::const_iterator> 849 jumpTables() const { 850 return make_range(JumpTables.begin(), JumpTables.end()); 851 } 852 853 /// Return relocation associated with a given \p Offset in the function, 854 /// or nullptr if no such relocation exists. 855 const Relocation *getRelocationAt(uint64_t Offset) const { 856 assert(CurrentState == State::Empty && 857 "Relocations unavailable in the current function state."); 858 auto RI = Relocations.find(Offset); 859 return (RI == Relocations.end()) ? nullptr : &RI->second; 860 } 861 862 /// Return the first relocation in the function that starts at an address in 863 /// the [StartOffset, EndOffset) range. Return nullptr if no such relocation 864 /// exists. 865 const Relocation *getRelocationInRange(uint64_t StartOffset, 866 uint64_t EndOffset) const { 867 assert(CurrentState == State::Empty && 868 "Relocations unavailable in the current function state."); 869 auto RI = Relocations.lower_bound(StartOffset); 870 if (RI != Relocations.end() && RI->first < EndOffset) 871 return &RI->second; 872 873 return nullptr; 874 } 875 876 /// Returns the raw binary encoding of this function. 877 ErrorOr<ArrayRef<uint8_t>> getData() const; 878 879 BinaryFunction &updateState(BinaryFunction::State State) { 880 CurrentState = State; 881 return *this; 882 } 883 884 /// Update layout of basic blocks used for output. 885 void updateBasicBlockLayout(BasicBlockOrderType &NewLayout) { 886 BasicBlocksPreviousLayout = BasicBlocksLayout; 887 888 if (NewLayout != BasicBlocksLayout) { 889 ModifiedLayout = true; 890 BasicBlocksLayout.clear(); 891 BasicBlocksLayout.swap(NewLayout); 892 } 893 } 894 895 /// Recompute landing pad information for the function and all its blocks. 896 void recomputeLandingPads(); 897 898 /// Return current basic block layout. 899 const BasicBlockOrderType &getLayout() const { return BasicBlocksLayout; } 900 901 /// Return a list of basic blocks sorted using DFS and update layout indices 902 /// using the same order. Does not modify the current layout. 903 BasicBlockOrderType dfs() const; 904 905 /// Find the loops in the CFG of the function and store information about 906 /// them. 907 void calculateLoopInfo(); 908 909 /// Calculate missed macro-fusion opportunities and update BinaryContext 910 /// stats. 911 void calculateMacroOpFusionStats(); 912 913 /// Returns if loop detection has been run for this function. 914 bool hasLoopInfo() const { return BLI != nullptr; } 915 916 const BinaryLoopInfo &getLoopInfo() { return *BLI.get(); } 917 918 bool isLoopFree() { 919 if (!hasLoopInfo()) 920 calculateLoopInfo(); 921 return BLI->empty(); 922 } 923 924 /// Print loop information about the function. 925 void printLoopInfo(raw_ostream &OS) const; 926 927 /// View CFG in graphviz program 928 void viewGraph() const; 929 930 /// Dump CFG in graphviz format 931 void dumpGraph(raw_ostream &OS) const; 932 933 /// Dump CFG in graphviz format to file. 934 void dumpGraphToFile(std::string Filename) const; 935 936 /// Dump CFG in graphviz format to a file with a filename that is derived 937 /// from the function name and Annotation strings. Useful for dumping the 938 /// CFG after an optimization pass. 939 void dumpGraphForPass(std::string Annotation = "") const; 940 941 /// Return BinaryContext for the function. 942 const BinaryContext &getBinaryContext() const { return BC; } 943 944 /// Return BinaryContext for the function. 945 BinaryContext &getBinaryContext() { return BC; } 946 947 /// Attempt to validate CFG invariants. 948 bool validateCFG() const; 949 950 BinaryBasicBlock *getBasicBlockForLabel(const MCSymbol *Label) { 951 auto I = LabelToBB.find(Label); 952 return I == LabelToBB.end() ? nullptr : I->second; 953 } 954 955 const BinaryBasicBlock *getBasicBlockForLabel(const MCSymbol *Label) const { 956 auto I = LabelToBB.find(Label); 957 return I == LabelToBB.end() ? nullptr : I->second; 958 } 959 960 /// Returns the basic block after the given basic block in the layout or 961 /// nullptr the last basic block is given. 962 const BinaryBasicBlock *getBasicBlockAfter(const BinaryBasicBlock *BB, 963 bool IgnoreSplits = true) const { 964 return const_cast<BinaryFunction *>(this)->getBasicBlockAfter(BB, 965 IgnoreSplits); 966 } 967 968 BinaryBasicBlock *getBasicBlockAfter(const BinaryBasicBlock *BB, 969 bool IgnoreSplits = true) { 970 for (auto I = layout_begin(), E = layout_end(); I != E; ++I) { 971 auto Next = std::next(I); 972 if (*I == BB && Next != E) { 973 return (IgnoreSplits || (*I)->isCold() == (*Next)->isCold()) ? *Next 974 : nullptr; 975 } 976 } 977 return nullptr; 978 } 979 980 /// Retrieve the landing pad BB associated with invoke instruction \p Invoke 981 /// that is in \p BB. Return nullptr if none exists 982 BinaryBasicBlock *getLandingPadBBFor(const BinaryBasicBlock &BB, 983 const MCInst &InvokeInst) const { 984 assert(BC.MIB->isInvoke(InvokeInst) && "must be invoke instruction"); 985 const Optional<MCPlus::MCLandingPad> LP = BC.MIB->getEHInfo(InvokeInst); 986 if (LP && LP->first) { 987 BinaryBasicBlock *LBB = BB.getLandingPad(LP->first); 988 assert(LBB && "Landing pad should be defined"); 989 return LBB; 990 } 991 return nullptr; 992 } 993 994 /// Return instruction at a given offset in the function. Valid before 995 /// CFG is constructed or while instruction offsets are available in CFG. 996 MCInst *getInstructionAtOffset(uint64_t Offset); 997 998 const MCInst *getInstructionAtOffset(uint64_t Offset) const { 999 return const_cast<BinaryFunction *>(this)->getInstructionAtOffset(Offset); 1000 } 1001 1002 /// Return offset for the first instruction. If there is data at the 1003 /// beginning of a function then offset of the first instruction could 1004 /// be different from 0 1005 uint64_t getFirstInstructionOffset() const { 1006 if (Instructions.empty()) 1007 return 0; 1008 return Instructions.begin()->first; 1009 } 1010 1011 /// Return jump table that covers a given \p Address in memory. 1012 JumpTable *getJumpTableContainingAddress(uint64_t Address) { 1013 auto JTI = JumpTables.upper_bound(Address); 1014 if (JTI == JumpTables.begin()) 1015 return nullptr; 1016 --JTI; 1017 if (JTI->first + JTI->second->getSize() > Address) 1018 return JTI->second; 1019 if (JTI->second->getSize() == 0 && JTI->first == Address) 1020 return JTI->second; 1021 return nullptr; 1022 } 1023 1024 const JumpTable *getJumpTableContainingAddress(uint64_t Address) const { 1025 return const_cast<BinaryFunction *>(this)->getJumpTableContainingAddress( 1026 Address); 1027 } 1028 1029 /// Return the name of the function if the function has just one name. 1030 /// If the function has multiple names - return one followed 1031 /// by "(*#<numnames>)". 1032 /// 1033 /// We should use getPrintName() for diagnostics and use 1034 /// hasName() to match function name against a given string. 1035 /// 1036 /// NOTE: for disambiguating names of local symbols we use the following 1037 /// naming schemes: 1038 /// primary: <function>/<id> 1039 /// alternative: <function>/<file>/<id2> 1040 std::string getPrintName() const { 1041 const size_t NumNames = Symbols.size() + Aliases.size(); 1042 return NumNames == 1 1043 ? getOneName().str() 1044 : (getOneName().str() + "(*" + std::to_string(NumNames) + ")"); 1045 } 1046 1047 /// The function may have many names. For that reason, we avoid having 1048 /// getName() method as most of the time the user needs a different 1049 /// interface, such as forEachName(), hasName(), hasNameRegex(), etc. 1050 /// In some cases though, we need just a name uniquely identifying 1051 /// the function, and that's what this method is for. 1052 StringRef getOneName() const { return Symbols[0]->getName(); } 1053 1054 /// Return the name of the function as getPrintName(), but also trying 1055 /// to demangle it. 1056 std::string getDemangledName() const; 1057 1058 /// Call \p Callback for every name of this function as long as the Callback 1059 /// returns false. Stop if Callback returns true or all names have been used. 1060 /// Return the name for which the Callback returned true if any. 1061 template <typename FType> 1062 Optional<StringRef> forEachName(FType Callback) const { 1063 for (MCSymbol *Symbol : Symbols) 1064 if (Callback(Symbol->getName())) 1065 return Symbol->getName(); 1066 1067 for (const std::string &Name : Aliases) 1068 if (Callback(StringRef(Name))) 1069 return StringRef(Name); 1070 1071 return NoneType(); 1072 } 1073 1074 /// Check if (possibly one out of many) function name matches the given 1075 /// string. Use this member function instead of direct name comparison. 1076 bool hasName(const std::string &FunctionName) const { 1077 auto Res = 1078 forEachName([&](StringRef Name) { return Name == FunctionName; }); 1079 return Res.hasValue(); 1080 } 1081 1082 /// Check if any of function names matches the given regex. 1083 Optional<StringRef> hasNameRegex(const StringRef NameRegex) const; 1084 1085 /// Check if any of restored function names matches the given regex. 1086 /// Restored name means stripping BOLT-added suffixes like "/1", 1087 Optional<StringRef> hasRestoredNameRegex(const StringRef NameRegex) const; 1088 1089 /// Return a vector of all possible names for the function. 1090 const std::vector<StringRef> getNames() const { 1091 std::vector<StringRef> AllNames; 1092 forEachName([&AllNames](StringRef Name) { 1093 AllNames.push_back(Name); 1094 return false; 1095 }); 1096 1097 return AllNames; 1098 } 1099 1100 /// Return a state the function is in (see BinaryFunction::State definition 1101 /// for description). 1102 State getState() const { return CurrentState; } 1103 1104 /// Return true if function has a control flow graph available. 1105 bool hasCFG() const { 1106 return getState() == State::CFG || getState() == State::CFG_Finalized || 1107 getState() == State::EmittedCFG; 1108 } 1109 1110 /// Return true if the function state implies that it includes instructions. 1111 bool hasInstructions() const { 1112 return getState() == State::Disassembled || hasCFG(); 1113 } 1114 1115 bool isEmitted() const { 1116 return getState() == State::EmittedCFG || getState() == State::Emitted; 1117 } 1118 1119 /// Return the section in the input binary this function originated from or 1120 /// nullptr if the function did not originate from the file. 1121 BinarySection *getOriginSection() const { return OriginSection; } 1122 1123 void setOriginSection(BinarySection *Section) { OriginSection = Section; } 1124 1125 /// Return true if the function did not originate from the primary input file. 1126 bool isInjected() const { return IsInjected; } 1127 1128 /// Return original address of the function (or offset from base for PIC). 1129 uint64_t getAddress() const { return Address; } 1130 1131 uint64_t getOutputAddress() const { return OutputAddress; } 1132 1133 uint64_t getOutputSize() const { return OutputSize; } 1134 1135 /// Does this function have a valid streaming order index? 1136 bool hasValidIndex() const { return Index != -1U; } 1137 1138 /// Get the streaming order index for this function. 1139 uint32_t getIndex() const { return Index; } 1140 1141 /// Set the streaming order index for this function. 1142 void setIndex(uint32_t Idx) { 1143 assert(!hasValidIndex()); 1144 Index = Idx; 1145 } 1146 1147 /// Return offset of the function body in the binary file. 1148 uint64_t getFileOffset() const { return FileOffset; } 1149 1150 /// Return (original) byte size of the function. 1151 uint64_t getSize() const { return Size; } 1152 1153 /// Return the maximum size the body of the function could have. 1154 uint64_t getMaxSize() const { return MaxSize; } 1155 1156 /// Return the number of emitted instructions for this function. 1157 uint32_t getNumNonPseudos() const { 1158 uint32_t N = 0; 1159 for (BinaryBasicBlock *const &BB : layout()) 1160 N += BB->getNumNonPseudos(); 1161 return N; 1162 } 1163 1164 /// Return MC symbol associated with the function. 1165 /// All references to the function should use this symbol. 1166 MCSymbol *getSymbol() { return Symbols[0]; } 1167 1168 /// Return MC symbol associated with the function (const version). 1169 /// All references to the function should use this symbol. 1170 const MCSymbol *getSymbol() const { return Symbols[0]; } 1171 1172 /// Return a list of symbols associated with the main entry of the function. 1173 SymbolListTy &getSymbols() { return Symbols; } 1174 const SymbolListTy &getSymbols() const { return Symbols; } 1175 1176 /// If a local symbol \p BBLabel corresponds to a basic block that is a 1177 /// secondary entry point into the function, then return a global symbol 1178 /// that represents the secondary entry point. Otherwise return nullptr. 1179 MCSymbol *getSecondaryEntryPointSymbol(const MCSymbol *BBLabel) const { 1180 auto I = SecondaryEntryPoints.find(BBLabel); 1181 if (I == SecondaryEntryPoints.end()) 1182 return nullptr; 1183 1184 return I->second; 1185 } 1186 1187 /// If the basic block serves as a secondary entry point to the function, 1188 /// return a global symbol representing the entry. Otherwise return nullptr. 1189 MCSymbol *getSecondaryEntryPointSymbol(const BinaryBasicBlock &BB) const { 1190 return getSecondaryEntryPointSymbol(BB.getLabel()); 1191 } 1192 1193 /// Return true if the basic block is an entry point into the function 1194 /// (either primary or secondary). 1195 bool isEntryPoint(const BinaryBasicBlock &BB) const { 1196 if (&BB == BasicBlocks.front()) 1197 return true; 1198 return getSecondaryEntryPointSymbol(BB); 1199 } 1200 1201 /// Return MC symbol corresponding to an enumerated entry for multiple-entry 1202 /// functions. 1203 MCSymbol *getSymbolForEntryID(uint64_t EntryNum); 1204 const MCSymbol *getSymbolForEntryID(uint64_t EntryNum) const { 1205 return const_cast<BinaryFunction *>(this)->getSymbolForEntryID(EntryNum); 1206 } 1207 1208 using EntryPointCallbackTy = function_ref<bool(uint64_t, const MCSymbol *)>; 1209 1210 /// Invoke \p Callback function for every entry point in the function starting 1211 /// with the main entry and using entries in the ascending address order. 1212 /// Stop calling the function after false is returned by the callback. 1213 /// 1214 /// Pass an offset of the entry point in the input binary and a corresponding 1215 /// global symbol to the callback function. 1216 /// 1217 /// Return true of all callbacks returned true, false otherwise. 1218 bool forEachEntryPoint(EntryPointCallbackTy Callback) const; 1219 1220 MCSymbol *getColdSymbol() { 1221 if (ColdSymbol) 1222 return ColdSymbol; 1223 1224 ColdSymbol = BC.Ctx->getOrCreateSymbol( 1225 NameResolver::append(getSymbol()->getName(), ".cold.0")); 1226 1227 return ColdSymbol; 1228 } 1229 1230 /// Return MC symbol associated with the end of the function. 1231 MCSymbol *getFunctionEndLabel() const { 1232 assert(BC.Ctx && "cannot be called with empty context"); 1233 if (!FunctionEndLabel) { 1234 std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex); 1235 FunctionEndLabel = BC.Ctx->createNamedTempSymbol("func_end"); 1236 } 1237 return FunctionEndLabel; 1238 } 1239 1240 /// Return MC symbol associated with the end of the cold part of the function. 1241 MCSymbol *getFunctionColdEndLabel() const { 1242 if (!FunctionColdEndLabel) { 1243 std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex); 1244 FunctionColdEndLabel = BC.Ctx->createNamedTempSymbol("func_cold_end"); 1245 } 1246 return FunctionColdEndLabel; 1247 } 1248 1249 /// Return a label used to identify where the constant island was emitted 1250 /// (AArch only). This is used to update the symbol table accordingly, 1251 /// emitting data marker symbols as required by the ABI. 1252 MCSymbol *getFunctionConstantIslandLabel() const { 1253 assert(Islands && "function expected to have constant islands"); 1254 1255 if (!Islands->FunctionConstantIslandLabel) { 1256 Islands->FunctionConstantIslandLabel = 1257 BC.Ctx->createNamedTempSymbol("func_const_island"); 1258 } 1259 return Islands->FunctionConstantIslandLabel; 1260 } 1261 1262 MCSymbol *getFunctionColdConstantIslandLabel() const { 1263 assert(Islands && "function expected to have constant islands"); 1264 1265 if (!Islands->FunctionColdConstantIslandLabel) { 1266 Islands->FunctionColdConstantIslandLabel = 1267 BC.Ctx->createNamedTempSymbol("func_cold_const_island"); 1268 } 1269 return Islands->FunctionColdConstantIslandLabel; 1270 } 1271 1272 /// Return true if this is a function representing a PLT entry. 1273 bool isPLTFunction() const { return PLTSymbol != nullptr; } 1274 1275 /// Return PLT function reference symbol for PLT functions and nullptr for 1276 /// non-PLT functions. 1277 const MCSymbol *getPLTSymbol() const { return PLTSymbol; } 1278 1279 /// Set function PLT reference symbol for PLT functions. 1280 void setPLTSymbol(const MCSymbol *Symbol) { 1281 assert(Size == 0 && "function size should be 0 for PLT functions"); 1282 PLTSymbol = Symbol; 1283 IsPseudo = true; 1284 } 1285 1286 /// Update output values of the function based on the final \p Layout. 1287 void updateOutputValues(const MCAsmLayout &Layout); 1288 1289 /// Return mapping of input to output addresses. Most users should call 1290 /// translateInputToOutputAddress() for address translation. 1291 InputOffsetToAddressMapTy &getInputOffsetToAddressMap() { 1292 assert(isEmitted() && "cannot use address mapping before code emission"); 1293 return InputOffsetToAddressMap; 1294 } 1295 1296 void addRelocationAArch64(uint64_t Offset, MCSymbol *Symbol, uint64_t RelType, 1297 uint64_t Addend, uint64_t Value, bool IsCI) { 1298 std::map<uint64_t, Relocation> &Rels = 1299 (IsCI) ? Islands->Relocations : Relocations; 1300 switch (RelType) { 1301 case ELF::R_AARCH64_ABS64: 1302 case ELF::R_AARCH64_ABS32: 1303 case ELF::R_AARCH64_ABS16: 1304 case ELF::R_AARCH64_ADD_ABS_LO12_NC: 1305 case ELF::R_AARCH64_ADR_GOT_PAGE: 1306 case ELF::R_AARCH64_ADR_PREL_LO21: 1307 case ELF::R_AARCH64_ADR_PREL_PG_HI21: 1308 case ELF::R_AARCH64_ADR_PREL_PG_HI21_NC: 1309 case ELF::R_AARCH64_LD64_GOT_LO12_NC: 1310 case ELF::R_AARCH64_LDST8_ABS_LO12_NC: 1311 case ELF::R_AARCH64_LDST16_ABS_LO12_NC: 1312 case ELF::R_AARCH64_LDST32_ABS_LO12_NC: 1313 case ELF::R_AARCH64_LDST64_ABS_LO12_NC: 1314 case ELF::R_AARCH64_LDST128_ABS_LO12_NC: 1315 case ELF::R_AARCH64_TLSDESC_ADD_LO12: 1316 case ELF::R_AARCH64_TLSDESC_ADR_PAGE21: 1317 case ELF::R_AARCH64_TLSDESC_ADR_PREL21: 1318 case ELF::R_AARCH64_TLSDESC_LD64_LO12: 1319 case ELF::R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21: 1320 case ELF::R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC: 1321 case ELF::R_AARCH64_MOVW_UABS_G0: 1322 case ELF::R_AARCH64_MOVW_UABS_G0_NC: 1323 case ELF::R_AARCH64_MOVW_UABS_G1: 1324 case ELF::R_AARCH64_MOVW_UABS_G1_NC: 1325 case ELF::R_AARCH64_MOVW_UABS_G2: 1326 case ELF::R_AARCH64_MOVW_UABS_G2_NC: 1327 case ELF::R_AARCH64_MOVW_UABS_G3: 1328 case ELF::R_AARCH64_PREL16: 1329 case ELF::R_AARCH64_PREL32: 1330 case ELF::R_AARCH64_PREL64: 1331 Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value}; 1332 return; 1333 case ELF::R_AARCH64_CALL26: 1334 case ELF::R_AARCH64_JUMP26: 1335 case ELF::R_AARCH64_TSTBR14: 1336 case ELF::R_AARCH64_CONDBR19: 1337 case ELF::R_AARCH64_TLSDESC_CALL: 1338 case ELF::R_AARCH64_TLSLE_ADD_TPREL_HI12: 1339 case ELF::R_AARCH64_TLSLE_ADD_TPREL_LO12_NC: 1340 return; 1341 default: 1342 llvm_unreachable("Unexpected AArch64 relocation type in code"); 1343 } 1344 } 1345 1346 void addRelocationX86(uint64_t Offset, MCSymbol *Symbol, uint64_t RelType, 1347 uint64_t Addend, uint64_t Value) { 1348 switch (RelType) { 1349 case ELF::R_X86_64_8: 1350 case ELF::R_X86_64_16: 1351 case ELF::R_X86_64_32: 1352 case ELF::R_X86_64_32S: 1353 case ELF::R_X86_64_64: 1354 case ELF::R_X86_64_PC8: 1355 case ELF::R_X86_64_PC32: 1356 case ELF::R_X86_64_PC64: 1357 case ELF::R_X86_64_GOTPCRELX: 1358 case ELF::R_X86_64_REX_GOTPCRELX: 1359 Relocations[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value}; 1360 return; 1361 case ELF::R_X86_64_PLT32: 1362 case ELF::R_X86_64_GOTPCREL: 1363 case ELF::R_X86_64_TPOFF32: 1364 case ELF::R_X86_64_GOTTPOFF: 1365 return; 1366 default: 1367 llvm_unreachable("Unexpected x86 relocation type in code"); 1368 } 1369 } 1370 1371 /// Register relocation type \p RelType at a given \p Address in the function 1372 /// against \p Symbol. 1373 /// Assert if the \p Address is not inside this function. 1374 void addRelocation(uint64_t Address, MCSymbol *Symbol, uint64_t RelType, 1375 uint64_t Addend, uint64_t Value) { 1376 assert(Address >= getAddress() && Address < getAddress() + getMaxSize() && 1377 "address is outside of the function"); 1378 uint64_t Offset = Address - getAddress(); 1379 if (BC.isAArch64()) { 1380 return addRelocationAArch64(Offset, Symbol, RelType, Addend, Value, 1381 isInConstantIsland(Address)); 1382 } 1383 1384 return addRelocationX86(Offset, Symbol, RelType, Addend, Value); 1385 } 1386 1387 /// Return the name of the section this function originated from. 1388 Optional<StringRef> getOriginSectionName() const { 1389 if (!OriginSection) 1390 return NoneType(); 1391 return OriginSection->getName(); 1392 } 1393 1394 /// Return internal section name for this function. 1395 StringRef getCodeSectionName() const { return StringRef(CodeSectionName); } 1396 1397 /// Assign a code section name to the function. 1398 void setCodeSectionName(StringRef Name) { 1399 CodeSectionName = std::string(Name); 1400 } 1401 1402 /// Get output code section. 1403 ErrorOr<BinarySection &> getCodeSection() const { 1404 return BC.getUniqueSectionByName(getCodeSectionName()); 1405 } 1406 1407 /// Return cold code section name for the function. 1408 StringRef getColdCodeSectionName() const { 1409 return StringRef(ColdCodeSectionName); 1410 } 1411 1412 /// Assign a section name for the cold part of the function. 1413 void setColdCodeSectionName(StringRef Name) { 1414 ColdCodeSectionName = std::string(Name); 1415 } 1416 1417 /// Get output code section for cold code of this function. 1418 ErrorOr<BinarySection &> getColdCodeSection() const { 1419 return BC.getUniqueSectionByName(getColdCodeSectionName()); 1420 } 1421 1422 /// Return true iif the function will halt execution on entry. 1423 bool trapsOnEntry() const { return TrapsOnEntry; } 1424 1425 /// Make the function always trap on entry. Other than the trap instruction, 1426 /// the function body will be empty. 1427 void setTrapOnEntry(); 1428 1429 /// Return true if the function could be correctly processed. 1430 bool isSimple() const { return IsSimple; } 1431 1432 /// Return true if the function should be ignored for optimization purposes. 1433 bool isIgnored() const { return IsIgnored; } 1434 1435 /// Return true if the function should not be disassembled, emitted, or 1436 /// otherwise processed. 1437 bool isPseudo() const { return IsPseudo; } 1438 1439 /// Return true if the function contains a jump table with entries pointing 1440 /// to split fragments. 1441 bool hasSplitJumpTable() const { return HasSplitJumpTable; } 1442 1443 /// Return true if all CFG edges have local successors. 1444 bool hasCanonicalCFG() const { return HasCanonicalCFG; } 1445 1446 /// Return true if the original function code has all necessary relocations 1447 /// to track addresses of functions emitted to new locations. 1448 bool hasExternalRefRelocations() const { return HasExternalRefRelocations; } 1449 1450 /// Return true if the function has instruction(s) with unknown control flow. 1451 bool hasUnknownControlFlow() const { return HasUnknownControlFlow; } 1452 1453 /// Return true if the function body is non-contiguous. 1454 bool isSplit() const { 1455 return isSimple() && layout_size() && 1456 layout_front()->isCold() != layout_back()->isCold(); 1457 } 1458 1459 bool shouldPreserveNops() const { return PreserveNops; } 1460 1461 /// Return true if the function has exception handling tables. 1462 bool hasEHRanges() const { return HasEHRanges; } 1463 1464 /// Return true if the function uses DW_CFA_GNU_args_size CFIs. 1465 bool usesGnuArgsSize() const { return UsesGnuArgsSize; } 1466 1467 /// Return true if the function has more than one entry point. 1468 bool isMultiEntry() const { return !SecondaryEntryPoints.empty(); } 1469 1470 /// Return true if the function might have a profile available externally, 1471 /// but not yet populated into the function. 1472 bool hasProfileAvailable() const { return HasProfileAvailable; } 1473 1474 bool hasMemoryProfile() const { return HasMemoryProfile; } 1475 1476 /// Return true if the body of the function was merged into another function. 1477 bool isFolded() const { return FoldedIntoFunction != nullptr; } 1478 1479 /// If this function was folded, return the function it was folded into. 1480 BinaryFunction *getFoldedIntoFunction() const { return FoldedIntoFunction; } 1481 1482 /// Return true if the function uses jump tables. 1483 bool hasJumpTables() const { return !JumpTables.empty(); } 1484 1485 /// Return true if the function has SDT marker 1486 bool hasSDTMarker() const { return HasSDTMarker; } 1487 1488 /// Return true if the function has Pseudo Probe 1489 bool hasPseudoProbe() const { return HasPseudoProbe; } 1490 1491 /// Return true if the original entry point was patched. 1492 bool isPatched() const { return IsPatched; } 1493 1494 const JumpTable *getJumpTable(const MCInst &Inst) const { 1495 const uint64_t Address = BC.MIB->getJumpTable(Inst); 1496 return getJumpTableContainingAddress(Address); 1497 } 1498 1499 JumpTable *getJumpTable(const MCInst &Inst) { 1500 const uint64_t Address = BC.MIB->getJumpTable(Inst); 1501 return getJumpTableContainingAddress(Address); 1502 } 1503 1504 const MCSymbol *getPersonalityFunction() const { return PersonalityFunction; } 1505 1506 uint8_t getPersonalityEncoding() const { return PersonalityEncoding; } 1507 1508 const CallSitesType &getCallSites() const { return CallSites; } 1509 1510 const CallSitesType &getColdCallSites() const { return ColdCallSites; } 1511 1512 const ArrayRef<uint8_t> getLSDAActionTable() const { return LSDAActionTable; } 1513 1514 const LSDATypeTableTy &getLSDATypeTable() const { return LSDATypeTable; } 1515 1516 const LSDATypeTableTy &getLSDATypeAddressTable() const { 1517 return LSDATypeAddressTable; 1518 } 1519 1520 const ArrayRef<uint8_t> getLSDATypeIndexTable() const { 1521 return LSDATypeIndexTable; 1522 } 1523 1524 const LabelsMapType &getLabels() const { return Labels; } 1525 1526 IslandInfo &getIslandInfo() { 1527 assert(Islands && "function expected to have constant islands"); 1528 return *Islands; 1529 } 1530 1531 const IslandInfo &getIslandInfo() const { 1532 assert(Islands && "function expected to have constant islands"); 1533 return *Islands; 1534 } 1535 1536 /// Return true if the function has CFI instructions 1537 bool hasCFI() const { 1538 return !FrameInstructions.empty() || !CIEFrameInstructions.empty(); 1539 } 1540 1541 /// Return unique number associated with the function. 1542 uint64_t getFunctionNumber() const { return FunctionNumber; } 1543 1544 /// Return true if the given address \p PC is inside the function body. 1545 bool containsAddress(uint64_t PC, bool UseMaxSize = false) const { 1546 if (UseMaxSize) 1547 return Address <= PC && PC < Address + MaxSize; 1548 return Address <= PC && PC < Address + Size; 1549 } 1550 1551 /// Create a basic block in the function. The new block is *NOT* inserted 1552 /// into the CFG. The caller must use insertBasicBlocks() to add any new 1553 /// blocks to the CFG. 1554 std::unique_ptr<BinaryBasicBlock> 1555 createBasicBlock(MCSymbol *Label = nullptr) { 1556 if (!Label) { 1557 std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex); 1558 Label = BC.Ctx->createNamedTempSymbol("BB"); 1559 } 1560 auto BB = 1561 std::unique_ptr<BinaryBasicBlock>(new BinaryBasicBlock(this, Label)); 1562 1563 LabelToBB[Label] = BB.get(); 1564 1565 return BB; 1566 } 1567 1568 /// Create a new basic block with an optional \p Label and add it to the list 1569 /// of basic blocks of this function. 1570 BinaryBasicBlock *addBasicBlock(MCSymbol *Label = nullptr) { 1571 assert(CurrentState == State::CFG && "Can only add blocks in CFG state"); 1572 1573 BasicBlocks.emplace_back(createBasicBlock(Label).release()); 1574 BinaryBasicBlock *BB = BasicBlocks.back(); 1575 1576 BB->setIndex(BasicBlocks.size() - 1); 1577 BB->setLayoutIndex(layout_size()); 1578 BasicBlocksLayout.emplace_back(BB); 1579 1580 return BB; 1581 } 1582 1583 /// Add basic block \BB as an entry point to the function. Return global 1584 /// symbol associated with the entry. 1585 MCSymbol *addEntryPoint(const BinaryBasicBlock &BB); 1586 1587 /// Mark all blocks that are unreachable from a root (entry point 1588 /// or landing pad) as invalid. 1589 void markUnreachableBlocks(); 1590 1591 /// Rebuilds BBs layout, ignoring dead BBs. Returns the number of removed 1592 /// BBs and the removed number of bytes of code. 1593 std::pair<unsigned, uint64_t> eraseInvalidBBs(); 1594 1595 /// Get the relative order between two basic blocks in the original 1596 /// layout. The result is > 0 if B occurs before A and < 0 if B 1597 /// occurs after A. If A and B are the same block, the result is 0. 1598 signed getOriginalLayoutRelativeOrder(const BinaryBasicBlock *A, 1599 const BinaryBasicBlock *B) const { 1600 return getIndex(A) - getIndex(B); 1601 } 1602 1603 /// Insert the BBs contained in NewBBs into the basic blocks for this 1604 /// function. Update the associated state of all blocks as needed, i.e. 1605 /// BB offsets and BB indices. The new BBs are inserted after Start. 1606 /// This operation could affect fallthrough branches for Start. 1607 /// 1608 void 1609 insertBasicBlocks(BinaryBasicBlock *Start, 1610 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs, 1611 const bool UpdateLayout = true, 1612 const bool UpdateCFIState = true, 1613 const bool RecomputeLandingPads = true); 1614 1615 iterator insertBasicBlocks( 1616 iterator StartBB, std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs, 1617 const bool UpdateLayout = true, const bool UpdateCFIState = true, 1618 const bool RecomputeLandingPads = true); 1619 1620 /// Update the basic block layout for this function. The BBs from 1621 /// [Start->Index, Start->Index + NumNewBlocks) are inserted into the 1622 /// layout after the BB indicated by Start. 1623 void updateLayout(BinaryBasicBlock *Start, const unsigned NumNewBlocks); 1624 1625 /// Make sure basic blocks' indices match the current layout. 1626 void updateLayoutIndices() const { 1627 unsigned Index = 0; 1628 for (BinaryBasicBlock *BB : layout()) 1629 BB->setLayoutIndex(Index++); 1630 } 1631 1632 /// Recompute the CFI state for NumNewBlocks following Start after inserting 1633 /// new blocks into the CFG. This must be called after updateLayout. 1634 void updateCFIState(BinaryBasicBlock *Start, const unsigned NumNewBlocks); 1635 1636 /// Return true if we detected ambiguous jump tables in this function, which 1637 /// happen when one JT is used in more than one indirect jumps. This precludes 1638 /// us from splitting edges for this JT unless we duplicate the JT (see 1639 /// disambiguateJumpTables). 1640 bool checkForAmbiguousJumpTables(); 1641 1642 /// Detect when two distinct indirect jumps are using the same jump table and 1643 /// duplicate it, allocating a separate JT for each indirect branch. This is 1644 /// necessary for code transformations on the CFG that change an edge induced 1645 /// by an indirect branch, e.g.: instrumentation or shrink wrapping. However, 1646 /// this is only possible if we are not updating jump tables in place, but are 1647 /// writing it to a new location (moving them). 1648 void disambiguateJumpTables(MCPlusBuilder::AllocatorIdTy AllocId); 1649 1650 /// Change \p OrigDest to \p NewDest in the jump table used at the end of 1651 /// \p BB. Returns false if \p OrigDest couldn't be find as a valid target 1652 /// and no replacement took place. 1653 bool replaceJumpTableEntryIn(BinaryBasicBlock *BB, BinaryBasicBlock *OldDest, 1654 BinaryBasicBlock *NewDest); 1655 1656 /// Split the CFG edge <From, To> by inserting an intermediate basic block. 1657 /// Returns a pointer to this new intermediate basic block. BB "From" will be 1658 /// updated to jump to the intermediate block, which in turn will have an 1659 /// unconditional branch to BB "To". 1660 /// User needs to manually call fixBranches(). This function only creates the 1661 /// correct CFG edges. 1662 BinaryBasicBlock *splitEdge(BinaryBasicBlock *From, BinaryBasicBlock *To); 1663 1664 /// We may have built an overly conservative CFG for functions with calls 1665 /// to functions that the compiler knows will never return. In this case, 1666 /// clear all successors from these blocks. 1667 void deleteConservativeEdges(); 1668 1669 /// Determine direction of the branch based on the current layout. 1670 /// Callee is responsible of updating basic block indices prior to using 1671 /// this function (e.g. by calling BinaryFunction::updateLayoutIndices()). 1672 static bool isForwardBranch(const BinaryBasicBlock *From, 1673 const BinaryBasicBlock *To) { 1674 assert(From->getFunction() == To->getFunction() && 1675 "basic blocks should be in the same function"); 1676 return To->getLayoutIndex() > From->getLayoutIndex(); 1677 } 1678 1679 /// Determine direction of the call to callee symbol relative to the start 1680 /// of this function. 1681 /// Note: this doesn't take function splitting into account. 1682 bool isForwardCall(const MCSymbol *CalleeSymbol) const; 1683 1684 /// Dump function information to debug output. If \p PrintInstructions 1685 /// is true - include instruction disassembly. 1686 void dump(bool PrintInstructions = true) const; 1687 1688 /// Print function information to the \p OS stream. 1689 void print(raw_ostream &OS, std::string Annotation = "", 1690 bool PrintInstructions = true) const; 1691 1692 /// Print all relocations between \p Offset and \p Offset + \p Size in 1693 /// this function. 1694 void printRelocations(raw_ostream &OS, uint64_t Offset, uint64_t Size) const; 1695 1696 /// Return true if function has a profile, even if the profile does not 1697 /// match CFG 100%. 1698 bool hasProfile() const { return ExecutionCount != COUNT_NO_PROFILE; } 1699 1700 /// Return true if function profile is present and accurate. 1701 bool hasValidProfile() const { 1702 return ExecutionCount != COUNT_NO_PROFILE && ProfileMatchRatio == 1.0f; 1703 } 1704 1705 /// Mark this function as having a valid profile. 1706 void markProfiled(uint16_t Flags) { 1707 if (ExecutionCount == COUNT_NO_PROFILE) 1708 ExecutionCount = 0; 1709 ProfileFlags = Flags; 1710 ProfileMatchRatio = 1.0f; 1711 } 1712 1713 /// Return flags describing a profile for this function. 1714 uint16_t getProfileFlags() const { return ProfileFlags; } 1715 1716 void addCFIInstruction(uint64_t Offset, MCCFIInstruction &&Inst) { 1717 assert(!Instructions.empty()); 1718 1719 // Fix CFI instructions skipping NOPs. We need to fix this because changing 1720 // CFI state after a NOP, besides being wrong and inaccurate, makes it 1721 // harder for us to recover this information, since we can create empty BBs 1722 // with NOPs and then reorder it away. 1723 // We fix this by moving the CFI instruction just before any NOPs. 1724 auto I = Instructions.lower_bound(Offset); 1725 if (Offset == getSize()) { 1726 assert(I == Instructions.end() && "unexpected iterator value"); 1727 // Sometimes compiler issues restore_state after all instructions 1728 // in the function (even after nop). 1729 --I; 1730 Offset = I->first; 1731 } 1732 assert(I->first == Offset && "CFI pointing to unknown instruction"); 1733 if (I == Instructions.begin()) { 1734 CIEFrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst)); 1735 return; 1736 } 1737 1738 --I; 1739 while (I != Instructions.begin() && BC.MIB->isNoop(I->second)) { 1740 Offset = I->first; 1741 --I; 1742 } 1743 OffsetToCFI.emplace(Offset, FrameInstructions.size()); 1744 FrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst)); 1745 return; 1746 } 1747 1748 BinaryBasicBlock::iterator addCFIInstruction(BinaryBasicBlock *BB, 1749 BinaryBasicBlock::iterator Pos, 1750 MCCFIInstruction &&Inst) { 1751 size_t Idx = FrameInstructions.size(); 1752 FrameInstructions.emplace_back(std::forward<MCCFIInstruction>(Inst)); 1753 return addCFIPseudo(BB, Pos, Idx); 1754 } 1755 1756 /// Insert a CFI pseudo instruction in a basic block. This pseudo instruction 1757 /// is a placeholder that refers to a real MCCFIInstruction object kept by 1758 /// this function that will be emitted at that position. 1759 BinaryBasicBlock::iterator addCFIPseudo(BinaryBasicBlock *BB, 1760 BinaryBasicBlock::iterator Pos, 1761 uint32_t Offset) { 1762 MCInst CFIPseudo; 1763 BC.MIB->createCFI(CFIPseudo, Offset); 1764 return BB->insertPseudoInstr(Pos, CFIPseudo); 1765 } 1766 1767 /// Retrieve the MCCFIInstruction object associated with a CFI pseudo. 1768 const MCCFIInstruction *getCFIFor(const MCInst &Instr) const { 1769 if (!BC.MIB->isCFI(Instr)) 1770 return nullptr; 1771 uint32_t Offset = Instr.getOperand(0).getImm(); 1772 assert(Offset < FrameInstructions.size() && "Invalid CFI offset"); 1773 return &FrameInstructions[Offset]; 1774 } 1775 1776 void setCFIFor(const MCInst &Instr, MCCFIInstruction &&CFIInst) { 1777 assert(BC.MIB->isCFI(Instr) && 1778 "attempting to change CFI in a non-CFI inst"); 1779 uint32_t Offset = Instr.getOperand(0).getImm(); 1780 assert(Offset < FrameInstructions.size() && "Invalid CFI offset"); 1781 FrameInstructions[Offset] = std::move(CFIInst); 1782 } 1783 1784 void mutateCFIRegisterFor(const MCInst &Instr, MCPhysReg NewReg); 1785 1786 const MCCFIInstruction *mutateCFIOffsetFor(const MCInst &Instr, 1787 int64_t NewOffset); 1788 1789 BinaryFunction &setFileOffset(uint64_t Offset) { 1790 FileOffset = Offset; 1791 return *this; 1792 } 1793 1794 BinaryFunction &setSize(uint64_t S) { 1795 Size = S; 1796 return *this; 1797 } 1798 1799 BinaryFunction &setMaxSize(uint64_t Size) { 1800 MaxSize = Size; 1801 return *this; 1802 } 1803 1804 BinaryFunction &setOutputAddress(uint64_t Address) { 1805 OutputAddress = Address; 1806 return *this; 1807 } 1808 1809 BinaryFunction &setOutputSize(uint64_t Size) { 1810 OutputSize = Size; 1811 return *this; 1812 } 1813 1814 BinaryFunction &setSimple(bool Simple) { 1815 IsSimple = Simple; 1816 return *this; 1817 } 1818 1819 void setPseudo(bool Pseudo) { IsPseudo = Pseudo; } 1820 1821 BinaryFunction &setUsesGnuArgsSize(bool Uses = true) { 1822 UsesGnuArgsSize = Uses; 1823 return *this; 1824 } 1825 1826 BinaryFunction &setHasProfileAvailable(bool V = true) { 1827 HasProfileAvailable = V; 1828 return *this; 1829 } 1830 1831 /// Mark function that should not be emitted. 1832 void setIgnored(); 1833 1834 void setIsPatched(bool V) { IsPatched = V; } 1835 1836 void setHasSplitJumpTable(bool V) { HasSplitJumpTable = V; } 1837 1838 void setHasCanonicalCFG(bool V) { HasCanonicalCFG = V; } 1839 1840 void setFolded(BinaryFunction *BF) { FoldedIntoFunction = BF; } 1841 1842 BinaryFunction &setPersonalityFunction(uint64_t Addr) { 1843 assert(!PersonalityFunction && "can't set personality function twice"); 1844 PersonalityFunction = BC.getOrCreateGlobalSymbol(Addr, "FUNCat"); 1845 return *this; 1846 } 1847 1848 BinaryFunction &setPersonalityEncoding(uint8_t Encoding) { 1849 PersonalityEncoding = Encoding; 1850 return *this; 1851 } 1852 1853 BinaryFunction &setAlignment(uint16_t Align) { 1854 Alignment = Align; 1855 return *this; 1856 } 1857 1858 uint16_t getAlignment() const { return Alignment; } 1859 1860 BinaryFunction &setMaxAlignmentBytes(uint16_t MaxAlignBytes) { 1861 MaxAlignmentBytes = MaxAlignBytes; 1862 return *this; 1863 } 1864 1865 uint16_t getMaxAlignmentBytes() const { return MaxAlignmentBytes; } 1866 1867 BinaryFunction &setMaxColdAlignmentBytes(uint16_t MaxAlignBytes) { 1868 MaxColdAlignmentBytes = MaxAlignBytes; 1869 return *this; 1870 } 1871 1872 uint16_t getMaxColdAlignmentBytes() const { return MaxColdAlignmentBytes; } 1873 1874 BinaryFunction &setImageAddress(uint64_t Address) { 1875 ImageAddress = Address; 1876 return *this; 1877 } 1878 1879 /// Return the address of this function' image in memory. 1880 uint64_t getImageAddress() const { return ImageAddress; } 1881 1882 BinaryFunction &setImageSize(uint64_t Size) { 1883 ImageSize = Size; 1884 return *this; 1885 } 1886 1887 /// Return the size of this function' image in memory. 1888 uint64_t getImageSize() const { return ImageSize; } 1889 1890 /// Return true if the function is a secondary fragment of another function. 1891 bool isFragment() const { return IsFragment; } 1892 1893 /// Returns if the given function is a parent fragment of this function. 1894 bool isParentFragment(BinaryFunction *Parent) const { 1895 return ParentFragments.count(Parent); 1896 } 1897 1898 /// Set the profile data for the number of times the function was called. 1899 BinaryFunction &setExecutionCount(uint64_t Count) { 1900 ExecutionCount = Count; 1901 return *this; 1902 } 1903 1904 /// Adjust execution count for the function by a given \p Count. The value 1905 /// \p Count will be subtracted from the current function count. 1906 /// 1907 /// The function will proportionally adjust execution count for all 1908 /// basic blocks and edges in the control flow graph. 1909 void adjustExecutionCount(uint64_t Count); 1910 1911 /// Set LSDA address for the function. 1912 BinaryFunction &setLSDAAddress(uint64_t Address) { 1913 LSDAAddress = Address; 1914 return *this; 1915 } 1916 1917 /// Set LSDA symbol for the function. 1918 BinaryFunction &setLSDASymbol(MCSymbol *Symbol) { 1919 LSDASymbol = Symbol; 1920 return *this; 1921 } 1922 1923 /// Return the profile information about the number of times 1924 /// the function was executed. 1925 /// 1926 /// Return COUNT_NO_PROFILE if there's no profile info. 1927 uint64_t getExecutionCount() const { return ExecutionCount; } 1928 1929 /// Return the raw profile information about the number of branch 1930 /// executions corresponding to this function. 1931 uint64_t getRawBranchCount() const { return RawBranchCount; } 1932 1933 /// Return the execution count for functions with known profile. 1934 /// Return 0 if the function has no profile. 1935 uint64_t getKnownExecutionCount() const { 1936 return ExecutionCount == COUNT_NO_PROFILE ? 0 : ExecutionCount; 1937 } 1938 1939 /// Return original LSDA address for the function or NULL. 1940 uint64_t getLSDAAddress() const { return LSDAAddress; } 1941 1942 /// Return symbol pointing to function's LSDA. 1943 MCSymbol *getLSDASymbol() { 1944 if (LSDASymbol) 1945 return LSDASymbol; 1946 if (CallSites.empty()) 1947 return nullptr; 1948 1949 LSDASymbol = BC.Ctx->getOrCreateSymbol( 1950 Twine("GCC_except_table") + Twine::utohexstr(getFunctionNumber())); 1951 1952 return LSDASymbol; 1953 } 1954 1955 /// Return symbol pointing to function's LSDA for the cold part. 1956 MCSymbol *getColdLSDASymbol() { 1957 if (ColdLSDASymbol) 1958 return ColdLSDASymbol; 1959 if (ColdCallSites.empty()) 1960 return nullptr; 1961 1962 ColdLSDASymbol = BC.Ctx->getOrCreateSymbol( 1963 Twine("GCC_cold_except_table") + Twine::utohexstr(getFunctionNumber())); 1964 1965 return ColdLSDASymbol; 1966 } 1967 1968 void setOutputDataAddress(uint64_t Address) { OutputDataOffset = Address; } 1969 1970 uint64_t getOutputDataAddress() const { return OutputDataOffset; } 1971 1972 void setOutputColdDataAddress(uint64_t Address) { 1973 OutputColdDataOffset = Address; 1974 } 1975 1976 uint64_t getOutputColdDataAddress() const { return OutputColdDataOffset; } 1977 1978 /// If \p Address represents an access to a constant island managed by this 1979 /// function, return a symbol so code can safely refer to it. Otherwise, 1980 /// return nullptr. First return value is the symbol for reference in the 1981 /// hot code area while the second return value is the symbol for reference 1982 /// in the cold code area, as when the function is split the islands are 1983 /// duplicated. 1984 MCSymbol *getOrCreateIslandAccess(uint64_t Address) { 1985 if (!Islands) 1986 return nullptr; 1987 1988 MCSymbol *Symbol; 1989 if (!isInConstantIsland(Address)) 1990 return nullptr; 1991 1992 // Register our island at global namespace 1993 Symbol = BC.getOrCreateGlobalSymbol(Address, "ISLANDat"); 1994 1995 // Internal bookkeeping 1996 const uint64_t Offset = Address - getAddress(); 1997 assert((!Islands->Offsets.count(Offset) || 1998 Islands->Offsets[Offset] == Symbol) && 1999 "Inconsistent island symbol management"); 2000 if (!Islands->Offsets.count(Offset)) { 2001 Islands->Offsets[Offset] = Symbol; 2002 Islands->Symbols.insert(Symbol); 2003 } 2004 return Symbol; 2005 } 2006 2007 /// Called by an external function which wishes to emit references to constant 2008 /// island symbols of this function. We create a proxy for it, so we emit 2009 /// separate symbols when emitting our constant island on behalf of this other 2010 /// function. 2011 MCSymbol *getOrCreateProxyIslandAccess(uint64_t Address, 2012 BinaryFunction &Referrer) { 2013 MCSymbol *Symbol = getOrCreateIslandAccess(Address); 2014 if (!Symbol) 2015 return nullptr; 2016 2017 MCSymbol *Proxy; 2018 if (!Islands->Proxies[&Referrer].count(Symbol)) { 2019 Proxy = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".proxy.for." + 2020 Referrer.getPrintName()); 2021 Islands->Proxies[&Referrer][Symbol] = Proxy; 2022 Islands->Proxies[&Referrer][Proxy] = Symbol; 2023 } 2024 Proxy = Islands->Proxies[&Referrer][Symbol]; 2025 return Proxy; 2026 } 2027 2028 /// Make this function depend on \p BF because we have a reference to its 2029 /// constant island. When emitting this function, we will also emit 2030 // \p BF's constants. This only happens in custom AArch64 assembly code. 2031 void createIslandDependency(MCSymbol *Island, BinaryFunction *BF) { 2032 if (!Islands) 2033 Islands = std::make_unique<IslandInfo>(); 2034 2035 Islands->Dependency.insert(BF); 2036 Islands->ProxySymbols[Island] = BF; 2037 } 2038 2039 /// Detects whether \p Address is inside a data region in this function 2040 /// (constant islands). 2041 bool isInConstantIsland(uint64_t Address) const { 2042 if (!Islands) 2043 return false; 2044 2045 if (Address < getAddress()) 2046 return false; 2047 2048 uint64_t Offset = Address - getAddress(); 2049 2050 if (Offset >= getMaxSize()) 2051 return false; 2052 2053 auto DataIter = Islands->DataOffsets.upper_bound(Offset); 2054 if (DataIter == Islands->DataOffsets.begin()) 2055 return false; 2056 DataIter = std::prev(DataIter); 2057 2058 auto CodeIter = Islands->CodeOffsets.upper_bound(Offset); 2059 if (CodeIter == Islands->CodeOffsets.begin()) 2060 return true; 2061 2062 return *std::prev(CodeIter) <= *DataIter; 2063 } 2064 2065 uint16_t getConstantIslandAlignment() const { 2066 return Islands ? Islands->getAlignment() : 1; 2067 } 2068 2069 uint64_t 2070 estimateConstantIslandSize(const BinaryFunction *OnBehalfOf = nullptr) const { 2071 if (!Islands) 2072 return 0; 2073 2074 uint64_t Size = 0; 2075 for (auto DataIter = Islands->DataOffsets.begin(); 2076 DataIter != Islands->DataOffsets.end(); ++DataIter) { 2077 auto NextData = std::next(DataIter); 2078 auto CodeIter = Islands->CodeOffsets.lower_bound(*DataIter); 2079 if (CodeIter == Islands->CodeOffsets.end() && 2080 NextData == Islands->DataOffsets.end()) { 2081 Size += getMaxSize() - *DataIter; 2082 continue; 2083 } 2084 2085 uint64_t NextMarker; 2086 if (CodeIter == Islands->CodeOffsets.end()) 2087 NextMarker = *NextData; 2088 else if (NextData == Islands->DataOffsets.end()) 2089 NextMarker = *CodeIter; 2090 else 2091 NextMarker = (*CodeIter > *NextData) ? *NextData : *CodeIter; 2092 2093 Size += NextMarker - *DataIter; 2094 } 2095 2096 if (!OnBehalfOf) { 2097 for (BinaryFunction *ExternalFunc : Islands->Dependency) { 2098 Size = alignTo(Size, ExternalFunc->getConstantIslandAlignment()); 2099 Size += ExternalFunc->estimateConstantIslandSize(this); 2100 } 2101 } 2102 2103 return Size; 2104 } 2105 2106 bool hasIslandsInfo() const { return !!Islands; } 2107 2108 bool hasConstantIsland() const { 2109 return Islands && !Islands->DataOffsets.empty(); 2110 } 2111 2112 /// Return true iff the symbol could be seen inside this function otherwise 2113 /// it is probably another function. 2114 bool isSymbolValidInScope(const SymbolRef &Symbol, uint64_t SymbolSize) const; 2115 2116 /// Disassemble function from raw data. 2117 /// If successful, this function will populate the list of instructions 2118 /// for this function together with offsets from the function start 2119 /// in the input. It will also populate Labels with destinations for 2120 /// local branches, and TakenBranches with [from, to] info. 2121 /// 2122 /// The Function should be properly initialized before this function 2123 /// is called. I.e. function address and size should be set. 2124 /// 2125 /// Returns true on successful disassembly, and updates the current 2126 /// state to State:Disassembled. 2127 /// 2128 /// Returns false if disassembly failed. 2129 bool disassemble(); 2130 2131 /// Scan function for references to other functions. In relocation mode, 2132 /// add relocations for external references. 2133 /// 2134 /// Return true on success. 2135 bool scanExternalRefs(); 2136 2137 /// Return the size of a data object located at \p Offset in the function. 2138 /// Return 0 if there is no data object at the \p Offset. 2139 size_t getSizeOfDataInCodeAt(uint64_t Offset) const; 2140 2141 /// Verify that starting at \p Offset function contents are filled with 2142 /// zero-value bytes. 2143 bool isZeroPaddingAt(uint64_t Offset) const; 2144 2145 /// Check that entry points have an associated instruction at their 2146 /// offsets after disassembly. 2147 void postProcessEntryPoints(); 2148 2149 /// Post-processing for jump tables after disassembly. Since their 2150 /// boundaries are not known until all call sites are seen, we need this 2151 /// extra pass to perform any final adjustments. 2152 void postProcessJumpTables(); 2153 2154 /// Builds a list of basic blocks with successor and predecessor info. 2155 /// 2156 /// The function should in Disassembled state prior to call. 2157 /// 2158 /// Returns true on success and update the current function state to 2159 /// State::CFG. Returns false if CFG cannot be built. 2160 bool buildCFG(MCPlusBuilder::AllocatorIdTy); 2161 2162 /// Perform post-processing of the CFG. 2163 void postProcessCFG(); 2164 2165 /// Verify that any assumptions we've made about indirect branches were 2166 /// correct and also make any necessary changes to unknown indirect branches. 2167 /// 2168 /// Catch-22: we need to know indirect branch targets to build CFG, and 2169 /// in order to determine the value for indirect branches we need to know CFG. 2170 /// 2171 /// As such, the process of decoding indirect branches is broken into 2 steps: 2172 /// first we make our best guess about a branch without knowing the CFG, 2173 /// and later after we have the CFG for the function, we verify our earlier 2174 /// assumptions and also do our best at processing unknown indirect branches. 2175 /// 2176 /// Return true upon successful processing, or false if the control flow 2177 /// cannot be statically evaluated for any given indirect branch. 2178 bool postProcessIndirectBranches(MCPlusBuilder::AllocatorIdTy AllocId); 2179 2180 /// Return all call site profile info for this function. 2181 IndirectCallSiteProfile &getAllCallSites() { return AllCallSites; } 2182 2183 const IndirectCallSiteProfile &getAllCallSites() const { 2184 return AllCallSites; 2185 } 2186 2187 /// Walks the list of basic blocks filling in missing information about 2188 /// edge frequency for fall-throughs. 2189 /// 2190 /// Assumes the CFG has been built and edge frequency for taken branches 2191 /// has been filled with LBR data. 2192 void inferFallThroughCounts(); 2193 2194 /// Clear execution profile of the function. 2195 void clearProfile(); 2196 2197 /// Converts conditional tail calls to unconditional tail calls. We do this to 2198 /// handle conditional tail calls correctly and to give a chance to the 2199 /// simplify conditional tail call pass to decide whether to re-optimize them 2200 /// using profile information. 2201 void removeConditionalTailCalls(); 2202 2203 // Convert COUNT_NO_PROFILE to 0 2204 void removeTagsFromProfile(); 2205 2206 /// Computes a function hotness score: the sum of the products of BB frequency 2207 /// and size. 2208 uint64_t getFunctionScore() const; 2209 2210 /// Return true if the layout has been changed by basic block reordering, 2211 /// false otherwise. 2212 bool hasLayoutChanged() const; 2213 2214 /// Get the edit distance of the new layout with respect to the previous 2215 /// layout after basic block reordering. 2216 uint64_t getEditDistance() const; 2217 2218 /// Get the number of instructions within this function. 2219 uint64_t getInstructionCount() const; 2220 2221 const CFIInstrMapType &getFDEProgram() const { return FrameInstructions; } 2222 2223 void moveRememberRestorePair(BinaryBasicBlock *BB); 2224 2225 bool replayCFIInstrs(int32_t FromState, int32_t ToState, 2226 BinaryBasicBlock *InBB, 2227 BinaryBasicBlock::iterator InsertIt); 2228 2229 /// unwindCFIState is used to unwind from a higher to a lower state number 2230 /// without using remember-restore instructions. We do that by keeping track 2231 /// of what values have been changed from state A to B and emitting 2232 /// instructions that undo this change. 2233 SmallVector<int32_t, 4> unwindCFIState(int32_t FromState, int32_t ToState, 2234 BinaryBasicBlock *InBB, 2235 BinaryBasicBlock::iterator &InsertIt); 2236 2237 /// After reordering, this function checks the state of CFI and fixes it if it 2238 /// is corrupted. If it is unable to fix it, it returns false. 2239 bool finalizeCFIState(); 2240 2241 /// Return true if this function needs an address-transaltion table after 2242 /// its code emission. 2243 bool requiresAddressTranslation() const; 2244 2245 /// Adjust branch instructions to match the CFG. 2246 /// 2247 /// As it comes to internal branches, the CFG represents "the ultimate source 2248 /// of truth". Transformations on functions and blocks have to update the CFG 2249 /// and fixBranches() would make sure the correct branch instructions are 2250 /// inserted at the end of basic blocks. 2251 /// 2252 /// We do require a conditional branch at the end of the basic block if 2253 /// the block has 2 successors as CFG currently lacks the conditional 2254 /// code support (it will probably stay that way). We only use this 2255 /// branch instruction for its conditional code, the destination is 2256 /// determined by CFG - first successor representing true/taken branch, 2257 /// while the second successor - false/fall-through branch. 2258 /// 2259 /// When we reverse the branch condition, the CFG is updated accordingly. 2260 void fixBranches(); 2261 2262 /// Mark function as finalized. No further optimizations are permitted. 2263 void setFinalized() { CurrentState = State::CFG_Finalized; } 2264 2265 void setEmitted(bool KeepCFG = false) { 2266 CurrentState = State::EmittedCFG; 2267 if (!KeepCFG) { 2268 releaseCFG(); 2269 CurrentState = State::Emitted; 2270 } 2271 } 2272 2273 /// Process LSDA information for the function. 2274 void parseLSDA(ArrayRef<uint8_t> LSDAData, uint64_t LSDAAddress); 2275 2276 /// Update exception handling ranges for the function. 2277 void updateEHRanges(); 2278 2279 /// Traverse cold basic blocks and replace references to constants in islands 2280 /// with a proxy symbol for the duplicated constant island that is going to be 2281 /// emitted in the cold region. 2282 void duplicateConstantIslands(); 2283 2284 /// Merge profile data of this function into those of the given 2285 /// function. The functions should have been proven identical with 2286 /// isIdenticalWith. 2287 void mergeProfileDataInto(BinaryFunction &BF) const; 2288 2289 /// Returns the last computed hash value of the function. 2290 size_t getHash() const { return Hash; } 2291 2292 using OperandHashFuncTy = 2293 function_ref<typename std::string(const MCOperand &)>; 2294 2295 /// Compute the hash value of the function based on its contents. 2296 /// 2297 /// If \p UseDFS is set, process basic blocks in DFS order. Otherwise, use 2298 /// the existing layout order. 2299 /// 2300 /// By default, instruction operands are ignored while calculating the hash. 2301 /// The caller can change this via passing \p OperandHashFunc function. 2302 /// The return result of this function will be mixed with internal hash. 2303 size_t computeHash( 2304 bool UseDFS = false, 2305 OperandHashFuncTy OperandHashFunc = [](const MCOperand &) { 2306 return std::string(); 2307 }) const; 2308 2309 void setDWARFUnit(DWARFUnit *Unit) { DwarfUnit = Unit; } 2310 2311 /// Return DWARF compile unit for this function. 2312 DWARFUnit *getDWARFUnit() const { return DwarfUnit; } 2313 2314 /// Return line info table for this function. 2315 const DWARFDebugLine::LineTable *getDWARFLineTable() const { 2316 return getDWARFUnit() ? BC.DwCtx->getLineTableForUnit(getDWARFUnit()) 2317 : nullptr; 2318 } 2319 2320 /// Finalize profile for the function. 2321 void postProcessProfile(); 2322 2323 /// Returns an estimate of the function's hot part after splitting. 2324 /// This is a very rough estimate, as with C++ exceptions there are 2325 /// blocks we don't move, and it makes no attempt at estimating the size 2326 /// of the added/removed branch instructions. 2327 /// Note that this size is optimistic and the actual size may increase 2328 /// after relaxation. 2329 size_t estimateHotSize(const bool UseSplitSize = true) const { 2330 size_t Estimate = 0; 2331 if (UseSplitSize && isSplit()) { 2332 for (const BinaryBasicBlock *BB : BasicBlocksLayout) 2333 if (!BB->isCold()) 2334 Estimate += BC.computeCodeSize(BB->begin(), BB->end()); 2335 } else { 2336 for (const BinaryBasicBlock *BB : BasicBlocksLayout) 2337 if (BB->getKnownExecutionCount() != 0) 2338 Estimate += BC.computeCodeSize(BB->begin(), BB->end()); 2339 } 2340 return Estimate; 2341 } 2342 2343 size_t estimateColdSize() const { 2344 if (!isSplit()) 2345 return estimateSize(); 2346 size_t Estimate = 0; 2347 for (const BinaryBasicBlock *BB : BasicBlocksLayout) 2348 if (BB->isCold()) 2349 Estimate += BC.computeCodeSize(BB->begin(), BB->end()); 2350 return Estimate; 2351 } 2352 2353 size_t estimateSize() const { 2354 size_t Estimate = 0; 2355 for (const BinaryBasicBlock *BB : BasicBlocksLayout) 2356 Estimate += BC.computeCodeSize(BB->begin(), BB->end()); 2357 return Estimate; 2358 } 2359 2360 /// Return output address ranges for a function. 2361 DebugAddressRangesVector getOutputAddressRanges() const; 2362 2363 /// Given an address corresponding to an instruction in the input binary, 2364 /// return an address of this instruction in output binary. 2365 /// 2366 /// Return 0 if no matching address could be found or the instruction was 2367 /// removed. 2368 uint64_t translateInputToOutputAddress(uint64_t Address) const; 2369 2370 /// Take address ranges corresponding to the input binary and translate 2371 /// them to address ranges in the output binary. 2372 DebugAddressRangesVector translateInputToOutputRanges( 2373 const DWARFAddressRangesVector &InputRanges) const; 2374 2375 /// Similar to translateInputToOutputRanges() but operates on location lists 2376 /// and moves associated data to output location lists. 2377 DebugLocationsVector 2378 translateInputToOutputLocationList(const DebugLocationsVector &InputLL) const; 2379 2380 /// Return true if the function is an AArch64 linker inserted veneer 2381 bool isAArch64Veneer() const; 2382 2383 virtual ~BinaryFunction(); 2384 2385 /// Info for fragmented functions. 2386 class FragmentInfo { 2387 private: 2388 uint64_t Address{0}; 2389 uint64_t ImageAddress{0}; 2390 uint64_t ImageSize{0}; 2391 uint64_t FileOffset{0}; 2392 2393 public: 2394 uint64_t getAddress() const { return Address; } 2395 uint64_t getImageAddress() const { return ImageAddress; } 2396 uint64_t getImageSize() const { return ImageSize; } 2397 uint64_t getFileOffset() const { return FileOffset; } 2398 2399 void setAddress(uint64_t VAddress) { Address = VAddress; } 2400 void setImageAddress(uint64_t Address) { ImageAddress = Address; } 2401 void setImageSize(uint64_t Size) { ImageSize = Size; } 2402 void setFileOffset(uint64_t Offset) { FileOffset = Offset; } 2403 }; 2404 2405 /// Cold fragment of the function. 2406 FragmentInfo ColdFragment; 2407 2408 FragmentInfo &cold() { return ColdFragment; } 2409 2410 const FragmentInfo &cold() const { return ColdFragment; } 2411 }; 2412 2413 inline raw_ostream &operator<<(raw_ostream &OS, 2414 const BinaryFunction &Function) { 2415 OS << Function.getPrintName(); 2416 return OS; 2417 } 2418 2419 } // namespace bolt 2420 2421 // GraphTraits specializations for function basic block graphs (CFGs) 2422 template <> 2423 struct GraphTraits<bolt::BinaryFunction *> 2424 : public GraphTraits<bolt::BinaryBasicBlock *> { 2425 static NodeRef getEntryNode(bolt::BinaryFunction *F) { 2426 return *F->layout_begin(); 2427 } 2428 2429 using nodes_iterator = pointer_iterator<bolt::BinaryFunction::iterator>; 2430 2431 static nodes_iterator nodes_begin(bolt::BinaryFunction *F) { 2432 llvm_unreachable("Not implemented"); 2433 return nodes_iterator(F->begin()); 2434 } 2435 static nodes_iterator nodes_end(bolt::BinaryFunction *F) { 2436 llvm_unreachable("Not implemented"); 2437 return nodes_iterator(F->end()); 2438 } 2439 static size_t size(bolt::BinaryFunction *F) { return F->size(); } 2440 }; 2441 2442 template <> 2443 struct GraphTraits<const bolt::BinaryFunction *> 2444 : public GraphTraits<const bolt::BinaryBasicBlock *> { 2445 static NodeRef getEntryNode(const bolt::BinaryFunction *F) { 2446 return *F->layout_begin(); 2447 } 2448 2449 using nodes_iterator = pointer_iterator<bolt::BinaryFunction::const_iterator>; 2450 2451 static nodes_iterator nodes_begin(const bolt::BinaryFunction *F) { 2452 llvm_unreachable("Not implemented"); 2453 return nodes_iterator(F->begin()); 2454 } 2455 static nodes_iterator nodes_end(const bolt::BinaryFunction *F) { 2456 llvm_unreachable("Not implemented"); 2457 return nodes_iterator(F->end()); 2458 } 2459 static size_t size(const bolt::BinaryFunction *F) { return F->size(); } 2460 }; 2461 2462 template <> 2463 struct GraphTraits<Inverse<bolt::BinaryFunction *>> 2464 : public GraphTraits<Inverse<bolt::BinaryBasicBlock *>> { 2465 static NodeRef getEntryNode(Inverse<bolt::BinaryFunction *> G) { 2466 return *G.Graph->layout_begin(); 2467 } 2468 }; 2469 2470 template <> 2471 struct GraphTraits<Inverse<const bolt::BinaryFunction *>> 2472 : public GraphTraits<Inverse<const bolt::BinaryBasicBlock *>> { 2473 static NodeRef getEntryNode(Inverse<const bolt::BinaryFunction *> G) { 2474 return *G.Graph->layout_begin(); 2475 } 2476 }; 2477 2478 } // namespace llvm 2479 2480 #endif 2481