xref: /llvm-project/bolt/runtime/instr.cpp (revision 361f3b5576c4e90e1f1cb7572d2d3923a1670b4b)
162aa74f8SRafael Auler //===-- instr.cpp -----------------------------------------------*- C++ -*-===//
262aa74f8SRafael Auler //
3da752c9cSRafael Auler // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4da752c9cSRafael Auler // See https://llvm.org/LICENSE.txt for license information.
5da752c9cSRafael Auler // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
662aa74f8SRafael Auler //
762aa74f8SRafael Auler //===----------------------------------------------------------------------===//
862aa74f8SRafael Auler //
916a497c6SRafael Auler // BOLT runtime instrumentation library for x86 Linux. Currently, BOLT does
1016a497c6SRafael Auler // not support linking modules with dependencies on one another into the final
1116a497c6SRafael Auler // binary (TODO?), which means this library has to be self-contained in a single
1216a497c6SRafael Auler // module.
1316a497c6SRafael Auler //
1416a497c6SRafael Auler // All extern declarations here need to be defined by BOLT itself. Those will be
1516a497c6SRafael Auler // undefined symbols that BOLT needs to resolve by emitting these symbols with
1616a497c6SRafael Auler // MCStreamer. Currently, Passes/Instrumentation.cpp is the pass responsible
1716a497c6SRafael Auler // for defining the symbols here and these two files have a tight coupling: one
1816a497c6SRafael Auler // working statically when you run BOLT and another during program runtime when
1916a497c6SRafael Auler // you run an instrumented binary. The main goal here is to output an fdata file
2016a497c6SRafael Auler // (BOLT profile) with the instrumentation counters inserted by the static pass.
2116a497c6SRafael Auler // Counters for indirect calls are an exception, as we can't know them
2216a497c6SRafael Auler // statically. These counters are created and managed here. To allow this, we
2316a497c6SRafael Auler // need a minimal framework for allocating memory dynamically. We provide this
2416a497c6SRafael Auler // with the BumpPtrAllocator class (not LLVM's, but our own version of it).
2516a497c6SRafael Auler //
2616a497c6SRafael Auler // Since this code is intended to be inserted into any executable, we decided to
2716a497c6SRafael Auler // make it standalone and do not depend on any external libraries (i.e. language
2816a497c6SRafael Auler // support libraries, such as glibc or stdc++). To allow this, we provide a few
2916a497c6SRafael Auler // light implementations of common OS interacting functionalities using direct
3016a497c6SRafael Auler // syscall wrappers. Our simple allocator doesn't manage deallocations that
3116a497c6SRafael Auler // fragment the memory space, so it's stack based. This is the minimal framework
3216a497c6SRafael Auler // provided here to allow processing instrumented counters and writing fdata.
3316a497c6SRafael Auler //
3416a497c6SRafael Auler // In the C++ idiom used here, we never use or rely on constructors or
3516a497c6SRafael Auler // destructors for global objects. That's because those need support from the
3616a497c6SRafael Auler // linker in initialization/finalization code, and we want to keep our linker
3716a497c6SRafael Auler // very simple. Similarly, we don't create any global objects that are zero
3816a497c6SRafael Auler // initialized, since those would need to go .bss, which our simple linker also
3916a497c6SRafael Auler // don't support (TODO?).
4062aa74f8SRafael Auler //
4162aa74f8SRafael Auler //===----------------------------------------------------------------------===//
4262aa74f8SRafael Auler 
439bd71615SXun Li #include "common.h"
4462aa74f8SRafael Auler 
4516a497c6SRafael Auler // Enables a very verbose logging to stderr useful when debugging
46cc4b2fb6SRafael Auler //#define ENABLE_DEBUG
47cc4b2fb6SRafael Auler 
48cc4b2fb6SRafael Auler #ifdef ENABLE_DEBUG
49cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
50cc4b2fb6SRafael Auler   { X; }
51cc4b2fb6SRafael Auler #else
52cc4b2fb6SRafael Auler #define DEBUG(X)                                                               \
53cc4b2fb6SRafael Auler   {}
54cc4b2fb6SRafael Auler #endif
55cc4b2fb6SRafael Auler 
563b876cc3SAlexander Shaposhnikov 
573b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
583b876cc3SAlexander Shaposhnikov extern "C" {
593b876cc3SAlexander Shaposhnikov extern uint64_t* _bolt_instr_locations_getter();
603b876cc3SAlexander Shaposhnikov extern uint32_t _bolt_num_counters_getter();
613b876cc3SAlexander Shaposhnikov 
62a0dd5b05SAlexander Shaposhnikov extern uint8_t* _bolt_instr_tables_getter();
63a0dd5b05SAlexander Shaposhnikov extern uint32_t _bolt_instr_num_funcs_getter();
643b876cc3SAlexander Shaposhnikov }
653b876cc3SAlexander Shaposhnikov 
663b876cc3SAlexander Shaposhnikov #else
67bbd9d610SAlexander Shaposhnikov 
6816a497c6SRafael Auler // Main counters inserted by instrumentation, incremented during runtime when
6916a497c6SRafael Auler // points of interest (locations) in the program are reached. Those are direct
7016a497c6SRafael Auler // calls and direct and indirect branches (local ones). There are also counters
7116a497c6SRafael Auler // for basic block execution if they are a spanning tree leaf and need to be
7216a497c6SRafael Auler // counted in order to infer the execution count of other edges of the CFG.
7362aa74f8SRafael Auler extern uint64_t __bolt_instr_locations[];
7416a497c6SRafael Auler extern uint32_t __bolt_num_counters;
7516a497c6SRafael Auler // Descriptions are serialized metadata about binary functions written by BOLT,
7616a497c6SRafael Auler // so we have a minimal understanding about the program structure. For a
7716a497c6SRafael Auler // reference on the exact format of this metadata, see *Description structs,
7816a497c6SRafael Auler // Location, IntrumentedNode and EntryNode.
7916a497c6SRafael Auler // Number of indirect call site descriptions
8016a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_calls;
8116a497c6SRafael Auler // Number of indirect call target descriptions
8216a497c6SRafael Auler extern uint32_t __bolt_instr_num_ind_targets;
83cc4b2fb6SRafael Auler // Number of function descriptions
84cc4b2fb6SRafael Auler extern uint32_t __bolt_instr_num_funcs;
8516a497c6SRafael Auler // Time to sleep across dumps (when we write the fdata profile to disk)
8616a497c6SRafael Auler extern uint32_t __bolt_instr_sleep_time;
8776d346caSVladislav Khmelevsky // Do not clear counters across dumps, rewrite file with the updated values
8876d346caSVladislav Khmelevsky extern bool __bolt_instr_no_counters_clear;
8976d346caSVladislav Khmelevsky // Wait until all forks of instrumented process will finish
9076d346caSVladislav Khmelevsky extern bool __bolt_instr_wait_forks;
91cc4b2fb6SRafael Auler // Filename to dump data to
9262aa74f8SRafael Auler extern char __bolt_instr_filename[];
9316a497c6SRafael Auler // If true, append current PID to the fdata filename when creating it so
9416a497c6SRafael Auler // different invocations of the same program can be differentiated.
9516a497c6SRafael Auler extern bool __bolt_instr_use_pid;
9616a497c6SRafael Auler // Functions that will be used to instrument indirect calls. BOLT static pass
9716a497c6SRafael Auler // will identify indirect calls and modify them to load the address in these
9816a497c6SRafael Auler // trampolines and call this address instead. BOLT can't use direct calls to
9916a497c6SRafael Auler // our handlers because our addresses here are not known at analysis time. We
10016a497c6SRafael Auler // only support resolving dependencies from this file to the output of BOLT,
10116a497c6SRafael Auler // *not* the other way around.
10216a497c6SRafael Auler // TODO: We need better linking support to make that happen.
103*361f3b55SVladislav Khmelevsky extern void (*__bolt_ind_call_counter_func_pointer)();
104*361f3b55SVladislav Khmelevsky extern void (*__bolt_ind_tailcall_counter_func_pointer)();
105ad79d517SVasily Leonenko // Function pointers to init/fini trampoline routines in the binary, so we can
106ad79d517SVasily Leonenko // resume regular execution of these functions that we hooked
107ad79d517SVasily Leonenko extern void (*__bolt_start_trampoline)();
108ad79d517SVasily Leonenko extern void (*__bolt_fini_trampoline)();
10962aa74f8SRafael Auler 
110a0dd5b05SAlexander Shaposhnikov #endif
111a0dd5b05SAlexander Shaposhnikov 
112cc4b2fb6SRafael Auler namespace {
113cc4b2fb6SRafael Auler 
114cc4b2fb6SRafael Auler /// A simple allocator that mmaps a fixed size region and manages this space
115cc4b2fb6SRafael Auler /// in a stack fashion, meaning you always deallocate the last element that
11616a497c6SRafael Auler /// was allocated. In practice, we don't need to deallocate individual elements.
11716a497c6SRafael Auler /// We monotonically increase our usage and then deallocate everything once we
11816a497c6SRafael Auler /// are done processing something.
119cc4b2fb6SRafael Auler class BumpPtrAllocator {
12016a497c6SRafael Auler   /// This is written before each allocation and act as a canary to detect when
12116a497c6SRafael Auler   /// a bug caused our program to cross allocation boundaries.
122cc4b2fb6SRafael Auler   struct EntryMetadata {
123cc4b2fb6SRafael Auler     uint64_t Magic;
124cc4b2fb6SRafael Auler     uint64_t AllocSize;
125cc4b2fb6SRafael Auler   };
1269bd71615SXun Li 
127cc4b2fb6SRafael Auler public:
128faaefff6SAlexander Shaposhnikov   void *allocate(size_t Size) {
12916a497c6SRafael Auler     Lock L(M);
130a0dd5b05SAlexander Shaposhnikov 
131cc4b2fb6SRafael Auler     if (StackBase == nullptr) {
132a0dd5b05SAlexander Shaposhnikov #if defined(__APPLE__)
133a0dd5b05SAlexander Shaposhnikov     int MAP_PRIVATE_MAP_ANONYMOUS = 0x1002;
134a0dd5b05SAlexander Shaposhnikov #else
135a0dd5b05SAlexander Shaposhnikov     int MAP_PRIVATE_MAP_ANONYMOUS = 0x22;
136a0dd5b05SAlexander Shaposhnikov #endif
13716a497c6SRafael Auler       StackBase = reinterpret_cast<uint8_t *>(
13816a497c6SRafael Auler           __mmap(0, MaxSize, 0x3 /* PROT_READ | PROT_WRITE*/,
13916a497c6SRafael Auler                  Shared ? 0x21 /*MAP_SHARED | MAP_ANONYMOUS*/
140a0dd5b05SAlexander Shaposhnikov                         : MAP_PRIVATE_MAP_ANONYMOUS /* MAP_PRIVATE | MAP_ANONYMOUS*/,
14116a497c6SRafael Auler                  -1, 0));
142cc4b2fb6SRafael Auler       StackSize = 0;
143cc4b2fb6SRafael Auler     }
144a0dd5b05SAlexander Shaposhnikov 
145cc4b2fb6SRafael Auler     Size = alignTo(Size + sizeof(EntryMetadata), 16);
146cc4b2fb6SRafael Auler     uint8_t *AllocAddress = StackBase + StackSize + sizeof(EntryMetadata);
147cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(StackBase + StackSize);
14816a497c6SRafael Auler     M->Magic = Magic;
149cc4b2fb6SRafael Auler     M->AllocSize = Size;
150cc4b2fb6SRafael Auler     StackSize += Size;
15116a497c6SRafael Auler     assert(StackSize < MaxSize, "allocator ran out of memory");
152cc4b2fb6SRafael Auler     return AllocAddress;
153cc4b2fb6SRafael Auler   }
154cc4b2fb6SRafael Auler 
15516a497c6SRafael Auler #ifdef DEBUG
15616a497c6SRafael Auler   /// Element-wise deallocation is only used for debugging to catch memory
15716a497c6SRafael Auler   /// bugs by checking magic bytes. Ordinarily, we reset the allocator once
15816a497c6SRafael Auler   /// we are done with it. Reset is done with clear(). There's no need
15916a497c6SRafael Auler   /// to deallocate each element individually.
160cc4b2fb6SRafael Auler   void deallocate(void *Ptr) {
16116a497c6SRafael Auler     Lock L(M);
162cc4b2fb6SRafael Auler     uint8_t MetadataOffset = sizeof(EntryMetadata);
163cc4b2fb6SRafael Auler     auto *M = reinterpret_cast<EntryMetadata *>(
164cc4b2fb6SRafael Auler         reinterpret_cast<uint8_t *>(Ptr) - MetadataOffset);
165cc4b2fb6SRafael Auler     const uint8_t *StackTop = StackBase + StackSize + MetadataOffset;
166cc4b2fb6SRafael Auler     // Validate size
167cc4b2fb6SRafael Auler     if (Ptr != StackTop - M->AllocSize) {
16816a497c6SRafael Auler       // Failed validation, check if it is a pointer returned by operator new []
169cc4b2fb6SRafael Auler       MetadataOffset +=
170cc4b2fb6SRafael Auler           sizeof(uint64_t); // Space for number of elements alloc'ed
171cc4b2fb6SRafael Auler       M = reinterpret_cast<EntryMetadata *>(reinterpret_cast<uint8_t *>(Ptr) -
172cc4b2fb6SRafael Auler                                             MetadataOffset);
17316a497c6SRafael Auler       // Ok, it failed both checks if this assertion fails. Stop the program, we
17416a497c6SRafael Auler       // have a memory bug.
175cc4b2fb6SRafael Auler       assert(Ptr == StackTop - M->AllocSize,
176cc4b2fb6SRafael Auler              "must deallocate the last element alloc'ed");
177cc4b2fb6SRafael Auler     }
17816a497c6SRafael Auler     assert(M->Magic == Magic, "allocator magic is corrupt");
179cc4b2fb6SRafael Auler     StackSize -= M->AllocSize;
180cc4b2fb6SRafael Auler   }
18116a497c6SRafael Auler #else
18216a497c6SRafael Auler   void deallocate(void *) {}
18316a497c6SRafael Auler #endif
18416a497c6SRafael Auler 
18516a497c6SRafael Auler   void clear() {
18616a497c6SRafael Auler     Lock L(M);
18716a497c6SRafael Auler     StackSize = 0;
18816a497c6SRafael Auler   }
18916a497c6SRafael Auler 
19016a497c6SRafael Auler   /// Set mmap reservation size (only relevant before first allocation)
1919bd71615SXun Li   void setMaxSize(uint64_t Size) { MaxSize = Size; }
19216a497c6SRafael Auler 
19316a497c6SRafael Auler   /// Set mmap reservation privacy (only relevant before first allocation)
1949bd71615SXun Li   void setShared(bool S) { Shared = S; }
19516a497c6SRafael Auler 
19616a497c6SRafael Auler   void destroy() {
19716a497c6SRafael Auler     if (StackBase == nullptr)
19816a497c6SRafael Auler       return;
19916a497c6SRafael Auler     __munmap(StackBase, MaxSize);
20016a497c6SRafael Auler   }
201cc4b2fb6SRafael Auler 
202cc4b2fb6SRafael Auler private:
20316a497c6SRafael Auler   static constexpr uint64_t Magic = 0x1122334455667788ull;
20416a497c6SRafael Auler   uint64_t MaxSize = 0xa00000;
205cc4b2fb6SRafael Auler   uint8_t *StackBase{nullptr};
206cc4b2fb6SRafael Auler   uint64_t StackSize{0};
20716a497c6SRafael Auler   bool Shared{false};
20816a497c6SRafael Auler   Mutex M;
209cc4b2fb6SRafael Auler };
210cc4b2fb6SRafael Auler 
21116a497c6SRafael Auler /// Used for allocating indirect call instrumentation counters. Initialized by
21216a497c6SRafael Auler /// __bolt_instr_setup, our initialization routine.
21316a497c6SRafael Auler BumpPtrAllocator GlobalAlloc;
214cc4b2fb6SRafael Auler } // anonymous namespace
215cc4b2fb6SRafael Auler 
216cc4b2fb6SRafael Auler // User-defined placement new operators. We only use those (as opposed to
217cc4b2fb6SRafael Auler // overriding the regular operator new) so we can keep our allocator in the
218cc4b2fb6SRafael Auler // stack instead of in a data section (global).
219faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A) { return A.allocate(Sz); }
220faaefff6SAlexander Shaposhnikov void *operator new(size_t Sz, BumpPtrAllocator &A, char C) {
221cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
222cc4b2fb6SRafael Auler   memSet(Ptr, C, Sz);
223cc4b2fb6SRafael Auler   return Ptr;
224cc4b2fb6SRafael Auler }
225faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A) {
226cc4b2fb6SRafael Auler   return A.allocate(Sz);
227cc4b2fb6SRafael Auler }
228faaefff6SAlexander Shaposhnikov void *operator new[](size_t Sz, BumpPtrAllocator &A, char C) {
229cc4b2fb6SRafael Auler   auto *Ptr = reinterpret_cast<char *>(A.allocate(Sz));
230cc4b2fb6SRafael Auler   memSet(Ptr, C, Sz);
231cc4b2fb6SRafael Auler   return Ptr;
232cc4b2fb6SRafael Auler }
233cc4b2fb6SRafael Auler // Only called during exception unwinding (useless). We must manually dealloc.
234cc4b2fb6SRafael Auler // C++ language weirdness
2359bd71615SXun Li void operator delete(void *Ptr, BumpPtrAllocator &A) { A.deallocate(Ptr); }
236cc4b2fb6SRafael Auler 
237cc4b2fb6SRafael Auler namespace {
238cc4b2fb6SRafael Auler 
23916a497c6SRafael Auler /// Basic key-val atom stored in our hash
24016a497c6SRafael Auler struct SimpleHashTableEntryBase {
24116a497c6SRafael Auler   uint64_t Key;
24216a497c6SRafael Auler   uint64_t Val;
24316a497c6SRafael Auler };
24416a497c6SRafael Auler 
24516a497c6SRafael Auler /// This hash table implementation starts by allocating a table of size
24616a497c6SRafael Auler /// InitialSize. When conflicts happen in this main table, it resolves
24716a497c6SRafael Auler /// them by chaining a new table of size IncSize. It never reallocs as our
24816a497c6SRafael Auler /// allocator doesn't support it. The key is intended to be function pointers.
24916a497c6SRafael Auler /// There's no clever hash function (it's just x mod size, size being prime).
25016a497c6SRafael Auler /// I never tuned the coefficientes in the modular equation (TODO)
25116a497c6SRafael Auler /// This is used for indirect calls (each call site has one of this, so it
25216a497c6SRafael Auler /// should have a small footprint) and for tallying call counts globally for
25316a497c6SRafael Auler /// each target to check if we missed the origin of some calls (this one is a
25416a497c6SRafael Auler /// large instantiation of this template, since it is global for all call sites)
25516a497c6SRafael Auler template <typename T = SimpleHashTableEntryBase, uint32_t InitialSize = 7,
25616a497c6SRafael Auler           uint32_t IncSize = 7>
25716a497c6SRafael Auler class SimpleHashTable {
25816a497c6SRafael Auler public:
25916a497c6SRafael Auler   using MapEntry = T;
26016a497c6SRafael Auler 
26116a497c6SRafael Auler   /// Increment by 1 the value of \p Key. If it is not in this table, it will be
26216a497c6SRafael Auler   /// added to the table and its value set to 1.
26316a497c6SRafael Auler   void incrementVal(uint64_t Key, BumpPtrAllocator &Alloc) {
26416a497c6SRafael Auler     ++get(Key, Alloc).Val;
26516a497c6SRafael Auler   }
26616a497c6SRafael Auler 
26716a497c6SRafael Auler   /// Basic member accessing interface. Here we pass the allocator explicitly to
26816a497c6SRafael Auler   /// avoid storing a pointer to it as part of this table (remember there is one
26916a497c6SRafael Auler   /// hash for each indirect call site, so we wan't to minimize our footprint).
27016a497c6SRafael Auler   MapEntry &get(uint64_t Key, BumpPtrAllocator &Alloc) {
27116a497c6SRafael Auler     Lock L(M);
27216a497c6SRafael Auler     if (TableRoot)
27316a497c6SRafael Auler       return getEntry(TableRoot, Key, Key, Alloc, 0);
27416a497c6SRafael Auler     return firstAllocation(Key, Alloc);
27516a497c6SRafael Auler   }
27616a497c6SRafael Auler 
27716a497c6SRafael Auler   /// Traverses all elements in the table
27816a497c6SRafael Auler   template <typename... Args>
27916a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...), Args... args) {
28016a497c6SRafael Auler     if (!TableRoot)
28116a497c6SRafael Auler       return;
28216a497c6SRafael Auler     return forEachElement(Callback, InitialSize, TableRoot, args...);
28316a497c6SRafael Auler   }
28416a497c6SRafael Auler 
28516a497c6SRafael Auler   void resetCounters();
28616a497c6SRafael Auler 
28716a497c6SRafael Auler private:
28816a497c6SRafael Auler   constexpr static uint64_t VacantMarker = 0;
28916a497c6SRafael Auler   constexpr static uint64_t FollowUpTableMarker = 0x8000000000000000ull;
29016a497c6SRafael Auler 
29116a497c6SRafael Auler   MapEntry *TableRoot{nullptr};
29216a497c6SRafael Auler   Mutex M;
29316a497c6SRafael Auler 
29416a497c6SRafael Auler   template <typename... Args>
29516a497c6SRafael Auler   void forEachElement(void (*Callback)(MapEntry &, Args...),
29616a497c6SRafael Auler                       uint32_t NumEntries, MapEntry *Entries, Args... args) {
297c7306cc2SAmir Ayupov     for (uint32_t I = 0; I < NumEntries; ++I) {
298c7306cc2SAmir Ayupov       MapEntry &Entry = Entries[I];
29916a497c6SRafael Auler       if (Entry.Key == VacantMarker)
30016a497c6SRafael Auler         continue;
30116a497c6SRafael Auler       if (Entry.Key & FollowUpTableMarker) {
30216a497c6SRafael Auler         forEachElement(Callback, IncSize,
30316a497c6SRafael Auler                        reinterpret_cast<MapEntry *>(Entry.Key &
30416a497c6SRafael Auler                                                     ~FollowUpTableMarker),
30516a497c6SRafael Auler                        args...);
30616a497c6SRafael Auler         continue;
30716a497c6SRafael Auler       }
30816a497c6SRafael Auler       Callback(Entry, args...);
30916a497c6SRafael Auler     }
31016a497c6SRafael Auler   }
31116a497c6SRafael Auler 
31216a497c6SRafael Auler   MapEntry &firstAllocation(uint64_t Key, BumpPtrAllocator &Alloc) {
31316a497c6SRafael Auler     TableRoot = new (Alloc, 0) MapEntry[InitialSize];
314c7306cc2SAmir Ayupov     MapEntry &Entry = TableRoot[Key % InitialSize];
31516a497c6SRafael Auler     Entry.Key = Key;
31616a497c6SRafael Auler     return Entry;
31716a497c6SRafael Auler   }
31816a497c6SRafael Auler 
31916a497c6SRafael Auler   MapEntry &getEntry(MapEntry *Entries, uint64_t Key, uint64_t Selector,
32016a497c6SRafael Auler                      BumpPtrAllocator &Alloc, int CurLevel) {
32116a497c6SRafael Auler     const uint32_t NumEntries = CurLevel == 0 ? InitialSize : IncSize;
32216a497c6SRafael Auler     uint64_t Remainder = Selector / NumEntries;
32316a497c6SRafael Auler     Selector = Selector % NumEntries;
324c7306cc2SAmir Ayupov     MapEntry &Entry = Entries[Selector];
32516a497c6SRafael Auler 
32616a497c6SRafael Auler     // A hit
32716a497c6SRafael Auler     if (Entry.Key == Key) {
32816a497c6SRafael Auler       return Entry;
32916a497c6SRafael Auler     }
33016a497c6SRafael Auler 
33116a497c6SRafael Auler     // Vacant - add new entry
33216a497c6SRafael Auler     if (Entry.Key == VacantMarker) {
33316a497c6SRafael Auler       Entry.Key = Key;
33416a497c6SRafael Auler       return Entry;
33516a497c6SRafael Auler     }
33616a497c6SRafael Auler 
33716a497c6SRafael Auler     // Defer to the next level
33816a497c6SRafael Auler     if (Entry.Key & FollowUpTableMarker) {
33916a497c6SRafael Auler       return getEntry(
34016a497c6SRafael Auler           reinterpret_cast<MapEntry *>(Entry.Key & ~FollowUpTableMarker),
34116a497c6SRafael Auler           Key, Remainder, Alloc, CurLevel + 1);
34216a497c6SRafael Auler     }
34316a497c6SRafael Auler 
34416a497c6SRafael Auler     // Conflict - create the next level
34516a497c6SRafael Auler     MapEntry *NextLevelTbl = new (Alloc, 0) MapEntry[IncSize];
34616a497c6SRafael Auler     uint64_t CurEntrySelector = Entry.Key / InitialSize;
34716a497c6SRafael Auler     for (int I = 0; I < CurLevel; ++I)
34816a497c6SRafael Auler       CurEntrySelector /= IncSize;
34916a497c6SRafael Auler     CurEntrySelector = CurEntrySelector % IncSize;
35016a497c6SRafael Auler     NextLevelTbl[CurEntrySelector] = Entry;
35116a497c6SRafael Auler     Entry.Key = reinterpret_cast<uint64_t>(NextLevelTbl) | FollowUpTableMarker;
35216a497c6SRafael Auler     return getEntry(NextLevelTbl, Key, Remainder, Alloc, CurLevel + 1);
35316a497c6SRafael Auler   }
35416a497c6SRafael Auler };
35516a497c6SRafael Auler 
35616a497c6SRafael Auler template <typename T> void resetIndCallCounter(T &Entry) {
35716a497c6SRafael Auler   Entry.Val = 0;
35816a497c6SRafael Auler }
35916a497c6SRafael Auler 
36016a497c6SRafael Auler template <typename T, uint32_t X, uint32_t Y>
36116a497c6SRafael Auler void SimpleHashTable<T, X, Y>::resetCounters() {
36216a497c6SRafael Auler   Lock L(M);
36316a497c6SRafael Auler   forEachElement(resetIndCallCounter);
36416a497c6SRafael Auler }
36516a497c6SRafael Auler 
36616a497c6SRafael Auler /// Represents a hash table mapping a function target address to its counter.
36716a497c6SRafael Auler using IndirectCallHashTable = SimpleHashTable<>;
36816a497c6SRafael Auler 
36916a497c6SRafael Auler /// Initialize with number 1 instead of 0 so we don't go into .bss. This is the
37016a497c6SRafael Auler /// global array of all hash tables storing indirect call destinations happening
37116a497c6SRafael Auler /// during runtime, one table per call site.
37216a497c6SRafael Auler IndirectCallHashTable *GlobalIndCallCounters{
37316a497c6SRafael Auler     reinterpret_cast<IndirectCallHashTable *>(1)};
37416a497c6SRafael Auler 
37516a497c6SRafael Auler /// Don't allow reentrancy in the fdata writing phase - only one thread writes
37616a497c6SRafael Auler /// it
37716a497c6SRafael Auler Mutex *GlobalWriteProfileMutex{reinterpret_cast<Mutex *>(1)};
37816a497c6SRafael Auler 
37916a497c6SRafael Auler /// Store number of calls in additional to target address (Key) and frequency
38016a497c6SRafael Auler /// as perceived by the basic block counter (Val).
38116a497c6SRafael Auler struct CallFlowEntryBase : public SimpleHashTableEntryBase {
38216a497c6SRafael Auler   uint64_t Calls;
38316a497c6SRafael Auler };
38416a497c6SRafael Auler 
38516a497c6SRafael Auler using CallFlowHashTableBase = SimpleHashTable<CallFlowEntryBase, 11939, 233>;
38616a497c6SRafael Auler 
38716a497c6SRafael Auler /// This is a large table indexing all possible call targets (indirect and
38816a497c6SRafael Auler /// direct ones). The goal is to find mismatches between number of calls (for
38916a497c6SRafael Auler /// those calls we were able to track) and the entry basic block counter of the
39016a497c6SRafael Auler /// callee. In most cases, these two should be equal. If not, there are two
39116a497c6SRafael Auler /// possible scenarios here:
39216a497c6SRafael Auler ///
39316a497c6SRafael Auler ///  * Entry BB has higher frequency than all known calls to this function.
39416a497c6SRafael Auler ///    In this case, we have dynamic library code or any uninstrumented code
39516a497c6SRafael Auler ///    calling this function. We will write the profile for these untracked
39616a497c6SRafael Auler ///    calls as having source "0 [unknown] 0" in the fdata file.
39716a497c6SRafael Auler ///
39816a497c6SRafael Auler ///  * Number of known calls is higher than the frequency of entry BB
39916a497c6SRafael Auler ///    This only happens when there is no counter for the entry BB / callee
40016a497c6SRafael Auler ///    function is not simple (in BOLT terms). We don't do anything special
40116a497c6SRafael Auler ///    here and just ignore those (we still report all calls to the non-simple
40216a497c6SRafael Auler ///    function, though).
40316a497c6SRafael Auler ///
40416a497c6SRafael Auler class CallFlowHashTable : public CallFlowHashTableBase {
40516a497c6SRafael Auler public:
40616a497c6SRafael Auler   CallFlowHashTable(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
40716a497c6SRafael Auler 
40816a497c6SRafael Auler   MapEntry &get(uint64_t Key) { return CallFlowHashTableBase::get(Key, Alloc); }
40916a497c6SRafael Auler 
41016a497c6SRafael Auler private:
41116a497c6SRafael Auler   // Different than the hash table for indirect call targets, we do store the
41216a497c6SRafael Auler   // allocator here since there is only one call flow hash and space overhead
41316a497c6SRafael Auler   // is negligible.
41416a497c6SRafael Auler   BumpPtrAllocator &Alloc;
41516a497c6SRafael Auler };
41616a497c6SRafael Auler 
41716a497c6SRafael Auler ///
41816a497c6SRafael Auler /// Description metadata emitted by BOLT to describe the program - refer to
41916a497c6SRafael Auler /// Passes/Instrumentation.cpp - Instrumentation::emitTablesAsELFNote()
42016a497c6SRafael Auler ///
42116a497c6SRafael Auler struct Location {
42216a497c6SRafael Auler   uint32_t FunctionName;
42316a497c6SRafael Auler   uint32_t Offset;
42416a497c6SRafael Auler };
42516a497c6SRafael Auler 
42616a497c6SRafael Auler struct CallDescription {
42716a497c6SRafael Auler   Location From;
42816a497c6SRafael Auler   uint32_t FromNode;
42916a497c6SRafael Auler   Location To;
43016a497c6SRafael Auler   uint32_t Counter;
43116a497c6SRafael Auler   uint64_t TargetAddress;
43216a497c6SRafael Auler };
43316a497c6SRafael Auler 
43416a497c6SRafael Auler using IndCallDescription = Location;
43516a497c6SRafael Auler 
43616a497c6SRafael Auler struct IndCallTargetDescription {
43716a497c6SRafael Auler   Location Loc;
43816a497c6SRafael Auler   uint64_t Address;
43916a497c6SRafael Auler };
44016a497c6SRafael Auler 
44116a497c6SRafael Auler struct EdgeDescription {
44216a497c6SRafael Auler   Location From;
44316a497c6SRafael Auler   uint32_t FromNode;
44416a497c6SRafael Auler   Location To;
44516a497c6SRafael Auler   uint32_t ToNode;
44616a497c6SRafael Auler   uint32_t Counter;
44716a497c6SRafael Auler };
44816a497c6SRafael Auler 
44916a497c6SRafael Auler struct InstrumentedNode {
45016a497c6SRafael Auler   uint32_t Node;
45116a497c6SRafael Auler   uint32_t Counter;
45216a497c6SRafael Auler };
45316a497c6SRafael Auler 
45416a497c6SRafael Auler struct EntryNode {
45516a497c6SRafael Auler   uint64_t Node;
45616a497c6SRafael Auler   uint64_t Address;
45716a497c6SRafael Auler };
45816a497c6SRafael Auler 
45916a497c6SRafael Auler struct FunctionDescription {
46016a497c6SRafael Auler   uint32_t NumLeafNodes;
46116a497c6SRafael Auler   const InstrumentedNode *LeafNodes;
46216a497c6SRafael Auler   uint32_t NumEdges;
46316a497c6SRafael Auler   const EdgeDescription *Edges;
46416a497c6SRafael Auler   uint32_t NumCalls;
46516a497c6SRafael Auler   const CallDescription *Calls;
46616a497c6SRafael Auler   uint32_t NumEntryNodes;
46716a497c6SRafael Auler   const EntryNode *EntryNodes;
46816a497c6SRafael Auler 
46916a497c6SRafael Auler   /// Constructor will parse the serialized function metadata written by BOLT
47016a497c6SRafael Auler   FunctionDescription(const uint8_t *FuncDesc);
47116a497c6SRafael Auler 
47216a497c6SRafael Auler   uint64_t getSize() const {
47316a497c6SRafael Auler     return 16 + NumLeafNodes * sizeof(InstrumentedNode) +
47416a497c6SRafael Auler            NumEdges * sizeof(EdgeDescription) +
47516a497c6SRafael Auler            NumCalls * sizeof(CallDescription) +
47616a497c6SRafael Auler            NumEntryNodes * sizeof(EntryNode);
47716a497c6SRafael Auler   }
47816a497c6SRafael Auler };
47916a497c6SRafael Auler 
48016a497c6SRafael Auler /// The context is created when the fdata profile needs to be written to disk
48116a497c6SRafael Auler /// and we need to interpret our runtime counters. It contains pointers to the
48216a497c6SRafael Auler /// mmaped binary (only the BOLT written metadata section). Deserialization
48316a497c6SRafael Auler /// should be straightforward as most data is POD or an array of POD elements.
48416a497c6SRafael Auler /// This metadata is used to reconstruct function CFGs.
48516a497c6SRafael Auler struct ProfileWriterContext {
48616a497c6SRafael Auler   IndCallDescription *IndCallDescriptions;
48716a497c6SRafael Auler   IndCallTargetDescription *IndCallTargets;
48816a497c6SRafael Auler   uint8_t *FuncDescriptions;
48916a497c6SRafael Auler   char *Strings;  // String table with function names used in this binary
49016a497c6SRafael Auler   int FileDesc;   // File descriptor for the file on disk backing this
49116a497c6SRafael Auler                   // information in memory via mmap
49216a497c6SRafael Auler   void *MMapPtr;  // The mmap ptr
49316a497c6SRafael Auler   int MMapSize;   // The mmap size
49416a497c6SRafael Auler 
49516a497c6SRafael Auler   /// Hash table storing all possible call destinations to detect untracked
49616a497c6SRafael Auler   /// calls and correctly report them as [unknown] in output fdata.
49716a497c6SRafael Auler   CallFlowHashTable *CallFlowTable;
49816a497c6SRafael Auler 
49916a497c6SRafael Auler   /// Lookup the sorted indirect call target vector to fetch function name and
50016a497c6SRafael Auler   /// offset for an arbitrary function pointer.
50116a497c6SRafael Auler   const IndCallTargetDescription *lookupIndCallTarget(uint64_t Target) const;
50216a497c6SRafael Auler };
50316a497c6SRafael Auler 
50416a497c6SRafael Auler /// Perform a string comparison and returns zero if Str1 matches Str2. Compares
50516a497c6SRafael Auler /// at most Size characters.
506cc4b2fb6SRafael Auler int compareStr(const char *Str1, const char *Str2, int Size) {
507821480d2SRafael Auler   while (*Str1 == *Str2) {
508821480d2SRafael Auler     if (*Str1 == '\0' || --Size == 0)
509821480d2SRafael Auler       return 0;
510821480d2SRafael Auler     ++Str1;
511821480d2SRafael Auler     ++Str2;
512821480d2SRafael Auler   }
513821480d2SRafael Auler   return 1;
514821480d2SRafael Auler }
515821480d2SRafael Auler 
51616a497c6SRafael Auler /// Output Location to the fdata file
51716a497c6SRafael Auler char *serializeLoc(const ProfileWriterContext &Ctx, char *OutBuf,
518cc4b2fb6SRafael Auler                    const Location Loc, uint32_t BufSize) {
519821480d2SRafael Auler   // fdata location format: Type Name Offset
520821480d2SRafael Auler   // Type 1 - regular symbol
521821480d2SRafael Auler   OutBuf = strCopy(OutBuf, "1 ");
52216a497c6SRafael Auler   const char *Str = Ctx.Strings + Loc.FunctionName;
523cc4b2fb6SRafael Auler   uint32_t Size = 25;
52462aa74f8SRafael Auler   while (*Str) {
52562aa74f8SRafael Auler     *OutBuf++ = *Str++;
526cc4b2fb6SRafael Auler     if (++Size >= BufSize)
527cc4b2fb6SRafael Auler       break;
52862aa74f8SRafael Auler   }
529cc4b2fb6SRafael Auler   assert(!*Str, "buffer overflow, function name too large");
53062aa74f8SRafael Auler   *OutBuf++ = ' ';
531821480d2SRafael Auler   OutBuf = intToStr(OutBuf, Loc.Offset, 16);
53262aa74f8SRafael Auler   *OutBuf++ = ' ';
53362aa74f8SRafael Auler   return OutBuf;
53462aa74f8SRafael Auler }
53562aa74f8SRafael Auler 
53616a497c6SRafael Auler /// Read and deserialize a function description written by BOLT. \p FuncDesc
53716a497c6SRafael Auler /// points at the beginning of the function metadata structure in the file.
53816a497c6SRafael Auler /// See Instrumentation::emitTablesAsELFNote()
53916a497c6SRafael Auler FunctionDescription::FunctionDescription(const uint8_t *FuncDesc) {
54016a497c6SRafael Auler   NumLeafNodes = *reinterpret_cast<const uint32_t *>(FuncDesc);
54116a497c6SRafael Auler   DEBUG(reportNumber("NumLeafNodes = ", NumLeafNodes, 10));
54216a497c6SRafael Auler   LeafNodes = reinterpret_cast<const InstrumentedNode *>(FuncDesc + 4);
54316a497c6SRafael Auler 
54416a497c6SRafael Auler   NumEdges = *reinterpret_cast<const uint32_t *>(
54516a497c6SRafael Auler       FuncDesc + 4 + NumLeafNodes * sizeof(InstrumentedNode));
54616a497c6SRafael Auler   DEBUG(reportNumber("NumEdges = ", NumEdges, 10));
54716a497c6SRafael Auler   Edges = reinterpret_cast<const EdgeDescription *>(
54816a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode));
54916a497c6SRafael Auler 
55016a497c6SRafael Auler   NumCalls = *reinterpret_cast<const uint32_t *>(
55116a497c6SRafael Auler       FuncDesc + 8 + NumLeafNodes * sizeof(InstrumentedNode) +
55216a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
55316a497c6SRafael Auler   DEBUG(reportNumber("NumCalls = ", NumCalls, 10));
55416a497c6SRafael Auler   Calls = reinterpret_cast<const CallDescription *>(
55516a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
55616a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription));
55716a497c6SRafael Auler   NumEntryNodes = *reinterpret_cast<const uint32_t *>(
55816a497c6SRafael Auler       FuncDesc + 12 + NumLeafNodes * sizeof(InstrumentedNode) +
55916a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
56016a497c6SRafael Auler   DEBUG(reportNumber("NumEntryNodes = ", NumEntryNodes, 10));
56116a497c6SRafael Auler   EntryNodes = reinterpret_cast<const EntryNode *>(
56216a497c6SRafael Auler       FuncDesc + 16 + NumLeafNodes * sizeof(InstrumentedNode) +
56316a497c6SRafael Auler       NumEdges * sizeof(EdgeDescription) + NumCalls * sizeof(CallDescription));
56416a497c6SRafael Auler }
56516a497c6SRafael Auler 
56616a497c6SRafael Auler /// Read and mmap descriptions written by BOLT from the executable's notes
56716a497c6SRafael Auler /// section
568a0dd5b05SAlexander Shaposhnikov #if defined(HAVE_ELF_H) and !defined(__APPLE__)
5692ffd6e2bSElvina Yakubova 
5702ffd6e2bSElvina Yakubova void *__attribute__((noinline)) __get_pc() {
5712ffd6e2bSElvina Yakubova   return __builtin_extract_return_addr(__builtin_return_address(0));
5722ffd6e2bSElvina Yakubova }
5732ffd6e2bSElvina Yakubova 
5742ffd6e2bSElvina Yakubova /// Get string with address and parse it to hex pair <StartAddress, EndAddress>
5752ffd6e2bSElvina Yakubova bool parseAddressRange(const char *Str, uint64_t &StartAddress,
5762ffd6e2bSElvina Yakubova                        uint64_t &EndAddress) {
5772ffd6e2bSElvina Yakubova   if (!Str)
5782ffd6e2bSElvina Yakubova     return false;
5792ffd6e2bSElvina Yakubova   // Parsed string format: <hex1>-<hex2>
5802ffd6e2bSElvina Yakubova   StartAddress = hexToLong(Str, '-');
5812ffd6e2bSElvina Yakubova   while (*Str && *Str != '-')
5822ffd6e2bSElvina Yakubova     ++Str;
5832ffd6e2bSElvina Yakubova   if (!*Str)
5842ffd6e2bSElvina Yakubova     return false;
5852ffd6e2bSElvina Yakubova   ++Str; // swallow '-'
5862ffd6e2bSElvina Yakubova   EndAddress = hexToLong(Str);
5872ffd6e2bSElvina Yakubova   return true;
5882ffd6e2bSElvina Yakubova }
5892ffd6e2bSElvina Yakubova 
5902ffd6e2bSElvina Yakubova /// Get full path to the real binary by getting current virtual address
5912ffd6e2bSElvina Yakubova /// and searching for the appropriate link in address range in
5922ffd6e2bSElvina Yakubova /// /proc/self/map_files
5932ffd6e2bSElvina Yakubova static char *getBinaryPath() {
5942ffd6e2bSElvina Yakubova   const uint32_t BufSize = 1024;
5952ffd6e2bSElvina Yakubova   const uint32_t NameMax = 256;
5962ffd6e2bSElvina Yakubova   const char DirPath[] = "/proc/self/map_files/";
5972ffd6e2bSElvina Yakubova   static char TargetPath[NameMax] = {};
5982ffd6e2bSElvina Yakubova   char Buf[BufSize];
5992ffd6e2bSElvina Yakubova 
6002ffd6e2bSElvina Yakubova   if (TargetPath[0] != '\0')
6012ffd6e2bSElvina Yakubova     return TargetPath;
6022ffd6e2bSElvina Yakubova 
6032ffd6e2bSElvina Yakubova   unsigned long CurAddr = (unsigned long)__get_pc();
6042ffd6e2bSElvina Yakubova   uint64_t FDdir = __open(DirPath,
605821480d2SRafael Auler                           /*flags=*/0 /*O_RDONLY*/,
606821480d2SRafael Auler                           /*mode=*/0666);
6072ffd6e2bSElvina Yakubova   assert(static_cast<int64_t>(FDdir) > 0,
6082ffd6e2bSElvina Yakubova          "failed to open /proc/self/map_files");
6092ffd6e2bSElvina Yakubova 
6102ffd6e2bSElvina Yakubova   while (long Nread = __getdents(FDdir, (struct dirent *)Buf, BufSize)) {
6112ffd6e2bSElvina Yakubova     assert(static_cast<int64_t>(Nread) != -1, "failed to get folder entries");
6122ffd6e2bSElvina Yakubova 
6132ffd6e2bSElvina Yakubova     struct dirent *d;
6142ffd6e2bSElvina Yakubova     for (long Bpos = 0; Bpos < Nread; Bpos += d->d_reclen) {
6152ffd6e2bSElvina Yakubova       d = (struct dirent *)(Buf + Bpos);
6162ffd6e2bSElvina Yakubova 
6172ffd6e2bSElvina Yakubova       uint64_t StartAddress, EndAddress;
6182ffd6e2bSElvina Yakubova       if (!parseAddressRange(d->d_name, StartAddress, EndAddress))
6192ffd6e2bSElvina Yakubova         continue;
6202ffd6e2bSElvina Yakubova       if (CurAddr < StartAddress || CurAddr > EndAddress)
6212ffd6e2bSElvina Yakubova         continue;
6222ffd6e2bSElvina Yakubova       char FindBuf[NameMax];
6232ffd6e2bSElvina Yakubova       char *C = strCopy(FindBuf, DirPath, NameMax);
6242ffd6e2bSElvina Yakubova       C = strCopy(C, d->d_name, NameMax - (C - FindBuf));
6252ffd6e2bSElvina Yakubova       *C = '\0';
6262ffd6e2bSElvina Yakubova       uint32_t Ret = __readlink(FindBuf, TargetPath, sizeof(TargetPath));
6272ffd6e2bSElvina Yakubova       assert(Ret != -1 && Ret != BufSize, "readlink error");
6282ffd6e2bSElvina Yakubova       TargetPath[Ret] = '\0';
6292ffd6e2bSElvina Yakubova       return TargetPath;
6302ffd6e2bSElvina Yakubova     }
6312ffd6e2bSElvina Yakubova   }
6322ffd6e2bSElvina Yakubova   return nullptr;
6332ffd6e2bSElvina Yakubova }
6342ffd6e2bSElvina Yakubova 
6352ffd6e2bSElvina Yakubova ProfileWriterContext readDescriptions() {
6362ffd6e2bSElvina Yakubova   ProfileWriterContext Result;
6372ffd6e2bSElvina Yakubova   char *BinPath = getBinaryPath();
6382ffd6e2bSElvina Yakubova   assert(BinPath && BinPath[0] != '\0', "failed to find binary path");
6392ffd6e2bSElvina Yakubova 
6402ffd6e2bSElvina Yakubova   uint64_t FD = __open(BinPath,
6412ffd6e2bSElvina Yakubova                        /*flags=*/0 /*O_RDONLY*/,
6422ffd6e2bSElvina Yakubova                        /*mode=*/0666);
6432ffd6e2bSElvina Yakubova   assert(static_cast<int64_t>(FD) > 0, "failed to open binary path");
6442ffd6e2bSElvina Yakubova 
645821480d2SRafael Auler   Result.FileDesc = FD;
646821480d2SRafael Auler 
647821480d2SRafael Auler   // mmap our binary to memory
648821480d2SRafael Auler   uint64_t Size = __lseek(FD, 0, 2 /*SEEK_END*/);
649821480d2SRafael Auler   uint8_t *BinContents = reinterpret_cast<uint8_t *>(
650821480d2SRafael Auler       __mmap(0, Size, 0x1 /* PROT_READ*/, 0x2 /* MAP_PRIVATE*/, FD, 0));
651821480d2SRafael Auler   Result.MMapPtr = BinContents;
652821480d2SRafael Auler   Result.MMapSize = Size;
653821480d2SRafael Auler   Elf64_Ehdr *Hdr = reinterpret_cast<Elf64_Ehdr *>(BinContents);
654821480d2SRafael Auler   Elf64_Shdr *Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff);
655821480d2SRafael Auler   Elf64_Shdr *StringTblHeader = reinterpret_cast<Elf64_Shdr *>(
656821480d2SRafael Auler       BinContents + Hdr->e_shoff + Hdr->e_shstrndx * Hdr->e_shentsize);
657821480d2SRafael Auler 
658821480d2SRafael Auler   // Find .bolt.instr.tables with the data we need and set pointers to it
659821480d2SRafael Auler   for (int I = 0; I < Hdr->e_shnum; ++I) {
660821480d2SRafael Auler     char *SecName = reinterpret_cast<char *>(
661821480d2SRafael Auler         BinContents + StringTblHeader->sh_offset + Shdr->sh_name);
662821480d2SRafael Auler     if (compareStr(SecName, ".bolt.instr.tables", 64) != 0) {
663821480d2SRafael Auler       Shdr = reinterpret_cast<Elf64_Shdr *>(BinContents + Hdr->e_shoff +
664821480d2SRafael Auler                                             (I + 1) * Hdr->e_shentsize);
665821480d2SRafael Auler       continue;
666821480d2SRafael Auler     }
667821480d2SRafael Auler     // Actual contents of the ELF note start after offset 20 decimal:
668821480d2SRafael Auler     // Offset 0: Producer name size (4 bytes)
669821480d2SRafael Auler     // Offset 4: Contents size (4 bytes)
670821480d2SRafael Auler     // Offset 8: Note type (4 bytes)
671821480d2SRafael Auler     // Offset 12: Producer name (BOLT\0) (5 bytes + align to 4-byte boundary)
672821480d2SRafael Auler     // Offset 20: Contents
67316a497c6SRafael Auler     uint32_t IndCallDescSize =
674cc4b2fb6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 20);
67516a497c6SRafael Auler     uint32_t IndCallTargetDescSize = *reinterpret_cast<uint32_t *>(
67616a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24 + IndCallDescSize);
67716a497c6SRafael Auler     uint32_t FuncDescSize =
67816a497c6SRafael Auler         *reinterpret_cast<uint32_t *>(BinContents + Shdr->sh_offset + 28 +
67916a497c6SRafael Auler                                       IndCallDescSize + IndCallTargetDescSize);
68016a497c6SRafael Auler     Result.IndCallDescriptions = reinterpret_cast<IndCallDescription *>(
68116a497c6SRafael Auler         BinContents + Shdr->sh_offset + 24);
68216a497c6SRafael Auler     Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
68316a497c6SRafael Auler         BinContents + Shdr->sh_offset + 28 + IndCallDescSize);
68416a497c6SRafael Auler     Result.FuncDescriptions = BinContents + Shdr->sh_offset + 32 +
68516a497c6SRafael Auler                               IndCallDescSize + IndCallTargetDescSize;
68616a497c6SRafael Auler     Result.Strings = reinterpret_cast<char *>(
68716a497c6SRafael Auler         BinContents + Shdr->sh_offset + 32 + IndCallDescSize +
68816a497c6SRafael Auler         IndCallTargetDescSize + FuncDescSize);
689821480d2SRafael Auler     return Result;
690821480d2SRafael Auler   }
691821480d2SRafael Auler   const char ErrMsg[] =
692821480d2SRafael Auler       "BOLT instrumentation runtime error: could not find section "
693821480d2SRafael Auler       ".bolt.instr.tables\n";
694821480d2SRafael Auler   reportError(ErrMsg, sizeof(ErrMsg));
695821480d2SRafael Auler   return Result;
696821480d2SRafael Auler }
697a0dd5b05SAlexander Shaposhnikov 
698ba31344fSRafael Auler #else
699a0dd5b05SAlexander Shaposhnikov 
70016a497c6SRafael Auler ProfileWriterContext readDescriptions() {
70116a497c6SRafael Auler   ProfileWriterContext Result;
702a0dd5b05SAlexander Shaposhnikov   uint8_t *Tables = _bolt_instr_tables_getter();
703a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallDescSize = *reinterpret_cast<uint32_t *>(Tables);
704a0dd5b05SAlexander Shaposhnikov   uint32_t IndCallTargetDescSize =
705a0dd5b05SAlexander Shaposhnikov       *reinterpret_cast<uint32_t *>(Tables + 4 + IndCallDescSize);
706a0dd5b05SAlexander Shaposhnikov   uint32_t FuncDescSize = *reinterpret_cast<uint32_t *>(
707a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize + IndCallTargetDescSize);
708a0dd5b05SAlexander Shaposhnikov   Result.IndCallDescriptions =
709a0dd5b05SAlexander Shaposhnikov       reinterpret_cast<IndCallDescription *>(Tables + 4);
710a0dd5b05SAlexander Shaposhnikov   Result.IndCallTargets = reinterpret_cast<IndCallTargetDescription *>(
711a0dd5b05SAlexander Shaposhnikov       Tables + 8 + IndCallDescSize);
712a0dd5b05SAlexander Shaposhnikov   Result.FuncDescriptions =
713a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize;
714a0dd5b05SAlexander Shaposhnikov   Result.Strings = reinterpret_cast<char *>(
715a0dd5b05SAlexander Shaposhnikov       Tables + 12 + IndCallDescSize + IndCallTargetDescSize + FuncDescSize);
716ba31344fSRafael Auler   return Result;
717ba31344fSRafael Auler }
718a0dd5b05SAlexander Shaposhnikov 
719ba31344fSRafael Auler #endif
720821480d2SRafael Auler 
721a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
72216a497c6SRafael Auler /// Debug by printing overall metadata global numbers to check it is sane
72316a497c6SRafael Auler void printStats(const ProfileWriterContext &Ctx) {
724cc4b2fb6SRafael Auler   char StatMsg[BufSize];
725cc4b2fb6SRafael Auler   char *StatPtr = StatMsg;
72616a497c6SRafael Auler   StatPtr =
72716a497c6SRafael Auler       strCopy(StatPtr,
72816a497c6SRafael Auler               "\nBOLT INSTRUMENTATION RUNTIME STATISTICS\n\nIndCallDescSize: ");
729cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr,
73016a497c6SRafael Auler                      Ctx.FuncDescriptions -
73116a497c6SRafael Auler                          reinterpret_cast<uint8_t *>(Ctx.IndCallDescriptions),
732cc4b2fb6SRafael Auler                      10);
733cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\nFuncDescSize: ");
734cc4b2fb6SRafael Auler   StatPtr = intToStr(
735cc4b2fb6SRafael Auler       StatPtr,
73616a497c6SRafael Auler       reinterpret_cast<uint8_t *>(Ctx.Strings) - Ctx.FuncDescriptions, 10);
73716a497c6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_ind_calls: ");
73816a497c6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_ind_calls, 10);
739cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n__bolt_instr_num_funcs: ");
740cc4b2fb6SRafael Auler   StatPtr = intToStr(StatPtr, __bolt_instr_num_funcs, 10);
741cc4b2fb6SRafael Auler   StatPtr = strCopy(StatPtr, "\n");
742cc4b2fb6SRafael Auler   __write(2, StatMsg, StatPtr - StatMsg);
743cc4b2fb6SRafael Auler }
744a0dd5b05SAlexander Shaposhnikov #endif
745a0dd5b05SAlexander Shaposhnikov 
746cc4b2fb6SRafael Auler 
747cc4b2fb6SRafael Auler /// This is part of a simple CFG representation in memory, where we store
748cc4b2fb6SRafael Auler /// a dynamically sized array of input and output edges per node, and store
749cc4b2fb6SRafael Auler /// a dynamically sized array of nodes per graph. We also store the spanning
750cc4b2fb6SRafael Auler /// tree edges for that CFG in a separate array of nodes in
751cc4b2fb6SRafael Auler /// \p SpanningTreeNodes, while the regular nodes live in \p CFGNodes.
752cc4b2fb6SRafael Auler struct Edge {
753cc4b2fb6SRafael Auler   uint32_t Node; // Index in nodes array regarding the destination of this edge
754cc4b2fb6SRafael Auler   uint32_t ID;   // Edge index in an array comprising all edges of the graph
755cc4b2fb6SRafael Auler };
756cc4b2fb6SRafael Auler 
757cc4b2fb6SRafael Auler /// A regular graph node or a spanning tree node
758cc4b2fb6SRafael Auler struct Node {
759cc4b2fb6SRafael Auler   uint32_t NumInEdges{0};  // Input edge count used to size InEdge
760cc4b2fb6SRafael Auler   uint32_t NumOutEdges{0}; // Output edge count used to size OutEdges
761cc4b2fb6SRafael Auler   Edge *InEdges{nullptr};  // Created and managed by \p Graph
762cc4b2fb6SRafael Auler   Edge *OutEdges{nullptr}; // ditto
763cc4b2fb6SRafael Auler };
764cc4b2fb6SRafael Auler 
765cc4b2fb6SRafael Auler /// Main class for CFG representation in memory. Manages object creation and
766cc4b2fb6SRafael Auler /// destruction, populates an array of CFG nodes as well as corresponding
767cc4b2fb6SRafael Auler /// spanning tree nodes.
768cc4b2fb6SRafael Auler struct Graph {
769cc4b2fb6SRafael Auler   uint32_t NumNodes;
770cc4b2fb6SRafael Auler   Node *CFGNodes;
771cc4b2fb6SRafael Auler   Node *SpanningTreeNodes;
77216a497c6SRafael Auler   uint64_t *EdgeFreqs;
77316a497c6SRafael Auler   uint64_t *CallFreqs;
774cc4b2fb6SRafael Auler   BumpPtrAllocator &Alloc;
77516a497c6SRafael Auler   const FunctionDescription &D;
776cc4b2fb6SRafael Auler 
77716a497c6SRafael Auler   /// Reads a list of edges from function description \p D and builds
778cc4b2fb6SRafael Auler   /// the graph from it. Allocates several internal dynamic structures that are
77916a497c6SRafael Auler   /// later destroyed by ~Graph() and uses \p Alloc. D.LeafNodes contain all
780cc4b2fb6SRafael Auler   /// spanning tree leaf nodes descriptions (their counters). They are the seed
781cc4b2fb6SRafael Auler   /// used to compute the rest of the missing edge counts in a bottom-up
782cc4b2fb6SRafael Auler   /// traversal of the spanning tree.
78316a497c6SRafael Auler   Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
78416a497c6SRafael Auler         const uint64_t *Counters, ProfileWriterContext &Ctx);
785cc4b2fb6SRafael Auler   ~Graph();
786cc4b2fb6SRafael Auler   void dump() const;
78716a497c6SRafael Auler 
78816a497c6SRafael Auler private:
78916a497c6SRafael Auler   void computeEdgeFrequencies(const uint64_t *Counters,
79016a497c6SRafael Auler                               ProfileWriterContext &Ctx);
79116a497c6SRafael Auler   void dumpEdgeFreqs() const;
792cc4b2fb6SRafael Auler };
793cc4b2fb6SRafael Auler 
79416a497c6SRafael Auler Graph::Graph(BumpPtrAllocator &Alloc, const FunctionDescription &D,
79516a497c6SRafael Auler              const uint64_t *Counters, ProfileWriterContext &Ctx)
79616a497c6SRafael Auler     : Alloc(Alloc), D(D) {
797cc4b2fb6SRafael Auler   DEBUG(reportNumber("G = 0x", (uint64_t)this, 16));
798cc4b2fb6SRafael Auler   // First pass to determine number of nodes
79916a497c6SRafael Auler   int32_t MaxNodes = -1;
80016a497c6SRafael Auler   CallFreqs = nullptr;
80116a497c6SRafael Auler   EdgeFreqs = nullptr;
80216a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
80316a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].FromNode) > MaxNodes)
80416a497c6SRafael Auler       MaxNodes = D.Edges[I].FromNode;
80516a497c6SRafael Auler     if (static_cast<int32_t>(D.Edges[I].ToNode) > MaxNodes)
80616a497c6SRafael Auler       MaxNodes = D.Edges[I].ToNode;
807cc4b2fb6SRafael Auler   }
808a0dd5b05SAlexander Shaposhnikov 
80916a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
81016a497c6SRafael Auler     if (static_cast<int32_t>(D.LeafNodes[I].Node) > MaxNodes)
81116a497c6SRafael Auler       MaxNodes = D.LeafNodes[I].Node;
812cc4b2fb6SRafael Auler   }
81316a497c6SRafael Auler   for (int I = 0; I < D.NumCalls; ++I) {
81416a497c6SRafael Auler     if (static_cast<int32_t>(D.Calls[I].FromNode) > MaxNodes)
81516a497c6SRafael Auler       MaxNodes = D.Calls[I].FromNode;
81616a497c6SRafael Auler   }
81716a497c6SRafael Auler   // No nodes? Nothing to do
81816a497c6SRafael Auler   if (MaxNodes < 0) {
81916a497c6SRafael Auler     DEBUG(report("No nodes!\n"));
820cc4b2fb6SRafael Auler     CFGNodes = nullptr;
821cc4b2fb6SRafael Auler     SpanningTreeNodes = nullptr;
822cc4b2fb6SRafael Auler     NumNodes = 0;
823cc4b2fb6SRafael Auler     return;
824cc4b2fb6SRafael Auler   }
825cc4b2fb6SRafael Auler   ++MaxNodes;
826cc4b2fb6SRafael Auler   DEBUG(reportNumber("NumNodes = ", MaxNodes, 10));
82716a497c6SRafael Auler   NumNodes = static_cast<uint32_t>(MaxNodes);
828cc4b2fb6SRafael Auler 
829cc4b2fb6SRafael Auler   // Initial allocations
830cc4b2fb6SRafael Auler   CFGNodes = new (Alloc) Node[MaxNodes];
831a0dd5b05SAlexander Shaposhnikov 
832cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->CFGNodes = 0x", (uint64_t)CFGNodes, 16));
833cc4b2fb6SRafael Auler   SpanningTreeNodes = new (Alloc) Node[MaxNodes];
834cc4b2fb6SRafael Auler   DEBUG(reportNumber("G->SpanningTreeNodes = 0x",
835cc4b2fb6SRafael Auler                      (uint64_t)SpanningTreeNodes, 16));
836cc4b2fb6SRafael Auler 
837cc4b2fb6SRafael Auler   // Figure out how much to allocate to each vector (in/out edge sets)
83816a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
83916a497c6SRafael Auler     CFGNodes[D.Edges[I].FromNode].NumOutEdges++;
84016a497c6SRafael Auler     CFGNodes[D.Edges[I].ToNode].NumInEdges++;
84116a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
842cc4b2fb6SRafael Auler       continue;
843cc4b2fb6SRafael Auler 
84416a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].FromNode].NumOutEdges++;
84516a497c6SRafael Auler     SpanningTreeNodes[D.Edges[I].ToNode].NumInEdges++;
846cc4b2fb6SRafael Auler   }
847cc4b2fb6SRafael Auler 
848cc4b2fb6SRafael Auler   // Allocate in/out edge sets
849cc4b2fb6SRafael Auler   for (int I = 0; I < MaxNodes; ++I) {
850cc4b2fb6SRafael Auler     if (CFGNodes[I].NumInEdges > 0)
851cc4b2fb6SRafael Auler       CFGNodes[I].InEdges = new (Alloc) Edge[CFGNodes[I].NumInEdges];
852cc4b2fb6SRafael Auler     if (CFGNodes[I].NumOutEdges > 0)
853cc4b2fb6SRafael Auler       CFGNodes[I].OutEdges = new (Alloc) Edge[CFGNodes[I].NumOutEdges];
854cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges > 0)
855cc4b2fb6SRafael Auler       SpanningTreeNodes[I].InEdges =
856cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumInEdges];
857cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].NumOutEdges > 0)
858cc4b2fb6SRafael Auler       SpanningTreeNodes[I].OutEdges =
859cc4b2fb6SRafael Auler           new (Alloc) Edge[SpanningTreeNodes[I].NumOutEdges];
860cc4b2fb6SRafael Auler     CFGNodes[I].NumInEdges = 0;
861cc4b2fb6SRafael Auler     CFGNodes[I].NumOutEdges = 0;
862cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumInEdges = 0;
863cc4b2fb6SRafael Auler     SpanningTreeNodes[I].NumOutEdges = 0;
864cc4b2fb6SRafael Auler   }
865cc4b2fb6SRafael Auler 
866cc4b2fb6SRafael Auler   // Fill in/out edge sets
86716a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
86816a497c6SRafael Auler     const uint32_t Src = D.Edges[I].FromNode;
86916a497c6SRafael Auler     const uint32_t Dst = D.Edges[I].ToNode;
870cc4b2fb6SRafael Auler     Edge *E = &CFGNodes[Src].OutEdges[CFGNodes[Src].NumOutEdges++];
871cc4b2fb6SRafael Auler     E->Node = Dst;
872cc4b2fb6SRafael Auler     E->ID = I;
873cc4b2fb6SRafael Auler 
874cc4b2fb6SRafael Auler     E = &CFGNodes[Dst].InEdges[CFGNodes[Dst].NumInEdges++];
875cc4b2fb6SRafael Auler     E->Node = Src;
876cc4b2fb6SRafael Auler     E->ID = I;
877cc4b2fb6SRafael Auler 
87816a497c6SRafael Auler     if (D.Edges[I].Counter != 0xffffffff)
879cc4b2fb6SRafael Auler       continue;
880cc4b2fb6SRafael Auler 
881cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Src]
882cc4b2fb6SRafael Auler              .OutEdges[SpanningTreeNodes[Src].NumOutEdges++];
883cc4b2fb6SRafael Auler     E->Node = Dst;
884cc4b2fb6SRafael Auler     E->ID = I;
885cc4b2fb6SRafael Auler 
886cc4b2fb6SRafael Auler     E = &SpanningTreeNodes[Dst]
887cc4b2fb6SRafael Auler              .InEdges[SpanningTreeNodes[Dst].NumInEdges++];
888cc4b2fb6SRafael Auler     E->Node = Src;
889cc4b2fb6SRafael Auler     E->ID = I;
890cc4b2fb6SRafael Auler   }
89116a497c6SRafael Auler 
89216a497c6SRafael Auler   computeEdgeFrequencies(Counters, Ctx);
893cc4b2fb6SRafael Auler }
894cc4b2fb6SRafael Auler 
895cc4b2fb6SRafael Auler Graph::~Graph() {
89616a497c6SRafael Auler   if (CallFreqs)
89716a497c6SRafael Auler     Alloc.deallocate(CallFreqs);
89816a497c6SRafael Auler   if (EdgeFreqs)
89916a497c6SRafael Auler     Alloc.deallocate(EdgeFreqs);
900cc4b2fb6SRafael Auler   for (int I = NumNodes - 1; I >= 0; --I) {
901cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].OutEdges)
902cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].OutEdges);
903cc4b2fb6SRafael Auler     if (SpanningTreeNodes[I].InEdges)
904cc4b2fb6SRafael Auler       Alloc.deallocate(SpanningTreeNodes[I].InEdges);
905cc4b2fb6SRafael Auler     if (CFGNodes[I].OutEdges)
906cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].OutEdges);
907cc4b2fb6SRafael Auler     if (CFGNodes[I].InEdges)
908cc4b2fb6SRafael Auler       Alloc.deallocate(CFGNodes[I].InEdges);
909cc4b2fb6SRafael Auler   }
910cc4b2fb6SRafael Auler   if (SpanningTreeNodes)
911cc4b2fb6SRafael Auler     Alloc.deallocate(SpanningTreeNodes);
912cc4b2fb6SRafael Auler   if (CFGNodes)
913cc4b2fb6SRafael Auler     Alloc.deallocate(CFGNodes);
914cc4b2fb6SRafael Auler }
915cc4b2fb6SRafael Auler 
916cc4b2fb6SRafael Auler void Graph::dump() const {
917cc4b2fb6SRafael Auler   reportNumber("Dumping graph with number of nodes: ", NumNodes, 10);
918cc4b2fb6SRafael Auler   report("  Full graph:\n");
919cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
920cc4b2fb6SRafael Auler     const Node *N = &CFGNodes[I];
921cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
922cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
923cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
924cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
925cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
926cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
927cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
928cc4b2fb6SRafael Auler     report("\n");
929cc4b2fb6SRafael Auler   }
930cc4b2fb6SRafael Auler   report("  Spanning tree:\n");
931cc4b2fb6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
932cc4b2fb6SRafael Auler     const Node *N = &SpanningTreeNodes[I];
933cc4b2fb6SRafael Auler     reportNumber("    Node #", I, 10);
934cc4b2fb6SRafael Auler     reportNumber("      InEdges total ", N->NumInEdges, 10);
935cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumInEdges; ++J)
936cc4b2fb6SRafael Auler       reportNumber("        ", N->InEdges[J].Node, 10);
937cc4b2fb6SRafael Auler     reportNumber("      OutEdges total ", N->NumOutEdges, 10);
938cc4b2fb6SRafael Auler     for (int J = 0; J < N->NumOutEdges; ++J)
939cc4b2fb6SRafael Auler       reportNumber("        ", N->OutEdges[J].Node, 10);
940cc4b2fb6SRafael Auler     report("\n");
941cc4b2fb6SRafael Auler   }
942cc4b2fb6SRafael Auler }
943cc4b2fb6SRafael Auler 
94416a497c6SRafael Auler void Graph::dumpEdgeFreqs() const {
94516a497c6SRafael Auler   reportNumber(
94616a497c6SRafael Auler       "Dumping edge frequencies for graph with num edges: ", D.NumEdges, 10);
94716a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
94816a497c6SRafael Auler     reportNumber("* Src: ", D.Edges[I].FromNode, 10);
94916a497c6SRafael Auler     reportNumber("  Dst: ", D.Edges[I].ToNode, 10);
950cc4b2fb6SRafael Auler     reportNumber("    Cnt: ", EdgeFreqs[I], 10);
951cc4b2fb6SRafael Auler   }
952cc4b2fb6SRafael Auler }
953cc4b2fb6SRafael Auler 
95416a497c6SRafael Auler /// Auxiliary map structure for fast lookups of which calls map to each node of
95516a497c6SRafael Auler /// the function CFG
95616a497c6SRafael Auler struct NodeToCallsMap {
95716a497c6SRafael Auler   struct MapEntry {
95816a497c6SRafael Auler     uint32_t NumCalls;
95916a497c6SRafael Auler     uint32_t *Calls;
96016a497c6SRafael Auler   };
96116a497c6SRafael Auler   MapEntry *Entries;
96216a497c6SRafael Auler   BumpPtrAllocator &Alloc;
96316a497c6SRafael Auler   const uint32_t NumNodes;
964cc4b2fb6SRafael Auler 
96516a497c6SRafael Auler   NodeToCallsMap(BumpPtrAllocator &Alloc, const FunctionDescription &D,
96616a497c6SRafael Auler                  uint32_t NumNodes)
96716a497c6SRafael Auler       : Alloc(Alloc), NumNodes(NumNodes) {
96816a497c6SRafael Auler     Entries = new (Alloc, 0) MapEntry[NumNodes];
96916a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
97016a497c6SRafael Auler       DEBUG(reportNumber("Registering call in node ", D.Calls[I].FromNode, 10));
97116a497c6SRafael Auler       ++Entries[D.Calls[I].FromNode].NumCalls;
97216a497c6SRafael Auler     }
97316a497c6SRafael Auler     for (int I = 0; I < NumNodes; ++I) {
97416a497c6SRafael Auler       Entries[I].Calls = Entries[I].NumCalls ? new (Alloc)
97516a497c6SRafael Auler                                                    uint32_t[Entries[I].NumCalls]
97616a497c6SRafael Auler                                              : nullptr;
97716a497c6SRafael Auler       Entries[I].NumCalls = 0;
97816a497c6SRafael Auler     }
97916a497c6SRafael Auler     for (int I = 0; I < D.NumCalls; ++I) {
980c7306cc2SAmir Ayupov       MapEntry &Entry = Entries[D.Calls[I].FromNode];
98116a497c6SRafael Auler       Entry.Calls[Entry.NumCalls++] = I;
98216a497c6SRafael Auler     }
98316a497c6SRafael Auler   }
98416a497c6SRafael Auler 
98516a497c6SRafael Auler   /// Set the frequency of all calls in node \p NodeID to Freq. However, if
98616a497c6SRafael Auler   /// the calls have their own counters and do not depend on the basic block
98716a497c6SRafael Auler   /// counter, this means they have landing pads and throw exceptions. In this
98816a497c6SRafael Auler   /// case, set their frequency with their counters and return the maximum
98916a497c6SRafael Auler   /// value observed in such counters. This will be used as the new frequency
99016a497c6SRafael Auler   /// at basic block entry. This is used to fix the CFG edge frequencies in the
99116a497c6SRafael Auler   /// presence of exceptions.
99216a497c6SRafael Auler   uint64_t visitAllCallsIn(uint32_t NodeID, uint64_t Freq, uint64_t *CallFreqs,
99316a497c6SRafael Auler                            const FunctionDescription &D,
99416a497c6SRafael Auler                            const uint64_t *Counters,
99516a497c6SRafael Auler                            ProfileWriterContext &Ctx) const {
996c7306cc2SAmir Ayupov     const MapEntry &Entry = Entries[NodeID];
99716a497c6SRafael Auler     uint64_t MaxValue = 0ull;
99816a497c6SRafael Auler     for (int I = 0, E = Entry.NumCalls; I != E; ++I) {
999c7306cc2SAmir Ayupov       const uint32_t CallID = Entry.Calls[I];
100016a497c6SRafael Auler       DEBUG(reportNumber("  Setting freq for call ID: ", CallID, 10));
1001c7306cc2SAmir Ayupov       const CallDescription &CallDesc = D.Calls[CallID];
100216a497c6SRafael Auler       if (CallDesc.Counter == 0xffffffff) {
100316a497c6SRafael Auler         CallFreqs[CallID] = Freq;
100416a497c6SRafael Auler         DEBUG(reportNumber("  with : ", Freq, 10));
100516a497c6SRafael Auler       } else {
1006c7306cc2SAmir Ayupov         const uint64_t CounterVal = Counters[CallDesc.Counter];
100716a497c6SRafael Auler         CallFreqs[CallID] = CounterVal;
100816a497c6SRafael Auler         MaxValue = CounterVal > MaxValue ? CounterVal : MaxValue;
100916a497c6SRafael Auler         DEBUG(reportNumber("  with (private counter) : ", CounterVal, 10));
101016a497c6SRafael Auler       }
101116a497c6SRafael Auler       DEBUG(reportNumber("  Address: 0x", CallDesc.TargetAddress, 16));
101216a497c6SRafael Auler       if (CallFreqs[CallID] > 0)
101316a497c6SRafael Auler         Ctx.CallFlowTable->get(CallDesc.TargetAddress).Calls +=
101416a497c6SRafael Auler             CallFreqs[CallID];
101516a497c6SRafael Auler     }
101616a497c6SRafael Auler     return MaxValue;
101716a497c6SRafael Auler   }
101816a497c6SRafael Auler 
101916a497c6SRafael Auler   ~NodeToCallsMap() {
102016a497c6SRafael Auler     for (int I = NumNodes - 1; I >= 0; --I) {
102116a497c6SRafael Auler       if (Entries[I].Calls)
102216a497c6SRafael Auler         Alloc.deallocate(Entries[I].Calls);
102316a497c6SRafael Auler     }
102416a497c6SRafael Auler     Alloc.deallocate(Entries);
102516a497c6SRafael Auler   }
102616a497c6SRafael Auler };
102716a497c6SRafael Auler 
102816a497c6SRafael Auler /// Fill an array with the frequency of each edge in the function represented
102916a497c6SRafael Auler /// by G, as well as another array for each call.
103016a497c6SRafael Auler void Graph::computeEdgeFrequencies(const uint64_t *Counters,
103116a497c6SRafael Auler                                    ProfileWriterContext &Ctx) {
103216a497c6SRafael Auler   if (NumNodes == 0)
103316a497c6SRafael Auler     return;
103416a497c6SRafael Auler 
103516a497c6SRafael Auler   EdgeFreqs = D.NumEdges ? new (Alloc, 0) uint64_t [D.NumEdges] : nullptr;
103616a497c6SRafael Auler   CallFreqs = D.NumCalls ? new (Alloc, 0) uint64_t [D.NumCalls] : nullptr;
103716a497c6SRafael Auler 
103816a497c6SRafael Auler   // Setup a lookup for calls present in each node (BB)
103916a497c6SRafael Auler   NodeToCallsMap *CallMap = new (Alloc) NodeToCallsMap(Alloc, D, NumNodes);
1040cc4b2fb6SRafael Auler 
1041cc4b2fb6SRafael Auler   // Perform a bottom-up, BFS traversal of the spanning tree in G. Edges in the
1042cc4b2fb6SRafael Auler   // spanning tree don't have explicit counters. We must infer their value using
1043cc4b2fb6SRafael Auler   // a linear combination of other counters (sum of counters of the outgoing
1044cc4b2fb6SRafael Auler   // edges minus sum of counters of the incoming edges).
104516a497c6SRafael Auler   uint32_t *Stack = new (Alloc) uint32_t [NumNodes];
1046cc4b2fb6SRafael Auler   uint32_t StackTop = 0;
1047cc4b2fb6SRafael Auler   enum Status : uint8_t { S_NEW = 0, S_VISITING, S_VISITED };
104816a497c6SRafael Auler   Status *Visited = new (Alloc, 0) Status[NumNodes];
104916a497c6SRafael Auler   uint64_t *LeafFrequency = new (Alloc, 0) uint64_t[NumNodes];
105016a497c6SRafael Auler   uint64_t *EntryAddress = new (Alloc, 0) uint64_t[NumNodes];
1051cc4b2fb6SRafael Auler 
1052cc4b2fb6SRafael Auler   // Setup a fast lookup for frequency of leaf nodes, which have special
1053cc4b2fb6SRafael Auler   // basic block frequency instrumentation (they are not edge profiled).
105416a497c6SRafael Auler   for (int I = 0; I < D.NumLeafNodes; ++I) {
105516a497c6SRafael Auler     LeafFrequency[D.LeafNodes[I].Node] = Counters[D.LeafNodes[I].Counter];
1056cc4b2fb6SRafael Auler     DEBUG({
105716a497c6SRafael Auler       if (Counters[D.LeafNodes[I].Counter] > 0) {
105816a497c6SRafael Auler         reportNumber("Leaf Node# ", D.LeafNodes[I].Node, 10);
105916a497c6SRafael Auler         reportNumber("     Counter: ", Counters[D.LeafNodes[I].Counter], 10);
1060cc4b2fb6SRafael Auler       }
1061cc4b2fb6SRafael Auler     });
106216a497c6SRafael Auler   }
106316a497c6SRafael Auler   for (int I = 0; I < D.NumEntryNodes; ++I) {
106416a497c6SRafael Auler     EntryAddress[D.EntryNodes[I].Node] = D.EntryNodes[I].Address;
106516a497c6SRafael Auler     DEBUG({
106616a497c6SRafael Auler         reportNumber("Entry Node# ", D.EntryNodes[I].Node, 10);
106716a497c6SRafael Auler         reportNumber("      Address: ", D.EntryNodes[I].Address, 16);
106816a497c6SRafael Auler     });
1069cc4b2fb6SRafael Auler   }
1070cc4b2fb6SRafael Auler   // Add all root nodes to the stack
107116a497c6SRafael Auler   for (int I = 0; I < NumNodes; ++I) {
107216a497c6SRafael Auler     if (SpanningTreeNodes[I].NumInEdges == 0)
1073cc4b2fb6SRafael Auler       Stack[StackTop++] = I;
1074cc4b2fb6SRafael Auler   }
1075cc4b2fb6SRafael Auler   // Empty stack?
1076cc4b2fb6SRafael Auler   if (StackTop == 0) {
107716a497c6SRafael Auler     DEBUG(report("Empty stack!\n"));
107816a497c6SRafael Auler     Alloc.deallocate(EntryAddress);
1079cc4b2fb6SRafael Auler     Alloc.deallocate(LeafFrequency);
1080cc4b2fb6SRafael Auler     Alloc.deallocate(Visited);
1081cc4b2fb6SRafael Auler     Alloc.deallocate(Stack);
108216a497c6SRafael Auler     CallMap->~NodeToCallsMap();
108316a497c6SRafael Auler     Alloc.deallocate(CallMap);
108416a497c6SRafael Auler     if (CallFreqs)
108516a497c6SRafael Auler       Alloc.deallocate(CallFreqs);
108616a497c6SRafael Auler     if (EdgeFreqs)
108716a497c6SRafael Auler       Alloc.deallocate(EdgeFreqs);
108816a497c6SRafael Auler     EdgeFreqs = nullptr;
108916a497c6SRafael Auler     CallFreqs = nullptr;
109016a497c6SRafael Auler     return;
1091cc4b2fb6SRafael Auler   }
1092cc4b2fb6SRafael Auler   // Add all known edge counts, will infer the rest
109316a497c6SRafael Auler   for (int I = 0; I < D.NumEdges; ++I) {
109416a497c6SRafael Auler     const uint32_t C = D.Edges[I].Counter;
1095cc4b2fb6SRafael Auler     if (C == 0xffffffff) // inferred counter - we will compute its value
1096cc4b2fb6SRafael Auler       continue;
109716a497c6SRafael Auler     EdgeFreqs[I] = Counters[C];
1098cc4b2fb6SRafael Auler   }
1099cc4b2fb6SRafael Auler 
1100cc4b2fb6SRafael Auler   while (StackTop > 0) {
1101cc4b2fb6SRafael Auler     const uint32_t Cur = Stack[--StackTop];
1102cc4b2fb6SRafael Auler     DEBUG({
1103cc4b2fb6SRafael Auler       if (Visited[Cur] == S_VISITING)
1104cc4b2fb6SRafael Auler         report("(visiting) ");
1105cc4b2fb6SRafael Auler       else
1106cc4b2fb6SRafael Auler         report("(new) ");
1107cc4b2fb6SRafael Auler       reportNumber("Cur: ", Cur, 10);
1108cc4b2fb6SRafael Auler     });
1109cc4b2fb6SRafael Auler 
1110cc4b2fb6SRafael Auler     // This shouldn't happen in a tree
1111cc4b2fb6SRafael Auler     assert(Visited[Cur] != S_VISITED, "should not have visited nodes in stack");
1112cc4b2fb6SRafael Auler     if (Visited[Cur] == S_NEW) {
1113cc4b2fb6SRafael Auler       Visited[Cur] = S_VISITING;
1114cc4b2fb6SRafael Auler       Stack[StackTop++] = Cur;
111516a497c6SRafael Auler       assert(StackTop <= NumNodes, "stack grew too large");
111616a497c6SRafael Auler       for (int I = 0, E = SpanningTreeNodes[Cur].NumOutEdges; I < E; ++I) {
111716a497c6SRafael Auler         const uint32_t Succ = SpanningTreeNodes[Cur].OutEdges[I].Node;
1118cc4b2fb6SRafael Auler         Stack[StackTop++] = Succ;
111916a497c6SRafael Auler         assert(StackTop <= NumNodes, "stack grew too large");
1120cc4b2fb6SRafael Auler      }
1121cc4b2fb6SRafael Auler       continue;
1122cc4b2fb6SRafael Auler     }
1123cc4b2fb6SRafael Auler     Visited[Cur] = S_VISITED;
1124cc4b2fb6SRafael Auler 
1125cc4b2fb6SRafael Auler     // Establish our node frequency based on outgoing edges, which should all be
1126cc4b2fb6SRafael Auler     // resolved by now.
1127cc4b2fb6SRafael Auler     int64_t CurNodeFreq = LeafFrequency[Cur];
1128cc4b2fb6SRafael Auler     // Not a leaf?
1129cc4b2fb6SRafael Auler     if (!CurNodeFreq) {
113016a497c6SRafael Auler       for (int I = 0, E = CFGNodes[Cur].NumOutEdges; I != E; ++I) {
113116a497c6SRafael Auler         const uint32_t SuccEdge = CFGNodes[Cur].OutEdges[I].ID;
113216a497c6SRafael Auler         CurNodeFreq += EdgeFreqs[SuccEdge];
1133cc4b2fb6SRafael Auler       }
1134cc4b2fb6SRafael Auler     }
113516a497c6SRafael Auler     if (CurNodeFreq < 0)
113616a497c6SRafael Auler       CurNodeFreq = 0;
113716a497c6SRafael Auler 
113816a497c6SRafael Auler     const uint64_t CallFreq = CallMap->visitAllCallsIn(
113916a497c6SRafael Auler         Cur, CurNodeFreq > 0 ? CurNodeFreq : 0, CallFreqs, D, Counters, Ctx);
114016a497c6SRafael Auler 
114116a497c6SRafael Auler     // Exception handling affected our output flow? Fix with calls info
114216a497c6SRafael Auler     DEBUG({
114316a497c6SRafael Auler       if (CallFreq > CurNodeFreq)
114416a497c6SRafael Auler         report("Bumping node frequency with call info\n");
114516a497c6SRafael Auler     });
114616a497c6SRafael Auler     CurNodeFreq = CallFreq > CurNodeFreq ? CallFreq : CurNodeFreq;
114716a497c6SRafael Auler 
114816a497c6SRafael Auler     if (CurNodeFreq > 0) {
114916a497c6SRafael Auler       if (uint64_t Addr = EntryAddress[Cur]) {
115016a497c6SRafael Auler         DEBUG(
115116a497c6SRafael Auler             reportNumber("  Setting flow at entry point address 0x", Addr, 16));
115216a497c6SRafael Auler         DEBUG(reportNumber("  with: ", CurNodeFreq, 10));
115316a497c6SRafael Auler         Ctx.CallFlowTable->get(Addr).Val = CurNodeFreq;
115416a497c6SRafael Auler       }
115516a497c6SRafael Auler     }
115616a497c6SRafael Auler 
115716a497c6SRafael Auler     // No parent? Reached a tree root, limit to call frequency updating.
115816a497c6SRafael Auler     if (SpanningTreeNodes[Cur].NumInEdges == 0) {
115916a497c6SRafael Auler       continue;
116016a497c6SRafael Auler     }
116116a497c6SRafael Auler 
116216a497c6SRafael Auler     assert(SpanningTreeNodes[Cur].NumInEdges == 1, "must have 1 parent");
116316a497c6SRafael Auler     const uint32_t Parent = SpanningTreeNodes[Cur].InEdges[0].Node;
116416a497c6SRafael Auler     const uint32_t ParentEdge = SpanningTreeNodes[Cur].InEdges[0].ID;
116516a497c6SRafael Auler 
1166cc4b2fb6SRafael Auler     // Calculate parent edge freq.
116716a497c6SRafael Auler     int64_t ParentEdgeFreq = CurNodeFreq;
116816a497c6SRafael Auler     for (int I = 0, E = CFGNodes[Cur].NumInEdges; I != E; ++I) {
116916a497c6SRafael Auler       const uint32_t PredEdge = CFGNodes[Cur].InEdges[I].ID;
117016a497c6SRafael Auler       ParentEdgeFreq -= EdgeFreqs[PredEdge];
1171cc4b2fb6SRafael Auler     }
117216a497c6SRafael Auler 
1173cc4b2fb6SRafael Auler     // Sometimes the conservative CFG that BOLT builds will lead to incorrect
1174cc4b2fb6SRafael Auler     // flow computation. For example, in a BB that transitively calls the exit
1175cc4b2fb6SRafael Auler     // syscall, BOLT will add a fall-through successor even though it should not
1176cc4b2fb6SRafael Auler     // have any successors. So this block execution will likely be wrong. We
1177cc4b2fb6SRafael Auler     // tolerate this imperfection since this case should be quite infrequent.
1178cc4b2fb6SRafael Auler     if (ParentEdgeFreq < 0) {
117916a497c6SRafael Auler       DEBUG(dumpEdgeFreqs());
1180cc4b2fb6SRafael Auler       DEBUG(report("WARNING: incorrect flow"));
1181cc4b2fb6SRafael Auler       ParentEdgeFreq = 0;
1182cc4b2fb6SRafael Auler     }
1183cc4b2fb6SRafael Auler     DEBUG(reportNumber("  Setting freq for ParentEdge: ", ParentEdge, 10));
1184cc4b2fb6SRafael Auler     DEBUG(reportNumber("  with ParentEdgeFreq: ", ParentEdgeFreq, 10));
118516a497c6SRafael Auler     EdgeFreqs[ParentEdge] = ParentEdgeFreq;
1186cc4b2fb6SRafael Auler   }
1187cc4b2fb6SRafael Auler 
118816a497c6SRafael Auler   Alloc.deallocate(EntryAddress);
1189cc4b2fb6SRafael Auler   Alloc.deallocate(LeafFrequency);
1190cc4b2fb6SRafael Auler   Alloc.deallocate(Visited);
1191cc4b2fb6SRafael Auler   Alloc.deallocate(Stack);
119216a497c6SRafael Auler   CallMap->~NodeToCallsMap();
119316a497c6SRafael Auler   Alloc.deallocate(CallMap);
119416a497c6SRafael Auler   DEBUG(dumpEdgeFreqs());
1195cc4b2fb6SRafael Auler }
1196cc4b2fb6SRafael Auler 
119716a497c6SRafael Auler /// Write to \p FD all of the edge profiles for function \p FuncDesc. Uses
119816a497c6SRafael Auler /// \p Alloc to allocate helper dynamic structures used to compute profile for
119916a497c6SRafael Auler /// edges that we do not explictly instrument.
120016a497c6SRafael Auler const uint8_t *writeFunctionProfile(int FD, ProfileWriterContext &Ctx,
120116a497c6SRafael Auler                                     const uint8_t *FuncDesc,
120216a497c6SRafael Auler                                     BumpPtrAllocator &Alloc) {
120316a497c6SRafael Auler   const FunctionDescription F(FuncDesc);
120416a497c6SRafael Auler   const uint8_t *next = FuncDesc + F.getSize();
1205cc4b2fb6SRafael Auler 
1206a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1207a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = __bolt_instr_locations;
1208a0dd5b05SAlexander Shaposhnikov #else
1209a0dd5b05SAlexander Shaposhnikov   uint64_t *bolt_instr_locations = _bolt_instr_locations_getter();
1210a0dd5b05SAlexander Shaposhnikov #endif
1211a0dd5b05SAlexander Shaposhnikov 
1212cc4b2fb6SRafael Auler   // Skip funcs we know are cold
1213cc4b2fb6SRafael Auler #ifndef ENABLE_DEBUG
121416a497c6SRafael Auler   uint64_t CountersFreq = 0;
121516a497c6SRafael Auler   for (int I = 0; I < F.NumLeafNodes; ++I) {
1216a0dd5b05SAlexander Shaposhnikov     CountersFreq += bolt_instr_locations[F.LeafNodes[I].Counter];
1217cc4b2fb6SRafael Auler   }
121816a497c6SRafael Auler   if (CountersFreq == 0) {
121916a497c6SRafael Auler     for (int I = 0; I < F.NumEdges; ++I) {
122016a497c6SRafael Auler       const uint32_t C = F.Edges[I].Counter;
122116a497c6SRafael Auler       if (C == 0xffffffff)
122216a497c6SRafael Auler         continue;
1223a0dd5b05SAlexander Shaposhnikov       CountersFreq += bolt_instr_locations[C];
122416a497c6SRafael Auler     }
122516a497c6SRafael Auler     if (CountersFreq == 0) {
122616a497c6SRafael Auler       for (int I = 0; I < F.NumCalls; ++I) {
122716a497c6SRafael Auler         const uint32_t C = F.Calls[I].Counter;
122816a497c6SRafael Auler         if (C == 0xffffffff)
122916a497c6SRafael Auler           continue;
1230a0dd5b05SAlexander Shaposhnikov         CountersFreq += bolt_instr_locations[C];
123116a497c6SRafael Auler       }
123216a497c6SRafael Auler       if (CountersFreq == 0)
1233cc4b2fb6SRafael Auler         return next;
123416a497c6SRafael Auler     }
123516a497c6SRafael Auler   }
1236cc4b2fb6SRafael Auler #endif
1237cc4b2fb6SRafael Auler 
1238a0dd5b05SAlexander Shaposhnikov   Graph *G = new (Alloc) Graph(Alloc, F, bolt_instr_locations, Ctx);
1239cc4b2fb6SRafael Auler   DEBUG(G->dump());
1240a0dd5b05SAlexander Shaposhnikov 
124116a497c6SRafael Auler   if (!G->EdgeFreqs && !G->CallFreqs) {
1242cc4b2fb6SRafael Auler     G->~Graph();
1243cc4b2fb6SRafael Auler     Alloc.deallocate(G);
1244cc4b2fb6SRafael Auler     return next;
1245cc4b2fb6SRafael Auler   }
1246cc4b2fb6SRafael Auler 
124716a497c6SRafael Auler   for (int I = 0; I < F.NumEdges; ++I) {
124816a497c6SRafael Auler     const uint64_t Freq = G->EdgeFreqs[I];
1249cc4b2fb6SRafael Auler     if (Freq == 0)
1250cc4b2fb6SRafael Auler       continue;
125116a497c6SRafael Auler     const EdgeDescription *Desc = &F.Edges[I];
1252cc4b2fb6SRafael Auler     char LineBuf[BufSize];
1253cc4b2fb6SRafael Auler     char *Ptr = LineBuf;
125416a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
125516a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
1256cc4b2fb6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 22);
1257cc4b2fb6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
1258cc4b2fb6SRafael Auler     *Ptr++ = '\n';
1259cc4b2fb6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
1260cc4b2fb6SRafael Auler   }
1261cc4b2fb6SRafael Auler 
126216a497c6SRafael Auler   for (int I = 0; I < F.NumCalls; ++I) {
126316a497c6SRafael Auler     const uint64_t Freq = G->CallFreqs[I];
126416a497c6SRafael Auler     if (Freq == 0)
126516a497c6SRafael Auler       continue;
126616a497c6SRafael Auler     char LineBuf[BufSize];
126716a497c6SRafael Auler     char *Ptr = LineBuf;
126816a497c6SRafael Auler     const CallDescription *Desc = &F.Calls[I];
126916a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->From, BufSize);
127016a497c6SRafael Auler     Ptr = serializeLoc(Ctx, Ptr, Desc->To, BufSize - (Ptr - LineBuf));
127116a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
127216a497c6SRafael Auler     Ptr = intToStr(Ptr, Freq, 10);
127316a497c6SRafael Auler     *Ptr++ = '\n';
127416a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
127516a497c6SRafael Auler   }
127616a497c6SRafael Auler 
1277cc4b2fb6SRafael Auler   G->~Graph();
1278cc4b2fb6SRafael Auler   Alloc.deallocate(G);
1279cc4b2fb6SRafael Auler   return next;
1280cc4b2fb6SRafael Auler }
1281cc4b2fb6SRafael Auler 
1282a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
128316a497c6SRafael Auler const IndCallTargetDescription *
128416a497c6SRafael Auler ProfileWriterContext::lookupIndCallTarget(uint64_t Target) const {
128516a497c6SRafael Auler   uint32_t B = 0;
128616a497c6SRafael Auler   uint32_t E = __bolt_instr_num_ind_targets;
128716a497c6SRafael Auler   if (E == 0)
128816a497c6SRafael Auler     return nullptr;
128916a497c6SRafael Auler   do {
129016a497c6SRafael Auler     uint32_t I = (E - B) / 2 + B;
129116a497c6SRafael Auler     if (IndCallTargets[I].Address == Target)
129216a497c6SRafael Auler       return &IndCallTargets[I];
129316a497c6SRafael Auler     if (IndCallTargets[I].Address < Target)
129416a497c6SRafael Auler       B = I + 1;
129516a497c6SRafael Auler     else
129616a497c6SRafael Auler       E = I;
129716a497c6SRafael Auler   } while (B < E);
129816a497c6SRafael Auler   return nullptr;
1299cc4b2fb6SRafael Auler }
130062aa74f8SRafael Auler 
130116a497c6SRafael Auler /// Write a single indirect call <src, target> pair to the fdata file
130216a497c6SRafael Auler void visitIndCallCounter(IndirectCallHashTable::MapEntry &Entry,
130316a497c6SRafael Auler                          int FD, int CallsiteID,
130416a497c6SRafael Auler                          ProfileWriterContext *Ctx) {
130516a497c6SRafael Auler   if (Entry.Val == 0)
130616a497c6SRafael Auler     return;
130716a497c6SRafael Auler   DEBUG(reportNumber("Target func 0x", Entry.Key, 16));
130816a497c6SRafael Auler   DEBUG(reportNumber("Target freq: ", Entry.Val, 10));
130916a497c6SRafael Auler   const IndCallDescription *CallsiteDesc =
131016a497c6SRafael Auler       &Ctx->IndCallDescriptions[CallsiteID];
131116a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
131216a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
131316a497c6SRafael Auler   if (!TargetDesc) {
131416a497c6SRafael Auler     DEBUG(report("Failed to lookup indirect call target\n"));
1315cc4b2fb6SRafael Auler     char LineBuf[BufSize];
131662aa74f8SRafael Auler     char *Ptr = LineBuf;
131716a497c6SRafael Auler     Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
131816a497c6SRafael Auler     Ptr = strCopy(Ptr, "0 [unknown] 0 0 ", BufSize - (Ptr - LineBuf) - 40);
131916a497c6SRafael Auler     Ptr = intToStr(Ptr, Entry.Val, 10);
132016a497c6SRafael Auler     *Ptr++ = '\n';
132116a497c6SRafael Auler     __write(FD, LineBuf, Ptr - LineBuf);
132216a497c6SRafael Auler     return;
132316a497c6SRafael Auler   }
132416a497c6SRafael Auler   Ctx->CallFlowTable->get(TargetDesc->Address).Calls += Entry.Val;
132516a497c6SRafael Auler   char LineBuf[BufSize];
132616a497c6SRafael Auler   char *Ptr = LineBuf;
132716a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, *CallsiteDesc, BufSize);
132816a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
1329cc4b2fb6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
133016a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val, 10);
133162aa74f8SRafael Auler   *Ptr++ = '\n';
1332821480d2SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
133362aa74f8SRafael Auler }
1334cc4b2fb6SRafael Auler 
133516a497c6SRafael Auler /// Write to \p FD all of the indirect call profiles.
133616a497c6SRafael Auler void writeIndirectCallProfile(int FD, ProfileWriterContext &Ctx) {
133716a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
133816a497c6SRafael Auler     DEBUG(reportNumber("IndCallsite #", I, 10));
133916a497c6SRafael Auler     GlobalIndCallCounters[I].forEachElement(visitIndCallCounter, FD, I, &Ctx);
134016a497c6SRafael Auler   }
134116a497c6SRafael Auler }
134216a497c6SRafael Auler 
134316a497c6SRafael Auler /// Check a single call flow for a callee versus all known callers. If there are
134416a497c6SRafael Auler /// less callers than what the callee expects, write the difference with source
134516a497c6SRafael Auler /// [unknown] in the profile.
134616a497c6SRafael Auler void visitCallFlowEntry(CallFlowHashTable::MapEntry &Entry, int FD,
134716a497c6SRafael Auler                         ProfileWriterContext *Ctx) {
134816a497c6SRafael Auler   DEBUG(reportNumber("Call flow entry address: 0x", Entry.Key, 16));
134916a497c6SRafael Auler   DEBUG(reportNumber("Calls: ", Entry.Calls, 10));
135016a497c6SRafael Auler   DEBUG(reportNumber("Reported entry frequency: ", Entry.Val, 10));
135116a497c6SRafael Auler   DEBUG({
135216a497c6SRafael Auler     if (Entry.Calls > Entry.Val)
135316a497c6SRafael Auler       report("  More calls than expected!\n");
135416a497c6SRafael Auler   });
135516a497c6SRafael Auler   if (Entry.Val <= Entry.Calls)
135616a497c6SRafael Auler     return;
135716a497c6SRafael Auler   DEBUG(reportNumber(
135816a497c6SRafael Auler       "  Balancing calls with traffic: ", Entry.Val - Entry.Calls, 10));
135916a497c6SRafael Auler   const IndCallTargetDescription *TargetDesc =
136016a497c6SRafael Auler       Ctx->lookupIndCallTarget(Entry.Key);
136116a497c6SRafael Auler   if (!TargetDesc) {
136216a497c6SRafael Auler     // There is probably something wrong with this callee and this should be
136316a497c6SRafael Auler     // investigated, but I don't want to assert and lose all data collected.
136416a497c6SRafael Auler     DEBUG(report("WARNING: failed to look up call target!\n"));
136516a497c6SRafael Auler     return;
136616a497c6SRafael Auler   }
136716a497c6SRafael Auler   char LineBuf[BufSize];
136816a497c6SRafael Auler   char *Ptr = LineBuf;
136916a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 [unknown] 0 ", BufSize);
137016a497c6SRafael Auler   Ptr = serializeLoc(*Ctx, Ptr, TargetDesc->Loc, BufSize - (Ptr - LineBuf));
137116a497c6SRafael Auler   Ptr = strCopy(Ptr, "0 ", BufSize - (Ptr - LineBuf) - 25);
137216a497c6SRafael Auler   Ptr = intToStr(Ptr, Entry.Val - Entry.Calls, 10);
137316a497c6SRafael Auler   *Ptr++ = '\n';
137416a497c6SRafael Auler   __write(FD, LineBuf, Ptr - LineBuf);
137516a497c6SRafael Auler }
137616a497c6SRafael Auler 
137716a497c6SRafael Auler /// Open fdata file for writing and return a valid file descriptor, aborting
137816a497c6SRafael Auler /// program upon failure.
137916a497c6SRafael Auler int openProfile() {
138016a497c6SRafael Auler   // Build the profile name string by appending our PID
138116a497c6SRafael Auler   char Buf[BufSize];
138216a497c6SRafael Auler   char *Ptr = Buf;
138316a497c6SRafael Auler   uint64_t PID = __getpid();
138416a497c6SRafael Auler   Ptr = strCopy(Buf, __bolt_instr_filename, BufSize);
138516a497c6SRafael Auler   if (__bolt_instr_use_pid) {
138616a497c6SRafael Auler     Ptr = strCopy(Ptr, ".", BufSize - (Ptr - Buf + 1));
138716a497c6SRafael Auler     Ptr = intToStr(Ptr, PID, 10);
138816a497c6SRafael Auler     Ptr = strCopy(Ptr, ".fdata", BufSize - (Ptr - Buf + 1));
138916a497c6SRafael Auler   }
139016a497c6SRafael Auler   *Ptr++ = '\0';
139116a497c6SRafael Auler   uint64_t FD = __open(Buf,
139216a497c6SRafael Auler                        /*flags=*/0x241 /*O_WRONLY|O_TRUNC|O_CREAT*/,
139316a497c6SRafael Auler                        /*mode=*/0666);
139416a497c6SRafael Auler   if (static_cast<int64_t>(FD) < 0) {
139516a497c6SRafael Auler     report("Error while trying to open profile file for writing: ");
139616a497c6SRafael Auler     report(Buf);
139716a497c6SRafael Auler     reportNumber("\nFailed with error number: 0x",
139816a497c6SRafael Auler                  0 - static_cast<int64_t>(FD), 16);
139916a497c6SRafael Auler     __exit(1);
140016a497c6SRafael Auler   }
140116a497c6SRafael Auler   return FD;
140216a497c6SRafael Auler }
1403a0dd5b05SAlexander Shaposhnikov 
1404a0dd5b05SAlexander Shaposhnikov #endif
1405a0dd5b05SAlexander Shaposhnikov 
140616a497c6SRafael Auler } // anonymous namespace
140716a497c6SRafael Auler 
1408a0dd5b05SAlexander Shaposhnikov #if !defined(__APPLE__)
1409a0dd5b05SAlexander Shaposhnikov 
141016a497c6SRafael Auler /// Reset all counters in case you want to start profiling a new phase of your
141116a497c6SRafael Auler /// program independently of prior phases.
141216a497c6SRafael Auler /// The address of this function is printed by BOLT and this can be called by
141316a497c6SRafael Auler /// any attached debugger during runtime. There is a useful oneliner for gdb:
141416a497c6SRafael Auler ///
141516a497c6SRafael Auler ///   gdb -p $(pgrep -xo PROCESSNAME) -ex 'p ((void(*)())0xdeadbeef)()' \
141616a497c6SRafael Auler ///     -ex 'set confirm off' -ex quit
141716a497c6SRafael Auler ///
141816a497c6SRafael Auler /// Where 0xdeadbeef is this function address and PROCESSNAME your binary file
141916a497c6SRafael Auler /// name.
142016a497c6SRafael Auler extern "C" void __bolt_instr_clear_counters() {
142116a497c6SRafael Auler   memSet(reinterpret_cast<char *>(__bolt_instr_locations), 0,
142216a497c6SRafael Auler          __bolt_num_counters * 8);
142316a497c6SRafael Auler   for (int I = 0; I < __bolt_instr_num_ind_calls; ++I) {
142416a497c6SRafael Auler     GlobalIndCallCounters[I].resetCounters();
142516a497c6SRafael Auler   }
142616a497c6SRafael Auler }
142716a497c6SRafael Auler 
142816a497c6SRafael Auler /// This is the entry point for profile writing.
142916a497c6SRafael Auler /// There are three ways of getting here:
143016a497c6SRafael Auler ///
143116a497c6SRafael Auler ///  * Program execution ended, finalization methods are running and BOLT
143216a497c6SRafael Auler ///    hooked into FINI from your binary dynamic section;
143316a497c6SRafael Auler ///  * You used the sleep timer option and during initialization we forked
143416a497c6SRafael Auler ///    a separete process that will call this function periodically;
143516a497c6SRafael Auler ///  * BOLT prints this function address so you can attach a debugger and
143616a497c6SRafael Auler ///    call this function directly to get your profile written to disk
143716a497c6SRafael Auler ///    on demand.
143816a497c6SRafael Auler ///
1439ad79d517SVasily Leonenko extern "C" void __attribute((force_align_arg_pointer))
1440ad79d517SVasily Leonenko __bolt_instr_data_dump() {
144116a497c6SRafael Auler   // Already dumping
144216a497c6SRafael Auler   if (!GlobalWriteProfileMutex->acquire())
144316a497c6SRafael Auler     return;
144416a497c6SRafael Auler 
144516a497c6SRafael Auler   BumpPtrAllocator HashAlloc;
144616a497c6SRafael Auler   HashAlloc.setMaxSize(0x6400000);
144716a497c6SRafael Auler   ProfileWriterContext Ctx = readDescriptions();
144816a497c6SRafael Auler   Ctx.CallFlowTable = new (HashAlloc, 0) CallFlowHashTable(HashAlloc);
144916a497c6SRafael Auler 
145016a497c6SRafael Auler   DEBUG(printStats(Ctx));
145116a497c6SRafael Auler 
145216a497c6SRafael Auler   int FD = openProfile();
145316a497c6SRafael Auler 
1454cc4b2fb6SRafael Auler   BumpPtrAllocator Alloc;
145516a497c6SRafael Auler   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1456cc4b2fb6SRafael Auler   for (int I = 0, E = __bolt_instr_num_funcs; I < E; ++I) {
145716a497c6SRafael Auler     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
145816a497c6SRafael Auler     Alloc.clear();
1459cc4b2fb6SRafael Auler     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1460cc4b2fb6SRafael Auler   }
146116a497c6SRafael Auler   assert(FuncDesc == (void *)Ctx.Strings,
1462cc4b2fb6SRafael Auler          "FuncDesc ptr must be equal to stringtable");
1463cc4b2fb6SRafael Auler 
146416a497c6SRafael Auler   writeIndirectCallProfile(FD, Ctx);
146516a497c6SRafael Auler   Ctx.CallFlowTable->forEachElement(visitCallFlowEntry, FD, &Ctx);
146616a497c6SRafael Auler 
1467821480d2SRafael Auler   __close(FD);
146816a497c6SRafael Auler   __munmap(Ctx.MMapPtr, Ctx.MMapSize);
146916a497c6SRafael Auler   __close(Ctx.FileDesc);
147016a497c6SRafael Auler   HashAlloc.destroy();
147116a497c6SRafael Auler   GlobalWriteProfileMutex->release();
147216a497c6SRafael Auler   DEBUG(report("Finished writing profile.\n"));
147316a497c6SRafael Auler }
147416a497c6SRafael Auler 
147516a497c6SRafael Auler /// Event loop for our child process spawned during setup to dump profile data
147616a497c6SRafael Auler /// at user-specified intervals
147716a497c6SRafael Auler void watchProcess() {
147816a497c6SRafael Auler   timespec ts, rem;
147916a497c6SRafael Auler   uint64_t Ellapsed = 0ull;
148076d346caSVladislav Khmelevsky   uint64_t ppid;
148176d346caSVladislav Khmelevsky   if (__bolt_instr_wait_forks) {
148276d346caSVladislav Khmelevsky     // Store parent pgid
148376d346caSVladislav Khmelevsky     ppid = -__getpgid(0);
148476d346caSVladislav Khmelevsky     // And leave parent process group
148576d346caSVladislav Khmelevsky     __setpgid(0, 0);
148676d346caSVladislav Khmelevsky   } else {
148776d346caSVladislav Khmelevsky     // Store parent pid
148876d346caSVladislav Khmelevsky     ppid = __getppid();
148976d346caSVladislav Khmelevsky     if (ppid == 1) {
149076d346caSVladislav Khmelevsky       // Parent already dead
149176d346caSVladislav Khmelevsky       goto out;
149276d346caSVladislav Khmelevsky     }
149376d346caSVladislav Khmelevsky   }
149476d346caSVladislav Khmelevsky 
149516a497c6SRafael Auler   ts.tv_sec = 1;
149616a497c6SRafael Auler   ts.tv_nsec = 0;
149716a497c6SRafael Auler   while (1) {
149816a497c6SRafael Auler     __nanosleep(&ts, &rem);
149976d346caSVladislav Khmelevsky     // This means our parent process or all its forks are dead,
150076d346caSVladislav Khmelevsky     // so no need for us to keep dumping.
150176d346caSVladislav Khmelevsky     if (__kill(ppid, 0) < 0) {
150276d346caSVladislav Khmelevsky       if (__bolt_instr_no_counters_clear)
150376d346caSVladislav Khmelevsky         __bolt_instr_data_dump();
150416a497c6SRafael Auler       break;
150516a497c6SRafael Auler     }
150676d346caSVladislav Khmelevsky 
150716a497c6SRafael Auler     if (++Ellapsed < __bolt_instr_sleep_time)
150816a497c6SRafael Auler       continue;
150976d346caSVladislav Khmelevsky 
151016a497c6SRafael Auler     Ellapsed = 0;
151116a497c6SRafael Auler     __bolt_instr_data_dump();
151276d346caSVladislav Khmelevsky     if (__bolt_instr_no_counters_clear == false)
151316a497c6SRafael Auler       __bolt_instr_clear_counters();
151416a497c6SRafael Auler   }
151576d346caSVladislav Khmelevsky 
151676d346caSVladislav Khmelevsky out:;
151716a497c6SRafael Auler   DEBUG(report("My parent process is dead, bye!\n"));
151816a497c6SRafael Auler   __exit(0);
151916a497c6SRafael Auler }
152016a497c6SRafael Auler 
152116a497c6SRafael Auler extern "C" void __bolt_instr_indirect_call();
152216a497c6SRafael Auler extern "C" void __bolt_instr_indirect_tailcall();
152316a497c6SRafael Auler 
152416a497c6SRafael Auler /// Initialization code
1525ad79d517SVasily Leonenko extern "C" void __attribute((force_align_arg_pointer)) __bolt_instr_setup() {
152616a497c6SRafael Auler   const uint64_t CountersStart =
152716a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[0]);
152816a497c6SRafael Auler   const uint64_t CountersEnd = alignTo(
152916a497c6SRafael Auler       reinterpret_cast<uint64_t>(&__bolt_instr_locations[__bolt_num_counters]),
153016a497c6SRafael Auler       0x1000);
153116a497c6SRafael Auler   DEBUG(reportNumber("replace mmap start: ", CountersStart, 16));
153216a497c6SRafael Auler   DEBUG(reportNumber("replace mmap stop: ", CountersEnd, 16));
153316a497c6SRafael Auler   assert (CountersEnd > CountersStart, "no counters");
153416a497c6SRafael Auler   // Maps our counters to be shared instead of private, so we keep counting for
153516a497c6SRafael Auler   // forked processes
153616a497c6SRafael Auler   __mmap(CountersStart, CountersEnd - CountersStart,
153716a497c6SRafael Auler          0x3 /*PROT_READ|PROT_WRITE*/,
153816a497c6SRafael Auler          0x31 /*MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED*/, -1, 0);
153916a497c6SRafael Auler 
1540*361f3b55SVladislav Khmelevsky   __bolt_ind_call_counter_func_pointer = __bolt_instr_indirect_call;
1541*361f3b55SVladislav Khmelevsky   __bolt_ind_tailcall_counter_func_pointer = __bolt_instr_indirect_tailcall;
154216a497c6SRafael Auler   // Conservatively reserve 100MiB shared pages
154316a497c6SRafael Auler   GlobalAlloc.setMaxSize(0x6400000);
154416a497c6SRafael Auler   GlobalAlloc.setShared(true);
154516a497c6SRafael Auler   GlobalWriteProfileMutex = new (GlobalAlloc, 0) Mutex();
154616a497c6SRafael Auler   if (__bolt_instr_num_ind_calls > 0)
154716a497c6SRafael Auler     GlobalIndCallCounters =
154816a497c6SRafael Auler         new (GlobalAlloc, 0) IndirectCallHashTable[__bolt_instr_num_ind_calls];
154916a497c6SRafael Auler 
155016a497c6SRafael Auler   if (__bolt_instr_sleep_time != 0) {
155176d346caSVladislav Khmelevsky     // Separate instrumented process to the own process group
155276d346caSVladislav Khmelevsky     if (__bolt_instr_wait_forks)
155376d346caSVladislav Khmelevsky       __setpgid(0, 0);
155476d346caSVladislav Khmelevsky 
1555c7306cc2SAmir Ayupov     if (long PID = __fork())
155616a497c6SRafael Auler       return;
155716a497c6SRafael Auler     watchProcess();
155816a497c6SRafael Auler   }
155916a497c6SRafael Auler }
156016a497c6SRafael Auler 
1561*361f3b55SVladislav Khmelevsky extern "C" __attribute((force_align_arg_pointer)) void
1562*361f3b55SVladislav Khmelevsky instrumentIndirectCall(uint64_t Target, uint64_t IndCallID) {
156316a497c6SRafael Auler   GlobalIndCallCounters[IndCallID].incrementVal(Target, GlobalAlloc);
156416a497c6SRafael Auler }
156516a497c6SRafael Auler 
156616a497c6SRafael Auler /// We receive as in-stack arguments the identifier of the indirect call site
156716a497c6SRafael Auler /// as well as the target address for the call
156816a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_call()
156916a497c6SRafael Auler {
157016a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1571*361f3b55SVladislav Khmelevsky                        "mov 0xa0(%%rsp), %%rdi\n"
1572*361f3b55SVladislav Khmelevsky                        "mov 0x98(%%rsp), %%rsi\n"
157316a497c6SRafael Auler                        "call instrumentIndirectCall\n"
157416a497c6SRafael Auler                        RESTORE_ALL
1575*361f3b55SVladislav Khmelevsky                        "ret\n"
157616a497c6SRafael Auler                        :::);
157716a497c6SRafael Auler }
157816a497c6SRafael Auler 
157916a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_indirect_tailcall()
158016a497c6SRafael Auler {
158116a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
1582*361f3b55SVladislav Khmelevsky                        "mov 0x98(%%rsp), %%rdi\n"
1583*361f3b55SVladislav Khmelevsky                        "mov 0x90(%%rsp), %%rsi\n"
158416a497c6SRafael Auler                        "call instrumentIndirectCall\n"
158516a497c6SRafael Auler                        RESTORE_ALL
1586*361f3b55SVladislav Khmelevsky                        "ret\n"
158716a497c6SRafael Auler                        :::);
158816a497c6SRafael Auler }
158916a497c6SRafael Auler 
159016a497c6SRafael Auler /// This is hooking ELF's entry, it needs to save all machine state.
159116a497c6SRafael Auler extern "C" __attribute((naked)) void __bolt_instr_start()
159216a497c6SRafael Auler {
159316a497c6SRafael Auler   __asm__ __volatile__(SAVE_ALL
159416a497c6SRafael Auler                        "call __bolt_instr_setup\n"
159516a497c6SRafael Auler                        RESTORE_ALL
1596ad79d517SVasily Leonenko                        "jmp __bolt_start_trampoline\n"
159716a497c6SRafael Auler                        :::);
159816a497c6SRafael Auler }
159916a497c6SRafael Auler 
160016a497c6SRafael Auler /// This is hooking into ELF's DT_FINI
160116a497c6SRafael Auler extern "C" void __bolt_instr_fini() {
1602ad79d517SVasily Leonenko   // Currently using assembly inline for trampoline function call
1603ad79d517SVasily Leonenko   // due to issues with function pointer dereferencing in case of
1604ad79d517SVasily Leonenko   // C function call.
1605ad79d517SVasily Leonenko   __asm__ __volatile__("call __bolt_fini_trampoline\n" :::);
160616a497c6SRafael Auler   if (__bolt_instr_sleep_time == 0)
160716a497c6SRafael Auler     __bolt_instr_data_dump();
160816a497c6SRafael Auler   DEBUG(report("Finished.\n"));
160962aa74f8SRafael Auler }
1610bbd9d610SAlexander Shaposhnikov 
16113b876cc3SAlexander Shaposhnikov #endif
16123b876cc3SAlexander Shaposhnikov 
16133b876cc3SAlexander Shaposhnikov #if defined(__APPLE__)
1614bbd9d610SAlexander Shaposhnikov 
1615a0dd5b05SAlexander Shaposhnikov extern "C" void __bolt_instr_data_dump() {
1616a0dd5b05SAlexander Shaposhnikov   ProfileWriterContext Ctx = readDescriptions();
1617a0dd5b05SAlexander Shaposhnikov 
1618a0dd5b05SAlexander Shaposhnikov   int FD = 2;
1619a0dd5b05SAlexander Shaposhnikov   BumpPtrAllocator Alloc;
1620a0dd5b05SAlexander Shaposhnikov   const uint8_t *FuncDesc = Ctx.FuncDescriptions;
1621a0dd5b05SAlexander Shaposhnikov   uint32_t bolt_instr_num_funcs = _bolt_instr_num_funcs_getter();
1622a0dd5b05SAlexander Shaposhnikov 
1623a0dd5b05SAlexander Shaposhnikov   for (int I = 0, E = bolt_instr_num_funcs; I < E; ++I) {
1624a0dd5b05SAlexander Shaposhnikov     FuncDesc = writeFunctionProfile(FD, Ctx, FuncDesc, Alloc);
1625a0dd5b05SAlexander Shaposhnikov     Alloc.clear();
1626a0dd5b05SAlexander Shaposhnikov     DEBUG(reportNumber("FuncDesc now: ", (uint64_t)FuncDesc, 16));
1627a0dd5b05SAlexander Shaposhnikov   }
1628a0dd5b05SAlexander Shaposhnikov   assert(FuncDesc == (void *)Ctx.Strings,
1629a0dd5b05SAlexander Shaposhnikov          "FuncDesc ptr must be equal to stringtable");
1630a0dd5b05SAlexander Shaposhnikov }
1631a0dd5b05SAlexander Shaposhnikov 
1632bbd9d610SAlexander Shaposhnikov // On OSX/iOS the final symbol name of an extern "C" function/variable contains
1633bbd9d610SAlexander Shaposhnikov // one extra leading underscore: _bolt_instr_setup -> __bolt_instr_setup.
16343b876cc3SAlexander Shaposhnikov extern "C"
16353b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__setup")))
16363b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
16373b876cc3SAlexander Shaposhnikov void _bolt_instr_setup() {
1638a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(SAVE_ALL :::);
16393b876cc3SAlexander Shaposhnikov 
1640a0dd5b05SAlexander Shaposhnikov   report("Hello!\n");
16413b876cc3SAlexander Shaposhnikov 
1642a0dd5b05SAlexander Shaposhnikov   __asm__ __volatile__(RESTORE_ALL :::);
16431cf23e5eSAlexander Shaposhnikov }
1644bbd9d610SAlexander Shaposhnikov 
16453b876cc3SAlexander Shaposhnikov extern "C"
16463b876cc3SAlexander Shaposhnikov __attribute__((section("__TEXT,__fini")))
16473b876cc3SAlexander Shaposhnikov __attribute__((force_align_arg_pointer))
16483b876cc3SAlexander Shaposhnikov void _bolt_instr_fini() {
1649a0dd5b05SAlexander Shaposhnikov   report("Bye!\n");
1650a0dd5b05SAlexander Shaposhnikov   __bolt_instr_data_dump();
1651e067f2adSAlexander Shaposhnikov }
1652e067f2adSAlexander Shaposhnikov 
1653bbd9d610SAlexander Shaposhnikov #endif
1654