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